39 lines
1.4 KiB
Rust
39 lines
1.4 KiB
Rust
use alloc::boxed::Box;
|
|
use embedded_hal_bus::i2c::AtomicDevice;
|
|
use embedded_hal_bus::util::AtomicCell;
|
|
use esp_hal::gpio::interconnect::PeripheralInput;
|
|
use esp_hal::i2c::master::Config;
|
|
use esp_hal::{gpio::interconnect::PeripheralOutput, i2c::master::I2c};
|
|
|
|
type InnerI2cBus<'a> = esp_hal::i2c::master::I2c<'a, esp_hal::Blocking>;
|
|
pub type I2cBus<'a> = &'a AtomicCell<InnerI2cBus<'a>>;
|
|
pub type I2cDevice<'a> = AtomicDevice<'a, esp_hal::i2c::master::I2c<'a, esp_hal::Blocking>>;
|
|
|
|
pub struct I2cBusPinConfiguration<I2C, SCL, SDA> {
|
|
pub i2c_peripheral: I2C,
|
|
pub scl: SCL,
|
|
pub sda: SDA,
|
|
}
|
|
|
|
impl<'a, I2C, SCL, SDA> I2cBusPinConfiguration<I2C, SCL, SDA>
|
|
where
|
|
I2C: esp_hal::i2c::master::Instance + 'a,
|
|
SCL: PeripheralOutput<'a> + PeripheralInput<'a>,
|
|
SDA: PeripheralOutput<'a> + PeripheralInput<'a>,
|
|
{
|
|
pub fn build(self) -> I2cBus<'a> {
|
|
let config = Config::default().with_frequency(esp_hal::time::Rate::from_khz(400));
|
|
let i2c = match I2c::new(self.i2c_peripheral, config) {
|
|
Ok(bus) => bus.with_sda(self.sda).with_scl(self.scl),
|
|
Err(e) => {
|
|
log::error!("Shared I2C bus initialization failed for GPIO17/GPIO18: {e:?}");
|
|
panic!("Shared I2C bus initialization failed");
|
|
}
|
|
};
|
|
let shared_i2c = Box::leak(Box::new(AtomicCell::new(i2c)));
|
|
log::info!("Shared I2C bus ready on GPIO17 (SDA) and GPIO18 (SCL)");
|
|
|
|
shared_i2c
|
|
}
|
|
}
|