ariel_os_rp/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
//! Provides support for the I2C communication bus in controller mode.

use ariel_os_embassy_common::{i2c::controller::Kilohertz, impl_async_i2c_for_driver_enum};
use embassy_rp::{
    bind_interrupts,
    i2c::{InterruptHandler, SclPin, SdaPin},
    peripherals, Peripheral,
};

const KHZ_TO_HZ: u32 = 1000;

/// I2C bus configuration.
// We do not provide configuration for internal pull-ups as the RP2040 datasheet mentions in
// section 4.3.1.3 that the GPIO used should have pull-ups enabled.
#[derive(Clone)]
#[non_exhaustive]
pub struct Config {
    /// The frequency at which the bus should operate.
    pub frequency: Frequency,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            frequency: Frequency::UpTo100k(Kilohertz::kHz(100)),
        }
    }
}

/// I2C bus frequency.
// FIXME(embassy): fast mode plus is supported by hardware but requires additional configuration
// that Embassy does not seem to currently provide.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[repr(u32)]
pub enum Frequency {
    /// Standard mode.
    UpTo100k(Kilohertz), // FIXME: use a ranged integer?
    /// Fast mode.
    UpTo400k(Kilohertz), // FIXME: use a ranged integer?
}

#[doc(hidden)]
impl Frequency {
    pub const fn first() -> Self {
        Self::UpTo100k(Kilohertz::kHz(1))
    }

    pub const fn last() -> Self {
        Self::UpTo400k(Kilohertz::kHz(400))
    }

    pub const fn next(self) -> Option<Self> {
        match self {
            Self::UpTo100k(f) => {
                if f.to_kHz() < 100 {
                    // NOTE(no-overflow): `f` is small enough due to if condition
                    Some(Self::UpTo100k(Kilohertz::kHz(f.to_kHz() + 1)))
                } else {
                    Some(Self::UpTo400k(Kilohertz::kHz(self.khz() + 1)))
                }
            }
            Self::UpTo400k(f) => {
                if f.to_kHz() < 400 {
                    // NOTE(no-overflow): `f` is small enough due to if condition
                    Some(Self::UpTo400k(Kilohertz::kHz(f.to_kHz() + 1)))
                } else {
                    None
                }
            }
        }
    }

    pub const fn prev(self) -> Option<Self> {
        match self {
            Self::UpTo100k(f) => {
                if f.to_kHz() > 1 {
                    // NOTE(no-overflow): `f` is large enough due to if condition
                    Some(Self::UpTo100k(Kilohertz::kHz(f.to_kHz() - 1)))
                } else {
                    None
                }
            }
            Self::UpTo400k(f) => {
                if f.to_kHz() > 100 + 1 {
                    // NOTE(no-overflow): `f` is large enough due to if condition
                    Some(Self::UpTo400k(Kilohertz::kHz(f.to_kHz() - 1)))
                } else {
                    Some(Self::UpTo100k(Kilohertz::kHz(self.khz() - 1)))
                }
            }
        }
    }

    pub const fn khz(self) -> u32 {
        match self {
            Self::UpTo100k(f) | Self::UpTo400k(f) => f.to_kHz(),
        }
    }
}

ariel_os_embassy_common::impl_i2c_from_frequency_up_to!();

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

            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: SdaPin<peripherals::$peripheral>> + 'static,
                    scl_pin: impl Peripheral<P: SclPin<peripherals::$peripheral>> + 'static,
                    config: Config,
                ) -> I2c {
                    let mut i2c_config = embassy_rp::i2c::Config::default();
                    i2c_config.frequency = config.frequency.khz() * KHZ_TO_HZ;

                    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 i2c_peripheral = unsafe { peripherals::$peripheral::steal() };

                    // NOTE(hal): even though we handle bus timeout at a higher level as well, it
                    // does not seem possible to disable the timeout feature on RP.
                    let i2c = embassy_rp::i2c::I2c::new_async(
                        i2c_peripheral,
                        scl_pin,
                        sda_pin,
                        Irqs,
                        i2c_config,
                    );

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

        /// 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_rp::i2c::Error) -> ariel_os_embassy_common::i2c::controller::Error {
    use embassy_rp::i2c::{AbortReason, Error::*};

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

    match err {
        Abort(reason) => match reason {
            AbortReason::NoAcknowledge => Error::NoAcknowledge(NoAcknowledgeSource::Unknown),
            AbortReason::ArbitrationLoss => Error::ArbitrationLoss,
            AbortReason::TxNotEmpty(_) => Error::Other,
            AbortReason::Other(_) => Error::Other,
        },
        InvalidReadBufferLength => Error::Other,
        InvalidWriteBufferLength => Error::Other,
        AddressOutOfRange(_) => Error::Other,
        AddressReserved(_) => Error::Other,
    }
}

// Define a driver per peripheral
define_i2c_drivers!(
    I2C0_IRQ => I2C0,
    I2C1_IRQ => I2C1,
);