ariel_os_nrf/i2c/controller/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
//! Provides support for the I2C communication bus in controller mode.

use ariel_os_embassy_common::impl_async_i2c_for_driver_enum;

use embassy_nrf::{
    bind_interrupts,
    gpio::Pin as GpioPin,
    peripherals,
    twim::{InterruptHandler, Twim},
    Peripheral,
};

/// I2C bus configuration.
#[non_exhaustive]
#[derive(Clone)]
pub struct Config {
    /// The frequency at which the bus should operate.
    pub frequency: Frequency,
    /// Whether to enable the internal pull-up resistor on the SDA pin.
    pub sda_pullup: bool,
    /// Whether to enable the internal pull-up resistor on the SCL pin.
    pub scl_pullup: bool,
    /// Whether to set the SDA pin's drive strength to
    /// [`DriveStrength::High`](crate::gpio::DriveStrength::High).
    pub sda_high_drive: bool,
    /// Whether to set the SCL pin's drive strength to
    /// [`DriveStrength::High`](crate::gpio::DriveStrength::High).
    pub scl_high_drive: bool,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            frequency: Frequency::_100k,
            sda_pullup: false,
            scl_pullup: false,
            sda_high_drive: false,
            scl_high_drive: false,
        }
    }
}

/// I2C bus frequency.
// NOTE(hal): the datasheets only mention these frequencies.
#[cfg(any(context = "nrf52833", context = "nrf52840", context = "nrf5340"))]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Frequency {
    /// Standard mode.
    _100k,
    /// 250 kHz.
    #[cfg(any(context = "nrf52833", context = "nrf5340"))]
    _250k,
    /// Fast mode.
    _400k,
    // FIXME(embassy): the upstream Embassy crate does not support this frequency
    // #[cfg(context = "nrf5340")]
    // _1M,
}

#[doc(hidden)]
impl Frequency {
    pub const fn first() -> Self {
        Self::_100k
    }

    pub const fn last() -> Self {
        Self::_400k
    }

    pub const fn next(self) -> Option<Self> {
        match self {
            #[cfg(context = "nrf52840")]
            Self::_100k => Some(Self::_400k),
            #[cfg(any(context = "nrf52833", context = "nrf5340"))]
            Self::_100k => Some(Self::_250k),
            #[cfg(any(context = "nrf52833", context = "nrf5340"))]
            Self::_250k => Some(Self::_400k),
            Self::_400k => None,
        }
    }

    pub const fn prev(self) -> Option<Self> {
        match self {
            Self::_100k => None,
            #[cfg(any(context = "nrf52833", context = "nrf5340"))]
            Self::_250k => Some(Self::_100k),
            #[cfg(context = "nrf52840")]
            Self::_400k => Some(Self::_100k),
            #[cfg(any(context = "nrf52833", context = "nrf5340"))]
            Self::_400k => Some(Self::_250k),
        }
    }

    pub const fn khz(self) -> u32 {
        match self {
            Self::_100k => 100,
            #[cfg(any(context = "nrf52833", context = "nrf5340"))]
            Self::_250k => 250,
            Self::_400k => 400,
        }
    }
}

ariel_os_embassy_common::impl_i2c_from_frequency!();

impl From<Frequency> for embassy_nrf::twim::Frequency {
    fn from(freq: Frequency) -> Self {
        match freq {
            Frequency::_100k => embassy_nrf::twim::Frequency::K100,
            #[cfg(any(context = "nrf52833", context = "nrf5340"))]
            Frequency::_250k => embassy_nrf::twim::Frequency::K250,
            Frequency::_400k => embassy_nrf::twim::Frequency::K400,
        }
    }
}

macro_rules! define_i2c_drivers {
    ($( $interrupt:ident => $peripheral:ident ),* $(,)?) => {
        $(
            /// Peripheral-specific I2C driver.
            pub struct $peripheral {
                twim: Twim<'static, peripherals::$peripheral>,
            }

            impl $peripheral {
                /// Returns a driver implementing [`embedded_hal_async::i2c::I2c`] for this
                /// I2C peripheral.
                #[expect(clippy::new_ret_no_self)]
                #[must_use]
                pub fn new(
                    sda_pin: impl Peripheral<P: GpioPin> + 'static,
                    scl_pin: impl Peripheral<P: GpioPin> + 'static,
                    config: Config,
                ) -> I2c {
                    let mut twim_config = embassy_nrf::twim::Config::default();
                    twim_config.frequency = config.frequency.into();
                    twim_config.sda_pullup = config.sda_pullup;
                    twim_config.scl_pullup = config.scl_pullup;
                    twim_config.sda_high_drive = config.sda_high_drive;
                    twim_config.scl_high_drive = config.scl_high_drive;

                    bind_interrupts!(
                        struct Irqs {
                            $interrupt => InterruptHandler<peripherals::$peripheral>;
                        }
                    );

                    // Make this struct a compile-time-enforced singleton: having multiple statics
                    // defined with the same name would result in a compile-time error.
                    paste::paste! {
                        #[allow(dead_code)]
                        static [<PREVENT_MULTIPLE_ $peripheral>]: () = ();
                    }

                    // FIXME(safety): enforce that the init code indeed has run
                    // SAFETY: this struct being a singleton prevents us from stealing the
                    // peripheral multiple times.
                    let twim_peripheral = unsafe { peripherals::$peripheral::steal() };

                    // NOTE(hal): the I2C peripheral and driver do not have any built-in timeout,
                    // we implement it at a higher level, not in this HAL-specific module.
                    let twim = Twim::new(twim_peripheral, Irqs, sda_pin, scl_pin, twim_config);

                    I2c::$peripheral(Self { twim })
                }
            }
        )*

        /// Peripheral-agnostic driver.
        pub enum I2c {
            $(
                #[doc = concat!(stringify!($peripheral), " peripheral.")]
                $peripheral($peripheral),
            )*
        }

        impl embedded_hal_async::i2c::ErrorType for I2c {
            type Error = ariel_os_embassy_common::i2c::controller::Error;
        }

        impl_async_i2c_for_driver_enum!(I2c, $( $peripheral ),*);
    }
}

// We cannot impl From because both types are external to this crate.
fn from_error(err: embassy_nrf::twim::Error) -> ariel_os_embassy_common::i2c::controller::Error {
    use embassy_nrf::twim::Error::*;

    use ariel_os_embassy_common::i2c::controller::{Error, NoAcknowledgeSource};

    match err {
        TxBufferTooLong => Error::Other,
        RxBufferTooLong => Error::Other,
        Transmit => Error::Other,
        Receive => Error::Other,
        BufferNotInRAM => Error::Other,
        AddressNack => Error::NoAcknowledge(NoAcknowledgeSource::Address),
        DataNack => Error::NoAcknowledge(NoAcknowledgeSource::Data),
        Overrun => Error::Overrun,
        Timeout => Error::Timeout,
        _ => Error::Other,
    }
}

// FIXME: support other nRF archs
// Define a driver per peripheral
#[cfg(any(context = "nrf52833", context = "nrf52840"))]
define_i2c_drivers!(
    TWISPI0 => TWISPI0,
    TWISPI1 => TWISPI1,
);
#[cfg(context = "nrf5340")]
define_i2c_drivers!(
    SERIAL0 => SERIAL0,
    SERIAL1 => SERIAL1,
);