Skip to main content

gd32e2_hal/
i2c.rs

1//! I²C master.
2//!
3//! 7-bit addressing. Transactions are `write`, `read` and `write_read` (the
4//! last joined by a repeated START), blocking or driven by interrupts; both
5//! lines must be open-drain.
6//!
7//! ```ignore
8//! let sda = parts.pb7.into_alternate_open_drain::<1>();
9//! let scl = parts.pb6.into_alternate_open_drain::<1>();
10//! let mut i2c = I2c::new(&mut rcu, dp.i2c0, sda, scl, I2cMode::standard(100.kHz()));
11//! ```
12//!
13//! # Driving a transaction by hand
14//!
15//! [`WriteTransfer`] and [`ReadTransfer`] are one way to do it; the primitives
16//! they are built from are public, so a handler can be written instead. A
17//! transaction is a sequence of phases, and the step a handler takes depends on
18//! which one it is in.
19//!
20//! Writing: [`write_start`](I2c::write_start), then on
21//! [`sbsend`](I2c::sbsend) [`write_addr`](I2c::write_addr), then on
22//! [`addsend`](I2c::addsend) [`clear_addsend`](I2c::clear_addsend), then one
23//! [`write_byte`](I2c::write_byte) per [`tbe`](I2c::tbe). `TBE` stays up with
24//! nothing left to feed, so `unlisten(Event::Byte)` after the last one and end
25//! on [`btc`](I2c::btc) with [`write_stop`](I2c::write_stop).
26//!
27//! Reading is the same up to `ADDSEND`, and then turns on the acknowledge:
28//! [`set_acken`](I2c::set_acken) governs the byte *already* being clocked in, so
29//! the NAK that ends the transaction has to be placed one byte early, and
30//! [`set_poap`](I2c::set_poap) moves it one further still. Both must stand
31//! before the START. Four lengths behave differently: one byte NAKs before
32//! `ADDSEND` is cleared; two ride on `POAP` and are taken together on `BTC`;
33//! three go straight to that tail; longer ones take bytes on
34//! [`rbne`](I2c::rbne) until three remain. Getting this wrong does not fail
35//! loudly — the target keeps driving the line and the bus hangs.
36
37use core::mem::ManuallyDrop;
38use core::ops::Deref;
39use core::ptr;
40
41use embedded_hal::i2c::{ErrorKind, ErrorType, NoAcknowledgeSource, Operation};
42
43use crate::gpio::{Alternate, OpenDrain, Pin};
44use crate::pac;
45use crate::rcu::{Enable, Rcu, Reset};
46use crate::time::Hertz;
47
48/// Smallest `CLKC` the hardware honours.
49const CLKC_MIN_STANDARD: u32 = 4;
50const CLKC_MIN_FAST: u32 = 1;
51
52/// Slowest `pclk1` each mode can be driven from, per the manual.
53const MIN_PCLK1_STANDARD_HZ: u32 = 2_000_000;
54const MIN_PCLK1_FAST_HZ: u32 = 8_000_000;
55const MIN_PCLK1_FAST_PLUS_HZ: u32 = 24_000_000;
56
57/// Longest SCL rise time the I²C specification allows per mode, in nanoseconds
58/// (NXP UM10204) — a property of the pulled-up line, not of the controller.
59const RISE_TIME_STANDARD_NS: u32 = 1000;
60const RISE_TIME_FAST_NS: u32 = 300;
61const RISE_TIME_FAST_PLUS_NS: u32 = 120;
62
63/// A peripheral that [`I2c`] can drive.
64pub trait Instance: Deref<Target = pac::i2c0::RegisterBlock> + Enable + Reset {}
65
66impl Instance for pac::I2c0 {}
67impl Instance for pac::I2c1 {}
68
69/// Marks a pin usable as `SDA` for `I2C`, in the right alternate function.
70pub trait SdaPin<I2C> {}
71/// Marks a pin usable as `SCL` for `I2C`, in the right alternate function.
72pub trait SclPin<I2C> {}
73
74macro_rules! i2c_pins {
75    ( $( $I2C:ty:
76        SDA: [ $($(#[$sda_cfg:meta])? $sda_p:literal $sda_n:literal : $sda_af:literal),* $(,)? ]
77        SCL: [ $($(#[$scl_cfg:meta])? $scl_p:literal $scl_n:literal : $scl_af:literal),* $(,)? ]
78    ),* $(,)? ) => {
79        $(
80            $($(#[$sda_cfg])? impl SdaPin<$I2C> for Pin<$sda_p, $sda_n, Alternate<$sda_af, OpenDrain>> {})*
81            $($(#[$scl_cfg])? impl SclPin<$I2C> for Pin<$scl_p, $scl_n, Alternate<$scl_af, OpenDrain>> {})*
82        )*
83    };
84}
85
86// PB10/PB11 at AF1 belong to a *different* I²C depending on the chip variant
87// (datasheet Table 2-14 footnotes): I2C0 on GD32E230x4, I2C1 on GD32E230x8.
88// They are therefore listed in the gated blocks, not here.
89//
90// The `pads_ge_*` gates say the package bonds the pin at all, and match the ones in
91// `gpio::Parts`.
92i2c_pins!(
93    pac::I2c0:
94        SDA: ['A' 10 : 4, #[cfg(pads_ge_24)] 'B' 7 : 1, #[cfg(pads_ge_48)] 'B' 9 : 1, 'F' 0 : 1]
95        SCL: ['A' 9 : 4, #[cfg(pads_ge_24)] 'B' 6 : 1, #[cfg(pads_ge_qfn32)] 'B' 8 : 1, 'F' 1 : 1],
96);
97
98// ---- (1) GD32E230x4 only: PB10/PB11 AF1 and PF6/PF7 AF0 are I2C0 ----
99#[cfg(chip_x4)]
100i2c_pins!(
101    pac::I2c0:
102        SDA: [#[cfg(pads_ge_48)] 'B' 11 : 1, #[cfg(pads_ge_48)] 'F' 7 : 0]
103        SCL: [#[cfg(pads_ge_48)] 'B' 10 : 1, #[cfg(pads_ge_48)] 'F' 6 : 0],
104);
105
106// ---- (3) GD32E230x8 only: I2C1 exists, and PB10/PB11 AF1 belong to it ----
107#[cfg(chip_x8)]
108i2c_pins!(
109    pac::I2c1:
110        SDA: ['A' 1 : 4, #[cfg(pads_ge_lqfp32)] 'A' 12 : 5, #[cfg(pads_ge_48)] 'B' 11 : 1, #[cfg(pads_ge_48)] 'B' 14 : 5, #[cfg(pads_ge_48)] 'F' 7 : 0]
111        SCL: ['A' 0 : 4, #[cfg(pads_ge_lqfp32)] 'A' 11 : 5, #[cfg(pads_ge_48)] 'B' 10 : 1, #[cfg(pads_ge_48)] 'B' 13 : 5, #[cfg(pads_ge_48)] 'F' 6 : 0]
112);
113
114/// Writes the bus timing to `CTL1`, `CKCFG` and `RT`, leaving the peripheral enabled.
115///
116/// `I2CCLK` takes `pclk1` in whole megahertz: `RISETIME` and the analog filter
117/// are measured in real time, so the absolute frequency is needed, not a divider.
118/// `CKCFG` and `I2CCLK` are only taken while `I2CEN` is clear, so the peripheral
119/// is disabled for the duration.
120///
121/// # Panics
122///
123/// If `pclk1` is below the minimum the mode needs (2 / 8 / 24 MHz), or if the
124/// requested frequency puts `CLKC` below what the hardware honours.
125fn apply_config<I2C: Instance>(i2c: &I2C, mode: I2cMode, pclk1: Hertz) {
126    let pclk1 = pclk1.to_Hz();
127    let pclk1_mhz = pclk1 / 1_000_000;
128    // t_rise / T_pclk1 + 1, and `1 ns × pclk1` is exactly `pclk1` in MHz.
129    let risetime = |t_rise_ns: u32| (pclk1_mhz * t_rise_ns / 1_000 + 1) as u8;
130
131    i2c.ctl0().modify(|_, w| w.i2cen().disabled());
132    // SAFETY: `pclk1` in whole megahertz, which the clock tree keeps within the
133    // field; a value below the mode's minimum is rejected by the asserts that
134    // follow, before `I2CEN` goes back up.
135    i2c.ctl1()
136        .modify(|_, w| unsafe { w.i2cclk().bits(pclk1_mhz as u8) });
137
138    match mode {
139        // Both halves of the period are `CLKC` cycles long, so the period is
140        // twice that.
141        I2cMode::Standard { frequency } => {
142            assert!(
143                pclk1 >= MIN_PCLK1_STANDARD_HZ,
144                "I2C standard mode needs pclk1 of at least 2 MHz"
145            );
146            let clkc = pclk1 / (2 * frequency.to_Hz());
147            assert!(
148                clkc >= CLKC_MIN_STANDARD,
149                "I2C frequency too high for this pclk1"
150            );
151            i2c.rt()
152                .write(|w| w.risetime().bits(risetime(RISE_TIME_STANDARD_NS)));
153            i2c.ckcfg()
154                .write(|w| w.fast().standard().clkc().bits(clkc as u16));
155        }
156        I2cMode::Fast {
157            frequency,
158            duty_cycle,
159        } => {
160            assert!(
161                pclk1 >= MIN_PCLK1_FAST_HZ,
162                "I2C fast mode needs pclk1 of at least 8 MHz"
163            );
164            i2c.rt()
165                .write(|w| w.risetime().bits(risetime(RISE_TIME_FAST_NS)));
166            write_fast_ckcfg(i2c, pclk1, frequency, duty_cycle);
167        }
168        I2cMode::FastPlus {
169            frequency,
170            duty_cycle,
171        } => {
172            assert!(
173                pclk1 >= MIN_PCLK1_FAST_PLUS_HZ,
174                "I2C fast mode plus needs pclk1 of at least 24 MHz"
175            );
176            i2c.rt()
177                .write(|w| w.risetime().bits(risetime(RISE_TIME_FAST_PLUS_NS)));
178            write_fast_ckcfg(i2c, pclk1, frequency, duty_cycle);
179            i2c.fmpcfg().write(|w| w.fmpen().set_bit());
180        }
181    }
182
183    i2c.ctl0().modify(|_, w| w.i2cen().enabled());
184}
185
186/// Writes `CKCFG` for the two fast modes, which share their formulas.
187///
188/// The duty cycle splits the period into `2 + 1` or `16 + 9` parts of `CLKC`
189/// cycles each.
190fn write_fast_ckcfg<I2C: Instance>(i2c: &I2C, pclk1: u32, frequency: Hertz, duty_cycle: DutyCycle) {
191    let parts = match duty_cycle {
192        DutyCycle::Ratio2to1 => 3,
193        DutyCycle::Ratio16to9 => 25,
194    };
195    let clkc = pclk1 / (parts * frequency.to_Hz());
196    assert!(
197        clkc >= CLKC_MIN_FAST,
198        "I2C frequency too high for this pclk1"
199    );
200    i2c.ckcfg().write(|w| {
201        let w = match duty_cycle {
202            DutyCycle::Ratio2to1 => w.dtcy().duty2(),
203            DutyCycle::Ratio16to9 => w.dtcy().duty16_9(),
204        };
205        w.fast().fast().clkc().bits(clkc as u16)
206    });
207}
208
209/// Ratio of the low to the high half of an SCL period (`DTCY`).
210#[derive(Clone, Copy, PartialEq, Eq)]
211#[cfg_attr(feature = "defmt", derive(defmt::Format))]
212#[allow(missing_docs)]
213pub enum DutyCycle {
214    Ratio2to1,
215    Ratio16to9,
216}
217
218/// Bus speed, and whatever else that speed implies.
219///
220/// Each variant has its own minimum `pclk1`: 2 / 8 / 24 MHz.
221#[derive(Clone, Copy, PartialEq, Eq)]
222#[cfg_attr(feature = "defmt", derive(defmt::Format))]
223pub enum I2cMode {
224    /// Up to 100 kHz, duty cycle fixed at 1:1.
225    Standard {
226        /// SCL frequency.
227        frequency: Hertz,
228    },
229    /// Up to 400 kHz.
230    Fast {
231        /// SCL frequency.
232        frequency: Hertz,
233        /// Shape of the SCL period.
234        duty_cycle: DutyCycle,
235    },
236    /// Up to 1 MHz; also enables the stronger line driver (`FMPCFG`).
237    FastPlus {
238        /// SCL frequency.
239        frequency: Hertz,
240        /// Shape of the SCL period.
241        duty_cycle: DutyCycle,
242    },
243}
244
245impl I2cMode {
246    /// Standard mode at `frequency`.
247    pub const fn standard(frequency: Hertz) -> Self {
248        Self::Standard { frequency }
249    }
250    /// Fast mode at `frequency`, with the given duty cycle.
251    pub const fn fast(frequency: Hertz, duty_cycle: DutyCycle) -> Self {
252        Self::Fast {
253            frequency,
254            duty_cycle,
255        }
256    }
257    /// Fast mode plus at `frequency`, with the given duty cycle.
258    pub const fn fast_plus(frequency: Hertz, duty_cycle: DutyCycle) -> Self {
259        Self::FastPlus {
260            frequency,
261            duty_cycle,
262        }
263    }
264}
265
266/// An error the peripheral flagged in `STAT0` (manual Table 17-3).
267///
268/// [`kind`] gives the portable classification.
269///
270/// [`kind`]: embedded_hal::i2c::Error::kind
271#[derive(Clone, Copy, Debug, PartialEq, Eq)]
272#[cfg_attr(feature = "defmt", derive(defmt::Format))]
273#[non_exhaustive]
274pub enum Error {
275    /// A START or STOP arrived where the protocol allows none (`BERR`).
276    Bus,
277    /// Another master won the bus; this one fell back to slave mode (`LOSTARB`).
278    ArbitrationLoss,
279    /// A byte was overwritten before being read, or needed before being written
280    /// (`OUERR`). Slave mode only, with clock stretching disabled.
281    Overrun,
282    /// Nobody acknowledged (`AERR`) — the ordinary answer from an empty address,
283    /// which is what bus scans rely on.
284    ///
285    /// One flag covers both cases, so the source comes from the step that ran.
286    NoAcknowledge(NoAcknowledgeSource),
287    /// The received PEC does not match the one computed locally (`PECERR`).
288    Pec,
289    /// An `SMBus` transaction exceeded its timeout (`SMBTO`).
290    SmbusTimeout,
291    /// An `SMBus` device pulled the alert line (`SMBALT`).
292    SmbusAlert,
293}
294
295impl embedded_hal::i2c::Error for Error {
296    fn kind(&self) -> ErrorKind {
297        match self {
298            Self::Bus => ErrorKind::Bus,
299            Self::ArbitrationLoss => ErrorKind::ArbitrationLoss,
300            Self::Overrun => ErrorKind::Overrun,
301            Self::NoAcknowledge(source) => ErrorKind::NoAcknowledge(*source),
302            // Nothing upstream describes these three.
303            Self::Pec | Self::SmbusTimeout | Self::SmbusAlert => ErrorKind::Other,
304        }
305    }
306}
307
308/// An I²C event that can raise an interrupt.
309#[derive(Clone, Copy, PartialEq, Eq)]
310#[cfg_attr(feature = "defmt", derive(defmt::Format))]
311pub enum Event {
312    /// The phase events `SBSEND`, `ADDSEND`, `ADD10SEND`, `STPDET` and `BTC`
313    /// (`EVIE`). Each is cleared by the step of the transaction that acts on it.
314    Protocol,
315    /// The byte events `TBE` and `RBNE` (`BUFIE`), on top of the phase ones.
316    ///
317    /// Listening raises `EVIE` as well, `BUFIE` doing nothing without it in
318    /// hardware. `TBE` is true whenever nothing is queued, so a handler feeding
319    /// a buffer must `unlisten` this once the last byte is out — which leaves
320    /// the phase events standing, and `BTC` then ends the transaction.
321    Byte,
322    /// Any of the `STAT0` error flags, which share one enable (`ERRIE`).
323    /// Cleared by [`take_error`](I2c::take_error), which a handler must call —
324    /// nothing else drains them.
325    Error,
326}
327
328/// A configured I²C master, owning the peripheral and its two pins.
329///
330/// Both lines are open-drain and need a pull-up.
331pub struct I2c<I2CX, SDA, SCL> {
332    i2c: I2CX,
333    sda_pin: SDA,
334    scl_pin: SCL,
335}
336
337impl<I2CX, SDA, SCL> I2c<I2CX, SDA, SCL>
338where
339    I2CX: Instance,
340    SDA: SdaPin<I2CX>,
341    SCL: SclPin<I2CX>,
342{
343    /// Enables the peripheral's clock, resets it and applies `mode`.
344    ///
345    /// The pins must already be open-drain in this I²C's alternate function;
346    /// [`release`](Self::release) hands them back.
347    ///
348    /// # Panics
349    ///
350    /// If `pclk1` is too slow for `mode` (2 / 8 / 24 MHz), or if `mode`'s
351    /// frequency is unreachable from it.
352    pub fn new(rcu: &mut Rcu, i2c: I2CX, sda_pin: SDA, scl_pin: SCL, mode: I2cMode) -> Self {
353        let pclk1 = rcu.clocks().pclk1();
354        I2CX::enable(rcu);
355        I2CX::reset(rcu);
356
357        apply_config(&i2c, mode, pclk1);
358        Self {
359            i2c,
360            sda_pin,
361            scl_pin,
362        }
363    }
364    /// Waits for a requested STOP to reach the bus, then returns the peripheral
365    /// and both pins, disabled, with its interrupts off and its clock stopped.
366    pub fn release(mut self, rcu: &mut Rcu) -> (I2CX, SDA, SCL) {
367        while self.i2c.ctl0().read().stop().bit_is_set() {}
368        self.unlisten(Event::Protocol);
369        self.unlisten(Event::Byte);
370        self.unlisten(Event::Error);
371        self.i2c.ctl0().modify(|_, w| w.i2cen().disabled());
372        I2CX::disable(rcu);
373        (self.i2c, self.sda_pin, self.scl_pin)
374    }
375}
376
377impl<I2CX, SDA, SCL> I2c<I2CX, SDA, SCL>
378where
379    I2CX: Instance,
380{
381    /// Whether the bus is in use, by another master or by a transaction of this
382    /// one (`I2CBSY`).
383    pub fn is_busy(&self) -> bool {
384        self.i2c.stat1().read().i2cbsy().is_busy()
385    }
386    /// START has gone out and the bus is waiting for the address (`SBSEND`).
387    pub fn sbsend(&self) -> bool {
388        self.i2c.stat0().read().sbsend().bit_is_set()
389    }
390    /// The addressed device answered; the data phase opens on
391    /// [`clear_addsend`](Self::clear_addsend) (`ADDSEND`).
392    pub fn addsend(&self) -> bool {
393        self.i2c.stat0().read().addsend().bit_is_set()
394    }
395    /// `DATA` will take the next byte (`TBE`).
396    ///
397    /// True whenever nothing is queued, so a handler listening for it must stop
398    /// once it has nothing left to send.
399    pub fn tbe(&self) -> bool {
400        self.i2c.stat0().read().tbe().bit_is_set()
401    }
402    /// The byte behind the one in `DATA` has arrived whole, and the peripheral
403    /// holds SCL until software catches up (`BTC`).
404    pub fn btc(&self) -> bool {
405        self.i2c.stat0().read().btc().bit_is_set()
406    }
407    /// A received byte is waiting in `DATA` (`RBNE`).
408    pub fn rbne(&self) -> bool {
409        self.i2c.stat0().read().rbne().bit_is_set()
410    }
411    /// Blocks until the bus is free.
412    ///
413    /// Only the first START needs this: `I2CBSY` stays set while this master owns
414    /// the bus, so waiting again before a repeated START would wait forever.
415    pub fn wait_idle(&self) {
416        while self.is_busy() {}
417    }
418
419    /// Raises START, which goes out as soon as the bus is free.
420    ///
421    /// On a bus this master already holds it is a repeated START, and the
422    /// transaction continues without a STOP in between.
423    pub fn write_start(&mut self) {
424        self.i2c.ctl0().modify(|_, w| w.start().start());
425    }
426    /// Puts the address into `DATA` with `read` as its direction bit.
427    ///
428    /// Also the second half of clearing `SBSEND`, the first being the read of
429    /// `STAT0` that observed it.
430    ///
431    /// # Panics
432    ///
433    /// If `address` does not fit in seven bits.
434    pub fn write_addr(&mut self, address: u8, read: bool) {
435        assert!(address <= 0x7F, "I2C address must be 7-bit");
436        self.i2c
437            .data()
438            .write(|w| w.trb().bits(address << 1 | read as u8));
439    }
440    /// Puts one byte into `DATA`, which also clears `TBE`.
441    pub fn write_byte(&mut self, byte: u8) {
442        self.i2c.data().write(|w| w.trb().bits(byte));
443    }
444    /// Takes the received byte out of `DATA`, which also clears `RBNE`.
445    pub fn read_byte(&mut self) -> u8 {
446        self.i2c.data().read().trb().bits()
447    }
448    /// Releases the bus with a STOP condition.
449    ///
450    /// Every path out of a transaction goes through here, failures included: a
451    /// skipped STOP leaves the master holding SCL, and the bus never goes idle
452    /// again.
453    pub fn write_stop(&mut self) {
454        self.i2c.ctl0().modify(|_, w| w.stop().stop());
455    }
456    /// Clears `ADDSEND`, which releases the bus into the data phase.
457    ///
458    /// Goes down on a read of `STAT0` then a read of `STAT1`, in that order;
459    /// skipping either leaves the transfer stalled.
460    pub fn clear_addsend(&mut self) {
461        self.i2c.stat0().read();
462        self.i2c.stat1().read();
463    }
464    /// Acknowledges or refuses the byte currently on the wire (`ACKEN`).
465    ///
466    /// It governs the byte already being clocked in, so the NAK that ends a read
467    /// has to stand one byte early — before `ADDSEND` is cleared on a one-byte
468    /// read, and before the last `BTC` otherwise.
469    pub fn set_acken(&mut self, ack: bool) {
470        self.i2c.ctl0().modify(|_, w| w.acken().bit(ack));
471    }
472    /// Moves the acknowledge one byte further along (`POAP`), for the two-byte
473    /// read where both bytes must be taken after the NAK is already placed.
474    ///
475    /// Like `ACKEN` it must stand before the START that begins the read.
476    pub fn set_poap(&mut self, next: bool) {
477        self.i2c.ctl0().modify(|_, w| w.poap().bit(next));
478    }
479
480    /// Sends START and the address, then waits for the device to answer.
481    ///
482    /// On a bus this master already holds, the START is a repeated one — hence no
483    /// [`wait_idle`](Self::wait_idle) here. Returns with `ADDSEND` still raised:
484    /// a short read has to write `ACKEN` before
485    /// [`clear_addsend`](Self::clear_addsend) opens the data phase. Failures
486    /// release the bus, so callers can propagate with `?`.
487    fn start(&mut self, address: u8, read: bool) -> Result<(), Error> {
488        self.write_start();
489
490        while self.i2c.stat0().read().sbsend().is_no_start() {
491            if let Some(err) = self.take_error_from(NoAcknowledgeSource::Unknown) {
492                self.write_stop();
493                return Err(err);
494            }
495        }
496        self.write_addr(address, read);
497
498        while self.i2c.stat0().read().addsend().is_not_match() {
499            if let Some(err) = self.take_error_from(NoAcknowledgeSource::Address) {
500                self.write_stop();
501                return Err(err);
502            }
503        }
504        Ok(())
505    }
506    /// Waits for a received byte to reach `DATA`, releasing the bus on error.
507    fn wait_rbne(&mut self) -> Result<(), Error> {
508        while self.i2c.stat0().read().rbne().is_empty() {
509            if let Some(err) = self.take_error_from(NoAcknowledgeSource::Data) {
510                self.write_stop();
511                return Err(err);
512            }
513        }
514        Ok(())
515    }
516    /// Waits for the byte in the shift register to finish, releasing the bus on
517    /// error.
518    ///
519    /// While receiving, `BTC` means a byte arrived behind the one still unread in
520    /// `DATA`, and the peripheral holds SCL low until software catches up.
521    fn wait_btc(&mut self) -> Result<(), Error> {
522        while self.i2c.stat0().read().btc().is_not_finished() {
523            if let Some(err) = self.take_error_from(NoAcknowledgeSource::Data) {
524                self.write_stop();
525                return Err(err);
526            }
527        }
528        Ok(())
529    }
530
531    /// Returns the first pending error, if any, clearing its flag.
532    ///
533    /// `source` says which step is running: one `AERR` covers both a dead address
534    /// and an unacknowledged data byte.
535    ///
536    /// `STAT0` flags are `rc_w0`, so clearing goes through `modify` — a `write`
537    /// would zero the flags it does not name and wipe them all.
538    fn take_error_from(&mut self, source: NoAcknowledgeSource) -> Option<Error> {
539        let stat = self.i2c.stat0().read();
540        if stat.berr().is_error() {
541            self.i2c.stat0().modify(|_, w| w.berr().no_error());
542            Some(Error::Bus)
543        } else if stat.lostarb().is_lost() {
544            self.i2c.stat0().modify(|_, w| w.lostarb().no_lost());
545            Some(Error::ArbitrationLoss)
546        } else if stat.aerr().is_error() {
547            self.i2c.stat0().modify(|_, w| w.aerr().no_error());
548            Some(Error::NoAcknowledge(source))
549        } else if stat.ouerr().is_overrun() {
550            self.i2c.stat0().modify(|_, w| w.ouerr().no_overrun());
551            Some(Error::Overrun)
552        } else if stat.pecerr().is_error() {
553            self.i2c.stat0().modify(|_, w| w.pecerr().no_error());
554            Some(Error::Pec)
555        } else if stat.smbto().is_timeout() {
556            self.i2c.stat0().modify(|_, w| w.smbto().no_timeout());
557            Some(Error::SmbusTimeout)
558        } else if stat.smbalt().is_alert() {
559            self.i2c.stat0().modify(|_, w| w.smbalt().no_alert());
560            Some(Error::SmbusAlert)
561        } else {
562            None
563        }
564    }
565
566    /// Writes `bytes` to the device at `address`, framed by START and STOP.
567    ///
568    /// `address` is the plain 7-bit value from the datasheet; the direction bit
569    /// is appended here. Blocks until the last byte is out and acknowledged, so
570    /// the bus is idle on return.
571    ///
572    /// # Errors
573    ///
574    /// [`Error::NoAcknowledge`] if nothing answers the address — with
575    /// [`NoAcknowledgeSource::Address`], which is how a bus scan finds devices —
576    /// or the device refuses a byte; [`Error::Bus`] or
577    /// [`Error::ArbitrationLoss`] on a bus fault.
578    ///
579    /// # Panics
580    ///
581    /// If `address` does not fit in seven bits (10-bit addressing is not
582    /// supported). Checked before the bus is touched.
583    pub fn write(&mut self, address: u8, bytes: &[u8]) -> Result<(), Error> {
584        assert!(address <= 0x7F, "I2C address must be 7-bit");
585
586        self.wait_idle();
587        self.write_phase(address, bytes)?;
588        self.write_stop();
589        Ok(())
590    }
591
592    /// Addresses the device for writing and clocks `bytes` out, leaving the bus
593    /// held: [`write`](Self::write) ends it with STOP,
594    /// [`write_read`](Self::write_read) with a repeated START.
595    fn write_phase(&mut self, address: u8, bytes: &[u8]) -> Result<(), Error> {
596        self.start(address, false)?;
597        self.clear_addsend();
598        self.write_bytes(bytes)?;
599
600        // With nothing sent there is no transfer to complete, and BTC never comes.
601        if !bytes.is_empty() {
602            self.wait_btc()?;
603        }
604        Ok(())
605    }
606
607    /// Clocks `bytes` out of an already addressed device.
608    fn write_bytes(&mut self, bytes: &[u8]) -> Result<(), Error> {
609        for byte in bytes {
610            while self.i2c.stat0().read().tbe().is_not_empty() {
611                if let Some(err) = self.take_error_from(NoAcknowledgeSource::Data) {
612                    self.write_stop();
613                    return Err(err);
614                }
615            }
616            self.i2c.data().write(|w| w.trb().bits(*byte));
617        }
618        Ok(())
619    }
620    /// Reads `bytes.len()` bytes from the device at `address`, framed by START
621    /// and STOP.
622    ///
623    /// An empty `bytes` is a no-op: a zero-byte transfer has no acknowledge to
624    /// end on.
625    ///
626    /// # Errors
627    ///
628    /// As for [`write`](Self::write); only the address can go unanswered.
629    ///
630    /// # Panics
631    ///
632    /// If `address` does not fit in seven bits.
633    pub fn read(&mut self, address: u8, bytes: &mut [u8]) -> Result<(), Error> {
634        assert!(address <= 0x7F, "I2C address must be 7-bit");
635        if bytes.is_empty() {
636            return Ok(());
637        }
638
639        self.wait_idle();
640        self.read_phase(address, bytes)
641    }
642
643    /// Addresses the device for reading and fills `bytes`, ending with STOP.
644    fn read_phase(&mut self, address: u8, bytes: &mut [u8]) -> Result<(), Error> {
645        let n = bytes.len();
646        self.read_slots(address, n, bytes.iter_mut())
647    }
648
649    /// The read phase over `n` byte slots, wherever they live: [`read`](Self::read)
650    /// passes one slice, [`transaction`] spreads one run of received bytes over
651    /// several buffers. `n` has to be known upfront — it decides where the NAK
652    /// falls.
653    ///
654    /// [`transaction`]: embedded_hal::i2c::I2c::transaction
655    fn read_slots<'a>(
656        &mut self,
657        address: u8,
658        n: usize,
659        mut slots: impl Iterator<Item = &'a mut u8>,
660    ) -> Result<(), Error> {
661        // Every `next()` below is matched against a slot counted in `n`.
662        match n {
663            0 => Ok(()),
664            1 => {
665                self.start(address, true)?;
666                // The byte starts arriving the moment ADDSEND goes down, so the
667                // NAK has to stand before that.
668                self.i2c.ctl0().modify(|_, w| w.acken().nak());
669                self.clear_addsend();
670                self.write_stop();
671
672                self.wait_rbne()?;
673                if let Some(slot) = slots.next() {
674                    *slot = self.read_byte();
675                }
676                Ok(())
677            }
678            2 => {
679                // POAP moves the acknowledge one byte along, so the NAK lands on
680                // the second byte. Must be set before START.
681                self.i2c.ctl0().modify(|_, w| w.poap().next());
682                let result = self.read_two(address, slots);
683                self.i2c.ctl0().modify(|_, w| w.poap().current());
684                result
685            }
686            _ => {
687                self.i2c.ctl0().modify(|_, w| w.acken().ack());
688                self.start(address, true)?;
689                self.clear_addsend();
690
691                // Up to the last three bytes: take each one as it lands.
692                for _ in 0..n - 3 {
693                    self.wait_rbne()?;
694                    if let Some(slot) = slots.next() {
695                        *slot = self.read_byte();
696                    }
697                }
698
699                // Byte N-2 is left in DATA on purpose: once N-1 arrives behind it
700                // the peripheral holds SCL, so this ACKEN cannot be late.
701                self.wait_btc()?;
702                self.i2c.ctl0().modify(|_, w| w.acken().nak());
703                if let Some(slot) = slots.next() {
704                    *slot = self.read_byte();
705                }
706
707                // Reading N-2 let the last byte in; SCL is stretched again, and
708                // STOP goes out before it is read.
709                self.wait_btc()?;
710                self.write_stop();
711                for slot in slots {
712                    *slot = self.read_byte();
713                }
714                Ok(())
715            }
716        }
717    }
718
719    /// The two-byte read, split out so `POAP` is restored on every path.
720    fn read_two<'a>(
721        &mut self,
722        address: u8,
723        slots: impl Iterator<Item = &'a mut u8>,
724    ) -> Result<(), Error> {
725        self.start(address, true)?;
726        self.i2c.ctl0().modify(|_, w| w.acken().nak());
727        self.clear_addsend();
728
729        // Neither byte is read until both have arrived, and STOP goes out before
730        // either leaves DATA.
731        self.wait_btc()?;
732        self.write_stop();
733        for slot in slots {
734            *slot = self.read_byte();
735        }
736        Ok(())
737    }
738
739    /// Writes `write`, then reads into `read`, joined by a repeated START.
740    ///
741    /// This is how a register-addressed device is read: the write phase moves its
742    /// pointer, the read phase takes what the pointer names. A
743    /// [`write`](Self::write) then a [`read`](Self::read) puts a STOP in between,
744    /// which some devices treat as the end of the register access.
745    ///
746    /// An empty `read` degenerates to [`write`](Self::write), an empty `write`
747    /// to [`read`](Self::read).
748    ///
749    /// # Errors
750    ///
751    /// As for [`write`](Self::write), from either phase.
752    ///
753    /// # Panics
754    ///
755    /// If `address` does not fit in seven bits.
756    pub fn write_read(&mut self, address: u8, write: &[u8], read: &mut [u8]) -> Result<(), Error> {
757        assert!(address <= 0x7F, "I2C address must be 7-bit");
758
759        self.wait_idle();
760        self.write_phase(address, write)?;
761
762        if read.is_empty() {
763            self.write_stop();
764            return Ok(());
765        }
766        // No STOP in between: the read phase's START is a repeated one.
767        self.read_phase(address, read)
768    }
769
770    /// Returns the pending error, if any, and clears it.
771    ///
772    /// The acknowledge for [`Event::Error`]: the flag is what holds the
773    /// interrupt request up, so a handler that skips this re-enters forever.
774    /// One error per call — with two pending, the second survives for the next.
775    /// A NACK reports [`NoAcknowledgeSource::Unknown`], the phase it arrived in
776    /// being known only to whoever drives the transaction.
777    pub fn take_error(&mut self) -> Option<Error> {
778        self.take_error_from(NoAcknowledgeSource::Unknown)
779    }
780
781    /// Raises an interrupt on `event`, which still has to be unmasked in the
782    /// NVIC.
783    ///
784    /// [`Event::Byte`] raises `EVIE` along with `BUFIE`, so it covers
785    /// [`Event::Protocol`] too.
786    pub fn listen(&mut self, event: Event) {
787        match event {
788            Event::Protocol => self.i2c.ctl1().modify(|_, w| w.evie().enabled()),
789            Event::Byte => self
790                .i2c
791                .ctl1()
792                .modify(|_, w| w.evie().enabled().bufie().enabled()),
793            Event::Error => self.i2c.ctl1().modify(|_, w| w.errie().enabled()),
794        }
795    }
796    /// Stops raising an interrupt on `event`.
797    ///
798    /// [`Event::Protocol`] takes `BUFIE` down with it: byte events cannot stand
799    /// on their own in hardware. Dropping only those is
800    /// `unlisten(Event::Byte)`.
801    pub fn unlisten(&mut self, event: Event) {
802        match event {
803            Event::Protocol => self
804                .i2c
805                .ctl1()
806                .modify(|_, w| w.evie().disabled().bufie().disabled()),
807            Event::Byte => self.i2c.ctl1().modify(|_, w| w.bufie().disabled()),
808            Event::Error => self.i2c.ctl1().modify(|_, w| w.errie().disabled()),
809        }
810    }
811    /// Whether `event` is being listened for.
812    pub fn is_listening(&self, event: Event) -> bool {
813        let ctl1 = self.i2c.ctl1().read();
814        match event {
815            Event::Protocol => ctl1.evie().is_enabled(),
816            Event::Byte => ctl1.evie().is_enabled() && ctl1.bufie().is_enabled(),
817            Event::Error => ctl1.errie().is_enabled(),
818        }
819    }
820
821    /// Starts a write of `buf` to `address`, to be driven by interrupts.
822    ///
823    /// Takes the peripheral with it; both come back from
824    /// [`release`](WriteTransfer::release). An empty `buf` still addresses the
825    /// device, which is how a bus scan probes for one. Blocks only until the bus
826    /// is free, then raises START and returns.
827    ///
828    /// Arms the interrupts itself and keeps re-arming them as the phases change,
829    /// so `listen` beforehand is neither needed nor respected.
830    ///
831    /// # Panics
832    ///
833    /// If `address` does not fit in seven bits.
834    pub fn start_write(mut self, address: u8, buf: &'static [u8]) -> WriteTransfer<I2CX, SDA, SCL> {
835        assert!(address <= 0x7F, "I2C address must be 7-bit");
836        self.wait_idle();
837        self.listen(Event::Error);
838        self.listen(Event::Byte);
839        self.write_start();
840        WriteTransfer {
841            i2c: self,
842            address: address << 1,
843            buf,
844            pos: 0,
845            state: WriteState::Sbsend,
846        }
847    }
848    /// Starts a read of `buf.len()` bytes from `address`, to be driven by
849    /// interrupts.
850    ///
851    /// Takes the peripheral with it; both come back from
852    /// [`release`](ReadTransfer::release). An empty `buf` finishes immediately
853    /// without touching the bus — a zero-byte read has no acknowledge to end on.
854    /// Blocks only until the bus is free, then raises START and returns.
855    ///
856    /// Arms the interrupts itself and keeps re-arming them as the phases change,
857    /// so `listen` beforehand is neither needed nor respected.
858    ///
859    /// # Panics
860    ///
861    /// If `address` does not fit in seven bits.
862    pub fn start_read(
863        mut self,
864        address: u8,
865        buf: &'static mut [u8],
866    ) -> ReadTransfer<I2CX, SDA, SCL> {
867        assert!(address <= 0x7F, "I2C address must be 7-bit");
868        if buf.is_empty() {
869            return ReadTransfer {
870                i2c: self,
871                address: address << 1 | 1,
872                buf,
873                pos: 0,
874                state: ReadState::Done(Ok(())),
875            };
876        }
877
878        self.wait_idle();
879        // Both of these must stand before START: ACKEN governs the byte already
880        // on the wire, and POAP moves it one further along.
881        self.set_acken(buf.len() > 2);
882        self.set_poap(buf.len() == 2);
883        self.listen(Event::Error);
884        self.listen(Event::Byte);
885        self.write_start();
886        ReadTransfer {
887            i2c: self,
888            address: address << 1 | 1,
889            buf,
890            pos: 0,
891            state: ReadState::Sbsend,
892        }
893    }
894}
895
896/// Where a [`WriteTransfer`] stands: the flag it is waiting for.
897#[derive(Clone, Copy)]
898enum WriteState {
899    /// START is out; `SBSEND` calls for the address.
900    Sbsend,
901    /// The address is out; `ADDSEND` opens the data phase.
902    Addsend,
903    /// Feeding `DATA`, one byte per `TBE`.
904    Sending,
905    /// Everything is fed; `BTC` says the wire is clear for STOP.
906    Btc,
907    /// Over, carrying the outcome the handler reached.
908    Done(Result<(), Error>),
909}
910
911/// A write driven by interrupts, owning the peripheral and the buffer.
912///
913/// Built by [`I2c::start_write`]. The handler for both I²C vectors calls
914/// [`on_interrupt`](Self::on_interrupt); the transfer is over once
915/// [`is_done`](Self::is_done) says so, and [`release`](Self::release) takes it
916/// apart.
917#[must_use = "dropping the transfer aborts it"]
918pub struct WriteTransfer<I2CX, SDA, SCL>
919where
920    I2CX: Instance,
921{
922    i2c: I2c<I2CX, SDA, SCL>,
923    address: u8,
924    buf: &'static [u8],
925    pos: usize,
926    state: WriteState,
927}
928
929impl<I2CX, SDA, SCL> WriteTransfer<I2CX, SDA, SCL>
930where
931    I2CX: Instance,
932{
933    /// Advances the transfer by one step. Call from both I²C interrupt
934    /// handlers.
935    ///
936    /// Reads the flags itself rather than trusting which vector it was entered
937    /// from, so a wakeup this step has nothing to do with is simply ignored.
938    pub fn on_interrupt(&mut self) {
939        if self.is_done() {
940            return;
941        }
942        if let Some(err) = self.i2c.take_error() {
943            self.i2c.write_stop();
944            self.finish(Err(err));
945            return;
946        }
947
948        match self.state {
949            WriteState::Sbsend if self.i2c.sbsend() => {
950                self.i2c.write_byte(self.address);
951                self.state = WriteState::Addsend;
952            }
953            WriteState::Addsend if self.i2c.addsend() => {
954                self.i2c.clear_addsend();
955                if self.buf.is_empty() {
956                    // Addressing was the whole transfer; BTC never comes.
957                    self.i2c.write_stop();
958                    self.finish(Ok(()));
959                } else {
960                    self.state = WriteState::Sending;
961                }
962            }
963            WriteState::Sending if self.i2c.tbe() => {
964                self.i2c.write_byte(self.buf[self.pos]);
965                self.pos += 1;
966                if self.pos == self.buf.len() {
967                    // TBE stays up with nothing left to feed, so stop listening
968                    // for it and wait out the byte in the shift register.
969                    self.i2c.unlisten(Event::Byte);
970                    self.state = WriteState::Btc;
971                }
972            }
973            WriteState::Btc if self.i2c.btc() => {
974                self.i2c.write_stop();
975                self.finish(Ok(()));
976            }
977            _ => {}
978        }
979    }
980    /// Whether the transfer has ended, successfully or not.
981    pub fn is_done(&self) -> bool {
982        matches!(self.state, WriteState::Done(_))
983    }
984    /// Gives back the peripheral, the buffer and the outcome.
985    ///
986    /// `None` means the transfer was taken apart while still running, in which
987    /// case the bus is released with a STOP first.
988    #[allow(clippy::type_complexity)]
989    pub fn release(
990        self,
991    ) -> (
992        I2c<I2CX, SDA, SCL>,
993        &'static [u8],
994        Option<Result<(), Error>>,
995    ) {
996        let mut this = ManuallyDrop::new(self);
997        let outcome = if let WriteState::Done(result) = this.state {
998            Some(result)
999        } else {
1000            this.abort();
1001            None
1002        };
1003        // SAFETY: `this` is never dropped, so the field is read exactly once.
1004        let i2c = unsafe { ptr::read(&raw const this.i2c) };
1005        (i2c, this.buf, outcome)
1006    }
1007    /// Stops every interrupt and records the outcome. The bus is released by
1008    /// the caller, which knows whether a STOP has gone out already.
1009    fn finish(&mut self, result: Result<(), Error>) {
1010        self.i2c.unlisten(Event::Protocol);
1011        self.i2c.unlisten(Event::Error);
1012        self.state = WriteState::Done(result);
1013    }
1014    /// Cuts a running transfer short, leaving the bus idle.
1015    fn abort(&mut self) {
1016        self.i2c.write_stop();
1017        self.finish(Ok(()));
1018    }
1019}
1020
1021impl<I2CX, SDA, SCL> Drop for WriteTransfer<I2CX, SDA, SCL>
1022where
1023    I2CX: Instance,
1024{
1025    fn drop(&mut self) {
1026        if !self.is_done() {
1027            self.abort();
1028        }
1029    }
1030}
1031
1032/// Where a [`ReadTransfer`] stands: the flag it is waiting for.
1033///
1034/// The tail states exist because `ACKEN` governs the byte already on the wire,
1035/// one ahead of the one being read — the manual's "Solution B".
1036#[derive(Clone, Copy)]
1037enum ReadState {
1038    /// START is out; `SBSEND` calls for the address.
1039    Sbsend,
1040    /// The address is out; `ADDSEND` opens the data phase.
1041    Addsend,
1042    /// Three or more bytes to go: take each one as it lands on `RBNE`.
1043    Receiving,
1044    /// Three left. `BTC` means two of them are in, so the NAK cannot be late.
1045    Penultimate,
1046    /// Two left, both already arrived: STOP goes out before either is read.
1047    Tail,
1048    /// The one-byte read: its NAK stands, STOP is out, `RBNE` is all that's
1049    /// left.
1050    Single,
1051    /// Over, carrying the outcome the handler reached.
1052    Done(Result<(), Error>),
1053}
1054
1055/// A read driven by interrupts, owning the peripheral and the buffer.
1056///
1057/// Built by [`I2c::start_read`]. The handler for both I²C vectors calls
1058/// [`on_interrupt`](Self::on_interrupt); the transfer is over once
1059/// [`is_done`](Self::is_done) says so, and [`release`](Self::release) takes it
1060/// apart.
1061#[must_use = "dropping the transfer aborts it"]
1062pub struct ReadTransfer<I2CX, SDA, SCL>
1063where
1064    I2CX: Instance,
1065{
1066    i2c: I2c<I2CX, SDA, SCL>,
1067    address: u8,
1068    buf: &'static mut [u8],
1069    pos: usize,
1070    state: ReadState,
1071}
1072
1073impl<I2CX, SDA, SCL> ReadTransfer<I2CX, SDA, SCL>
1074where
1075    I2CX: Instance,
1076{
1077    /// Advances the transfer by one step. Call from both I²C interrupt
1078    /// handlers.
1079    ///
1080    /// Reads the flags itself rather than trusting which vector it was entered
1081    /// from, so a wakeup this step has nothing to do with is simply ignored.
1082    pub fn on_interrupt(&mut self) {
1083        if self.is_done() {
1084            return;
1085        }
1086        if let Some(err) = self.i2c.take_error() {
1087            self.i2c.write_stop();
1088            self.finish(Err(err));
1089            return;
1090        }
1091
1092        match self.state {
1093            ReadState::Sbsend if self.i2c.sbsend() => {
1094                self.i2c.write_byte(self.address);
1095                self.state = ReadState::Addsend;
1096            }
1097            ReadState::Addsend if self.i2c.addsend() => {
1098                self.state = match self.buf.len() {
1099                    1 => {
1100                        // The byte starts arriving the moment ADDSEND goes
1101                        // down, so the NAK has to stand before that.
1102                        self.i2c.set_acken(false);
1103                        self.i2c.clear_addsend();
1104                        self.i2c.write_stop();
1105                        ReadState::Single
1106                    }
1107                    2 => {
1108                        self.i2c.set_acken(false);
1109                        self.i2c.clear_addsend();
1110                        self.i2c.unlisten(Event::Byte);
1111                        ReadState::Tail
1112                    }
1113                    3 => {
1114                        // Nothing to take before the tail: the three bytes are
1115                        // exactly what the last two steps handle.
1116                        self.i2c.clear_addsend();
1117                        self.i2c.unlisten(Event::Byte);
1118                        ReadState::Penultimate
1119                    }
1120                    _ => {
1121                        self.i2c.clear_addsend();
1122                        ReadState::Receiving
1123                    }
1124                };
1125            }
1126            ReadState::Single if self.i2c.rbne() => {
1127                self.buf[0] = self.i2c.read_byte();
1128                self.pos = 1;
1129                self.finish(Ok(()));
1130            }
1131            ReadState::Receiving if self.i2c.rbne() => {
1132                self.buf[self.pos] = self.i2c.read_byte();
1133                self.pos += 1;
1134                if self.pos == self.buf.len() - 3 {
1135                    // From here on the steps wait for BTC, and RBNE would only
1136                    // wake the handler between them.
1137                    self.i2c.unlisten(Event::Byte);
1138                    self.state = ReadState::Penultimate;
1139                }
1140            }
1141            ReadState::Penultimate if self.i2c.btc() => {
1142                // Byte N-2 stayed in DATA on purpose: with N-1 behind it the
1143                // peripheral holds SCL, so this ACKEN cannot be late.
1144                self.i2c.set_acken(false);
1145                self.buf[self.pos] = self.i2c.read_byte();
1146                self.pos += 1;
1147                self.state = ReadState::Tail;
1148            }
1149            ReadState::Tail if self.i2c.btc() => {
1150                // Both remaining bytes have arrived; STOP goes out before
1151                // either leaves DATA.
1152                self.i2c.write_stop();
1153                while self.pos < self.buf.len() {
1154                    self.buf[self.pos] = self.i2c.read_byte();
1155                    self.pos += 1;
1156                }
1157                self.finish(Ok(()));
1158            }
1159            _ => {}
1160        }
1161    }
1162    /// Whether the transfer has ended, successfully or not.
1163    pub fn is_done(&self) -> bool {
1164        matches!(self.state, ReadState::Done(_))
1165    }
1166    /// Gives back the peripheral, the buffer and the outcome.
1167    ///
1168    /// `None` means the transfer was taken apart while still running, in which
1169    /// case the bus is released with a STOP first.
1170    #[allow(clippy::type_complexity)]
1171    pub fn release(
1172        self,
1173    ) -> (
1174        I2c<I2CX, SDA, SCL>,
1175        &'static mut [u8],
1176        Option<Result<(), Error>>,
1177    ) {
1178        let mut this = ManuallyDrop::new(self);
1179        let outcome = if let ReadState::Done(result) = this.state {
1180            Some(result)
1181        } else {
1182            this.abort();
1183            None
1184        };
1185        // SAFETY: `this` is never dropped, so the fields are read exactly once.
1186        let (i2c, buf) = unsafe {
1187            (
1188                ptr::read(&raw const this.i2c),
1189                ptr::read(&raw const this.buf),
1190            )
1191        };
1192        (i2c, buf, outcome)
1193    }
1194    /// Stops every interrupt, restores `POAP` and records the outcome. The bus
1195    /// is released by the caller, which knows whether a STOP has gone out
1196    /// already.
1197    fn finish(&mut self, result: Result<(), Error>) {
1198        self.i2c.set_poap(false);
1199        self.i2c.unlisten(Event::Protocol);
1200        self.i2c.unlisten(Event::Error);
1201        self.state = ReadState::Done(result);
1202    }
1203    /// Cuts a running transfer short, leaving the bus idle.
1204    fn abort(&mut self) {
1205        self.i2c.write_stop();
1206        self.finish(Ok(()));
1207    }
1208}
1209
1210impl<I2CX, SDA, SCL> Drop for ReadTransfer<I2CX, SDA, SCL>
1211where
1212    I2CX: Instance,
1213{
1214    fn drop(&mut self) {
1215        if !self.is_done() {
1216            self.abort();
1217        }
1218    }
1219}
1220
1221impl<I2CX, SDA, SCL> ErrorType for I2c<I2CX, SDA, SCL>
1222where
1223    I2CX: Instance,
1224{
1225    type Error = Error;
1226}
1227
1228/// Whether two operations run in the same direction, and so belong to one
1229/// addressed phase.
1230fn same_direction(a: &Operation<'_>, b: &Operation<'_>) -> bool {
1231    matches!(
1232        (a, b),
1233        (Operation::Read(_), Operation::Read(_)) | (Operation::Write(_), Operation::Write(_))
1234    )
1235}
1236
1237impl<I2CX, SDA, SCL> embedded_hal::i2c::I2c for I2c<I2CX, SDA, SCL>
1238where
1239    I2CX: Instance,
1240{
1241    /// Per the trait's contract: neighbouring operations of the same direction
1242    /// join into one addressed phase, a change of direction inserts a repeated
1243    /// START, and only the end carries a STOP.
1244    ///
1245    /// # Panics
1246    ///
1247    /// If `address` does not fit in seven bits, or if a `Read` is followed by
1248    /// further operations — ending a read early needs a repeated START in place
1249    /// of its STOP, which the read sequences here do not express. `[Write.., Read]`
1250    /// works.
1251    fn transaction(&mut self, address: u8, operations: &mut [Operation<'_>]) -> Result<(), Error> {
1252        assert!(address <= 0x7F, "I2C address must be 7-bit");
1253        if operations.is_empty() {
1254            return Ok(());
1255        }
1256        let phases = operations.chunk_by(same_direction).count();
1257
1258        self.wait_idle();
1259        for (i, phase) in operations.chunk_by_mut(same_direction).enumerate() {
1260            let last = i + 1 == phases;
1261            match phase.first() {
1262                Some(Operation::Write(_)) => {
1263                    self.start(address, false)?;
1264                    self.clear_addsend();
1265                    let mut sent = false;
1266                    for op in phase.iter() {
1267                        if let Operation::Write(bytes) = op {
1268                            self.write_bytes(bytes)?;
1269                            sent |= !bytes.is_empty();
1270                        }
1271                    }
1272                    if sent {
1273                        self.wait_btc()?;
1274                    }
1275                    if last {
1276                        self.write_stop();
1277                    }
1278                }
1279                Some(Operation::Read(_)) => {
1280                    assert!(last, "I2C read must be the last operation of a transaction");
1281                    let n = phase
1282                        .iter()
1283                        .map(|op| match op {
1284                            Operation::Read(buf) => buf.len(),
1285                            Operation::Write(_) => 0,
1286                        })
1287                        .sum();
1288                    let slots = phase
1289                        .iter_mut()
1290                        .filter_map(|op| match op {
1291                            Operation::Read(buf) => Some(buf),
1292                            Operation::Write(_) => None,
1293                        })
1294                        .flat_map(|buf| buf.iter_mut());
1295                    self.read_slots(address, n, slots)?;
1296                }
1297                None => {}
1298            }
1299        }
1300        Ok(())
1301    }
1302
1303    fn read(&mut self, address: u8, bytes: &mut [u8]) -> Result<(), Error> {
1304        self.read(address, bytes)
1305    }
1306    fn write(&mut self, address: u8, bytes: &[u8]) -> Result<(), Error> {
1307        self.write(address, bytes)
1308    }
1309    fn write_read(&mut self, address: u8, bytes: &[u8], buffer: &mut [u8]) -> Result<(), Error> {
1310        self.write_read(address, bytes, buffer)
1311    }
1312}