Skip to main content

esp_hal/i2c/lp_i2c/
rtc_i2c.rs

1//! RTC_I2C implementation of the low-power I2C driver.
2//!
3//! This peripheral transfers through a single data register and always needs a slave sub-register
4//! address.
5
6use crate::{
7    gpio::{
8        LpPin,
9        lp_io::{LpFunction, low_level},
10    },
11    i2c::lp_i2c::{Error, LpI2c, Scl, Sda},
12    peripherals::{GPIO, RTC_IO, SENS},
13    system::{Peripheral, PeripheralClockControl},
14    time::Duration,
15};
16
17fn bind_pin(pin: &impl LpPin, function: LpFunction) {
18    let lp = pin.lp_number();
19
20    GPIO::regs()
21        .pin(pin.number() as usize)
22        .modify(|_, w| w.pad_driver().bit(true));
23    RTC_IO::regs()
24        .touch_pad(lp as usize)
25        .modify(|_, w| w.rue().bit(true).rde().bit(false));
26    RTC_IO::regs()
27        .rtc_gpio_enable_w1ts()
28        .write(|w| unsafe { w.rtc_gpio_enable_w1ts().bits(1 << lp) });
29    low_level::set_config(lp, true, true, function);
30}
31
32for_each_lp_function! {
33    (($_func:ident, SAR_I2C_SCL_n, $n:literal), $gpio:ident, $af:ident, $_lp_in:tt $_lp_out:tt) => {
34        impl Scl for crate::peripherals::$gpio<'_> {
35            fn connect_scl(&self) {
36                bind_pin(self, LpFunction::$af);
37                // sar_i2c_io holds both selector fields; update only this one.
38                RTC_IO::regs().sar_i2c_io().modify(|_, w| unsafe {
39                    w.sar_i2c_scl_sel().bits($n)
40                });
41            }
42        }
43    };
44    (($_func:ident, SAR_I2C_SDA_n, $n:literal), $gpio:ident, $af:ident, $_lp_in:tt $_lp_out:tt) => {
45        impl Sda for crate::peripherals::$gpio<'_> {
46            fn connect_sda(&self) {
47                bind_pin(self, LpFunction::$af);
48                // sar_i2c_io holds both selector fields; update only this one.
49                RTC_IO::regs().sar_i2c_io().modify(|_, w| unsafe {
50                    w.sar_i2c_sda_sel().bits($n)
51                });
52            }
53        }
54    };
55}
56
57impl<'d> LpI2c<'d> {
58    pub(super) fn init(&mut self) {
59        self.i2c.register_block().ctrl().reset();
60        SENS::regs().sar_i2c_ctrl().reset();
61
62        PeripheralClockControl::set_reset(Peripheral::RtcI2c, true);
63        self.i2c
64            .register_block()
65            .ctrl()
66            .modify(|_, w| w.i2c_reset().set_bit());
67        // The state machine does not always come out of reset when the pulse is shorter than this.
68        crate::rom::ets_delay_us(20);
69        self.i2c
70            .register_block()
71            .ctrl()
72            .modify(|_, w| w.i2c_reset().clear_bit());
73        PeripheralClockControl::set_reset(Peripheral::RtcI2c, false);
74
75        // Enable internal open-drain for SDA and SCL
76        self.i2c.register_block().ctrl().modify(|_, w| {
77            w.sda_force_out().clear_bit();
78            w.scl_force_out().clear_bit()
79        });
80
81        PeripheralClockControl::set_enabled_untracked(Peripheral::RtcI2c, true);
82
83        self.i2c
84            .register_block()
85            .ctrl()
86            .modify(|_, w| w.ms_mode().set_bit());
87        self.i2c
88            .register_block()
89            .ctrl()
90            .modify(|_, w| w.i2c_ctrl_clk_gate_en().set_bit());
91    }
92
93    pub(super) fn configure(&mut self, config: &Config) -> Result<(), ConfigError> {
94        let ticks = nanos_to_clock(config.timeout.as_micros().saturating_mul(1_000));
95
96        // The register field is 20 bits wide.
97        if ticks > (1 << 20) - 1 {
98            return Err(ConfigError::TimeoutTooLong);
99        }
100
101        self.i2c
102            .register_block()
103            .scl_low()
104            .write(|w| unsafe { w.period().bits(config.timing.scl_low_period) });
105        self.i2c
106            .register_block()
107            .scl_high()
108            .write(|w| unsafe { w.period().bits(config.timing.scl_high_period) });
109        self.i2c
110            .register_block()
111            .sda_duty()
112            .write(|w| unsafe { w.num().bits(config.timing.sda_duty) });
113        self.i2c
114            .register_block()
115            .scl_start_period()
116            .write(|w| unsafe { w.scl_start_period().bits(config.timing.scl_start_period) });
117        self.i2c
118            .register_block()
119            .scl_stop_period()
120            .write(|w| unsafe { w.scl_stop_period().bits(config.timing.scl_stop_period) });
121
122        self.i2c
123            .register_block()
124            .to()
125            .write(|w| unsafe { w.time_out().bits(ticks) });
126
127        Ok(())
128    }
129
130    pub(super) fn write_bytes(
131        &mut self,
132        address: u8,
133        register: u8,
134        data: &[u8],
135    ) -> Result<(), Error> {
136        let sens = unsafe { crate::pac::SENS::steal() };
137
138        if data.len() > u8::MAX as usize - 2 {
139            return Err(Error::TransactionSizeLimitExceeded);
140        }
141
142        self.write_cmd(
143            0,
144            Command::Write {
145                ack_exp: Ack::Ack,
146                ack_check_en: true,
147                // Slave addr + Reg addr + data
148                length: 2 + (data.len() as u8),
149            },
150        );
151        self.write_cmd(1, Command::Stop);
152
153        self.clear_interrupts();
154
155        let ctrl = {
156            let mut result = 0;
157            // Configure slave address.
158            result |= address as u32;
159            // Set slave register.
160            result |= (register as u32) << 11;
161            // Set first data
162            result |= (data[0] as u32) << 19;
163            result |= 1u32 << 27; // Write
164            result
165        };
166        sens.sar_i2c_ctrl()
167            .write(|w| unsafe { w.sar_i2c_ctrl().bits(ctrl) });
168
169        // Start transmission.
170        sens.sar_i2c_ctrl().modify(|_, w| {
171            w.sar_i2c_start_force().set_bit();
172            w.sar_i2c_start().set_bit()
173        });
174
175        for &byte in data.iter().skip(1) {
176            match self.wait_for_tx_interrupt() {
177                Ok(true) => {
178                    sens.sar_i2c_ctrl().modify(|r, w| {
179                        let mut value = r.sar_i2c_ctrl().bits();
180                        value &= !(0xFF << 19);
181                        value |= (byte as u32) << 19;
182                        value |= 1 << 27;
183                        unsafe { w.sar_i2c_ctrl().bits(value) }
184                    });
185                    self.i2c
186                        .register_block()
187                        .int_clr()
188                        .write(|w| w.tx_data().clear_bit_by_one());
189                }
190                Ok(false) => panic!("Peripheral didn't wait for data"),
191                Err(err) => {
192                    // Stop transmission.
193                    sens.sar_i2c_ctrl().modify(|_, w| {
194                        w.sar_i2c_start_force().clear_bit();
195                        w.sar_i2c_start().clear_bit()
196                    });
197
198                    return Err(err);
199                }
200            }
201        }
202
203        let result = self.wait_for_complete_interrupt();
204
205        // Stop transmission.
206        sens.sar_i2c_ctrl().write(|w| {
207            w.sar_i2c_start_force().clear_bit();
208            w.sar_i2c_start().clear_bit()
209        });
210
211        result
212    }
213
214    pub(super) fn read_bytes(
215        &mut self,
216        address: u8,
217        register: u8,
218        data: &mut [u8],
219    ) -> Result<(), Error> {
220        let sens = unsafe { crate::pac::SENS::steal() };
221
222        if data.len() > u8::MAX as usize {
223            return Err(Error::TransactionSizeLimitExceeded);
224        }
225
226        // Slave addr + Reg addr
227        self.write_cmd(
228            2,
229            Command::Write {
230                ack_exp: Ack::Ack,
231                ack_check_en: true,
232                length: 2,
233            },
234        );
235        // Restart
236        self.write_cmd(3, Command::Start);
237        self.write_cmd(
238            4,
239            Command::Write {
240                ack_exp: Ack::Ack,
241                ack_check_en: true,
242                // Reg addr
243                length: 1,
244            },
245        );
246        if data.len() > 1 {
247            self.write_cmd(
248                5,
249                Command::Read {
250                    ack_value: Ack::Ack,
251                    length: (data.len() - 1) as _,
252                },
253            );
254            self.write_cmd(
255                6,
256                Command::Read {
257                    ack_value: Ack::Nack,
258                    length: 1,
259                },
260            );
261            self.write_cmd(7, Command::Stop);
262        } else {
263            self.write_cmd(
264                5,
265                Command::Read {
266                    ack_value: Ack::Nack,
267                    length: 1,
268                },
269            );
270            self.write_cmd(6, Command::Stop);
271        }
272
273        self.clear_interrupts();
274
275        // Start transmission.
276        let ctrl = {
277            let mut result = 0;
278            result |= address as u32;
279            result |= (register as u32) << 11;
280            result |= 0u32 << 27; // Read
281            result
282        };
283        sens.sar_i2c_ctrl().write(|w| {
284            unsafe { w.sar_i2c_ctrl().bits(ctrl) };
285            w.sar_i2c_start_force().set_bit();
286            w.sar_i2c_start().set_bit()
287        });
288
289        for byte in data {
290            match self.wait_for_rx_interrupt() {
291                Ok(true) => {
292                    *byte = self.i2c.register_block().data().read().i2c_rdata().bits();
293                    self.i2c
294                        .register_block()
295                        .int_clr()
296                        .write(|w| w.rx_data().clear_bit_by_one());
297                }
298                Ok(false) => panic!("Peripheral didn't wait for data to be read"),
299                Err(err) => {
300                    // Stop transmission.
301                    sens.sar_i2c_ctrl().modify(|_, w| {
302                        w.sar_i2c_start_force().clear_bit();
303                        w.sar_i2c_start().clear_bit()
304                    });
305
306                    return Err(err);
307                }
308            }
309        }
310
311        let result = self.wait_for_complete_interrupt();
312
313        // Stop transmission.
314        sens.sar_i2c_ctrl().modify(|_, w| {
315            w.sar_i2c_start_force().clear_bit();
316            w.sar_i2c_start().clear_bit()
317        });
318
319        result
320    }
321
322    fn clear_interrupts(&self) {
323        self.i2c.register_block().int_clr().write(|w| {
324            w.trans_complete().clear_bit_by_one();
325            w.tx_data().clear_bit_by_one();
326            w.rx_data().clear_bit_by_one();
327            w.ack_err().clear_bit_by_one();
328            w.time_out().clear_bit_by_one();
329            w.arbitration_lost().clear_bit_by_one()
330        });
331    }
332
333    fn wait_for_tx_interrupt(&self) -> Result<bool, Error> {
334        loop {
335            let int_raw = self.i2c.register_block().int_raw().read();
336            if int_raw.tx_data().bit_is_set() {
337                break Ok(true);
338            } else if int_raw.trans_complete().bit_is_set() {
339                break Ok(false);
340            } else if int_raw.time_out().bit_is_set() {
341                break Err(Error::TimeOut);
342            } else if int_raw.ack_err().bit_is_set() {
343                break Err(Error::AckCheckFailed);
344            } else if int_raw.arbitration_lost().bit_is_set() {
345                break Err(Error::ArbitrationLost);
346            }
347        }
348    }
349
350    fn wait_for_rx_interrupt(&self) -> Result<bool, Error> {
351        loop {
352            let int_raw = self.i2c.register_block().int_raw().read();
353            if int_raw.rx_data().bit_is_set() {
354                break Ok(true);
355            } else if int_raw.trans_complete().bit_is_set() {
356                break Ok(false);
357            } else if int_raw.time_out().bit_is_set() {
358                break Err(Error::TimeOut);
359            } else if int_raw.ack_err().bit_is_set() {
360                break Err(Error::AckCheckFailed);
361            } else if int_raw.arbitration_lost().bit_is_set() {
362                break Err(Error::ArbitrationLost);
363            }
364        }
365    }
366
367    fn wait_for_complete_interrupt(&self) -> Result<(), Error> {
368        loop {
369            let int_raw = self.i2c.register_block().int_raw().read();
370            if int_raw.trans_complete().bit_is_set() {
371                break Ok(());
372            } else if int_raw.time_out().bit_is_set() {
373                break Err(Error::TimeOut);
374            } else if int_raw.ack_err().bit_is_set() {
375                break Err(Error::AckCheckFailed);
376            } else if int_raw.arbitration_lost().bit_is_set() {
377                break Err(Error::ArbitrationLost);
378            }
379        }
380    }
381
382    fn write_cmd(&self, idx: usize, command: Command) {
383        let cmd = command.into();
384        self.i2c
385            .register_block()
386            .cmd(idx)
387            .write(|w| unsafe { w.command().bits(cmd) });
388    }
389
390    pub(super) fn disable(&mut self) {
391        PeripheralClockControl::set_reset(Peripheral::RtcI2c, true);
392        PeripheralClockControl::set_enabled_untracked(Peripheral::RtcI2c, false);
393    }
394}
395
396/// I2C-specific configuration errors
397#[derive(Debug, Clone, Copy, PartialEq)]
398#[cfg_attr(feature = "defmt", derive(defmt::Format))]
399#[non_exhaustive]
400pub enum ConfigError {
401    /// The timeout period is longer than the configuration register allows.
402    TimeoutTooLong,
403}
404
405/// I2C driver configuration
406#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, procmacros::BuilderLite)]
407#[cfg_attr(feature = "defmt", derive(defmt::Format))]
408#[non_exhaustive]
409pub struct Config {
410    /// The I2C timings (clock frequency).
411    timing: Timing,
412
413    /// I2C SCL timeout period.
414    timeout: Duration,
415}
416
417/// I2C timings
418#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, procmacros::BuilderLite)]
419#[cfg_attr(feature = "defmt", derive(defmt::Format))]
420pub struct Timing {
421    /// SCL low period
422    scl_low_period: u32,
423    /// SCL high period
424    scl_high_period: u32,
425    /// Period between the SDA switch and the falling edge of SCL
426    sda_duty: u32,
427    /// Waiting time after the START condition in micro seconds
428    scl_start_period: u32,
429    /// Waiting time before the END condition in micro seconds
430    scl_stop_period: u32,
431}
432
433impl Timing {
434    /// I2C timings for standard mode (100 kHz).
435    pub fn standard_mode() -> Self {
436        Self::default()
437            .with_scl_low_period(clock_from_micros(5))
438            .with_scl_high_period(clock_from_micros(5))
439            .with_sda_duty(clock_from_micros(2))
440            .with_scl_start_period(clock_from_micros(3))
441            .with_scl_stop_period(clock_from_micros(6))
442    }
443
444    /// I2C timings for fast mode (400 kHz).
445    pub fn fast_mode() -> Self {
446        Self::default()
447            .with_scl_low_period(clock_from_nanos(1_400))
448            .with_scl_high_period(clock_from_nanos(300))
449            .with_sda_duty(clock_from_nanos(1_000))
450            .with_scl_start_period(clock_from_nanos(2_000))
451            .with_scl_stop_period(clock_from_nanos(1_300))
452    }
453}
454
455fn clock_from_micros(micros: u64) -> u32 {
456    nanos_to_clock(micros * 1_000)
457}
458
459fn clock_from_nanos(nanos: u64) -> u32 {
460    nanos_to_clock(nanos)
461}
462
463fn nanos_to_clock(nanos: u64) -> u32 {
464    ((nanos as u128 * crate::soc::clocks::rc_fast_clk_frequency() as u128) / 1_000_000_000) as u32
465}
466
467/// A generic I2C Command.
468enum Command {
469    Start,
470    Stop,
471    Write {
472        /// This bit is to set an expected ACK value for the transmitter.
473        ack_exp: Ack,
474        /// Enables checking the ACK value received against the ack_exp
475        /// value.
476        ack_check_en: bool,
477        /// Length of data (in bytes) to be written. The maximum length is
478        /// 255, while the minimum is 1.
479        length: u8,
480    },
481    Read {
482        /// Indicates whether the receiver will send an ACK after this byte
483        /// has been received.
484        ack_value: Ack,
485        /// Length of data (in bytes) to be read. The maximum length is 255,
486        /// while the minimum is 1.
487        length: u8,
488    },
489}
490
491#[derive(Eq, PartialEq, Copy, Clone)]
492enum Ack {
493    Ack,
494    Nack,
495}
496
497impl From<Command> for u16 {
498    fn from(c: Command) -> u16 {
499        let opcode = match c {
500            Command::Start => 0,
501            Command::Stop => 3,
502            Command::Write { .. } => 1,
503            Command::Read { .. } => 2,
504        };
505
506        let length = match c {
507            Command::Start | Command::Stop => 0,
508            Command::Write { length: l, .. } | Command::Read { length: l, .. } => l,
509        };
510
511        let ack_exp = match c {
512            Command::Start | Command::Stop | Command::Read { .. } => Ack::Nack,
513            Command::Write { ack_exp: exp, .. } => exp,
514        };
515
516        let ack_check_en = match c {
517            Command::Start | Command::Stop | Command::Read { .. } => false,
518            Command::Write {
519                ack_check_en: en, ..
520            } => en,
521        };
522
523        let ack_value = match c {
524            Command::Start | Command::Stop | Command::Write { .. } => Ack::Nack,
525            Command::Read { ack_value: ack, .. } => ack,
526        };
527
528        let mut cmd: u16 = length.into();
529
530        if ack_check_en {
531            cmd |= 1 << 8;
532        } else {
533            cmd &= !(1 << 8);
534        }
535
536        if ack_exp == Ack::Nack {
537            cmd |= 1 << 9;
538        } else {
539            cmd &= !(1 << 9);
540        }
541
542        if ack_value == Ack::Nack {
543            cmd |= 1 << 10;
544        } else {
545            cmd &= !(1 << 10);
546        }
547
548        cmd |= opcode << 11;
549
550        cmd
551    }
552}