ariel_os_stm32/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 218 219 220 221 222 223 224 225 226 227 228 229
//! 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_embedded_hal::adapter::{BlockingAsync, YieldingAsync};
use embassy_stm32::{
bind_interrupts,
i2c::{ErrorInterruptHandler, EventInterruptHandler, I2c as InnerI2c, SclPin, SdaPin},
mode::Blocking,
peripherals,
time::Hertz,
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,
}
impl Default for Config {
fn default() -> Self {
Self {
frequency: Frequency::UpTo100k(Kilohertz::kHz(100)),
sda_pullup: false,
scl_pullup: false,
}
}
}
/// 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!();
impl From<Frequency> for Hertz {
fn from(freq: Frequency) -> Self {
match freq {
Frequency::UpTo100k(f) | Frequency::UpTo400k(f) => Hertz::khz(f.to_kHz()),
}
}
}
macro_rules! define_i2c_drivers {
($( $ev_interrupt:ident + $er_interrupt:ident => $peripheral:ident ),* $(,)?) => {
$(
/// Peripheral-specific I2C driver.
// NOTE(hal): this is not required in this HAL, as the inner I2C type is
// not generic over the I2C peripheral, and is only done for consistency with
// other HALs.
pub struct $peripheral {
twim: YieldingAsync<BlockingAsync<InnerI2c<'static, Blocking>>>,
}
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_stm32::i2c::Config::default();
i2c_config.sda_pullup = config.sda_pullup;
i2c_config.scl_pullup = config.scl_pullup;
i2c_config.timeout = ariel_os_embassy_common::i2c::controller::I2C_TIMEOUT;
bind_interrupts!(
struct Irqs {
$ev_interrupt => EventInterruptHandler<peripherals::$peripheral>;
$er_interrupt => ErrorInterruptHandler<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() };
let frequency = config.frequency;
let i2c = InnerI2c::new_blocking(
twim_peripheral,
scl_pin,
sda_pin,
frequency.into(),
i2c_config,
);
I2c::$peripheral(Self { twim: YieldingAsync::new(BlockingAsync::new(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_stm32::i2c::Error) -> ariel_os_embassy_common::i2c::controller::Error {
use embassy_stm32::i2c::Error::*;
use ariel_os_embassy_common::i2c::controller::{Error, NoAcknowledgeSource};
match err {
Bus => Error::Bus,
Arbitration => Error::ArbitrationLoss,
Nack => Error::NoAcknowledge(NoAcknowledgeSource::Unknown),
Timeout => Error::Timeout,
Crc => Error::Other,
Overrun => Error::Overrun,
ZeroLengthTransfer => Error::Other,
}
}
// Define a driver per peripheral
#[cfg(context = "stm32f401retx")]
define_i2c_drivers!(
I2C1_EV + I2C1_ER => I2C1,
I2C2_EV + I2C2_ER => I2C2,
I2C3_EV + I2C3_ER => I2C3,
);
#[cfg(context = "stm32h755zitx")]
define_i2c_drivers!(
I2C1_EV + I2C1_ER => I2C1,
I2C2_EV + I2C2_ER => I2C2,
I2C3_EV + I2C3_ER => I2C3,
I2C4_EV + I2C4_ER => I2C4,
);
#[cfg(context = "stm32wb55rgvx")]
define_i2c_drivers!(
I2C1_EV + I2C1_ER => I2C1,
// There is no I2C2
I2C3_EV + I2C3_ER => I2C3,
);