use embassy_embedded_hal::shared_bus::asynch::i2c::I2cDevice;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::mutex::Mutex;
use esp_hal::Async;
use esp_hal::i2c::master::{Config, I2c};
use esp_hal::peripherals::{GPIO8, GPIO9, I2C0};
use esp_hal::time::Rate;
use static_cell::StaticCell;
pub type SysI2cBus = Mutex<CriticalSectionRawMutex, I2c<'static, Async>>;
pub type SysI2cDevice = I2cDevice<'static, CriticalSectionRawMutex, I2c<'static, Async>>;
pub const FREQUENCY: Rate = Rate::from_khz(400);
#[allow(missing_docs)]
pub struct SysI2cResources {
pub i2c: I2C0<'static>,
pub sda: GPIO8<'static>,
pub scl: GPIO9<'static>,
}
impl SysI2cResources {
pub fn into_bus(self) -> &'static SysI2cBus {
static BUS: StaticCell<SysI2cBus> = StaticCell::new();
let i2c = I2c::new(self.i2c, Config::default().with_frequency(FREQUENCY))
.expect("400 kHz is a valid I2C configuration")
.with_sda(self.sda)
.with_scl(self.scl)
.into_async();
BUS.init(Mutex::new(i2c))
}
}
pub fn device(bus: &'static SysI2cBus) -> SysI2cDevice {
I2cDevice::new(bus)
}