omnitiles/hw/
i2c.rs

1// SPDX-License-Identifier: MIT
2// © 2025–2026 Christopher Liu
3
4//! I2C abstraction layer.
5//!
6//! Provides a thin blocking I2C bus wrapper around the stm32f7xx-hal `BlockingI2c` type.
7
8use stm32f7xx_hal::{
9    i2c::{self, BlockingI2c, PinScl, PinSda},
10    pac::I2C1,
11    prelude::*,
12};
13
14/// Wrapper around an enabled HAL BlockingI2c instance.
15pub struct I2cBus<SCL, SDA> {
16    i2c: BlockingI2c<I2C1, SCL, SDA>,
17}
18
19impl<SCL, SDA> I2cBus<SCL, SDA>
20where
21    SCL: PinScl<I2C1>,
22    SDA: PinSda<I2C1>,
23{
24    pub fn new(i2c: BlockingI2c<I2C1, SCL, SDA>) -> Self {
25        Self { i2c }
26    }
27
28    /// Perform a write-then-read transaction (register read pattern).
29    pub fn write_read(&mut self, addr: u8, bytes: &[u8], buf: &mut [u8]) -> Result<(), i2c::Error> {
30        self.i2c.write_read(addr, bytes, buf).map_err(|e| match e {
31            nb::Error::Other(e) => e,
32            nb::Error::WouldBlock => unreachable!(),
33        })
34    }
35
36    /// Write bytes to an I2C device.
37    pub fn write(&mut self, addr: u8, bytes: &[u8]) -> Result<(), i2c::Error> {
38        self.i2c.write(addr, bytes).map_err(|e| match e {
39            nb::Error::Other(e) => e,
40            nb::Error::WouldBlock => unreachable!(),
41        })
42    }
43}