In embedded Rust, how do you write a temperature-sensor driver once against embedded-hal 1.0's `I2c` trait so it runs on two different microcontrollers?
answer
- generic struct, not a chip type
- own the bus, hand it back later
- the associated Error type
- one transaction with a repeated start
- a fake bus for host tests
basics
~20 sMake the driver generic over a type parameter bounded by embedded_hal::i2c::I2c, store the bus by value, and return I2C::Error from its methods. Each chip's HAL implements I2c for its controller, so both firmwares pass their own bus in.
solid answer
~40 sThe driver is a `no_std` library with a struct such as `TempSensor<I2C>` and an `impl<I2C: I2c> TempSensor<I2C>` block. `new(i2c, address)` takes the bus **by value**, as the `embedded_hal::i2c` docs recommend; because `I2c` has a blanket impl for `&mut T`, a caller can still lend a bus with `&mut bus`. Reading a register is `self.i2c.write_read(self.address, &[TEMP_REG], &mut buf)?`, one transaction with a repeated start, and the error is the HAL's own `I2C::Error`, which generic code can classify with `Error::kind()`. Each firmware builds its chip's HAL I2C controller and passes it in; the driver never names a chip. The same bound lets a host test pass a fake bus that implements only `transaction`, so the conversion logic runs under `cargo test` with no board.
code
rust · 29 lines#![no_std]
use embedded_hal::i2c::I2c;
const TEMP_REG: u8 = 0x00;
pub struct TempSensor<I2C> {
i2c: I2C,
address: u8,
}
impl<I2C: I2c> TempSensor<I2C> {
pub fn new(i2c: I2C, address: u8) -> Self {
Self { i2c, address }
}
/// Temperature in hundredths of a degree Celsius.
pub fn read_centi_celsius(&mut self) -> Result<i32, I2C::Error> {
let mut buf = [0u8; 2];
self.i2c.write_read(self.address, &[TEMP_REG], &mut buf)?;
let raw = i16::from_be_bytes(buf) >> 4; // 12-bit two's complement
Ok(i32::from(raw) * 625 / 100) // 0.0625 degrees per step
}
/// Hands the bus back, e.g. to give it to another driver.
pub fn release(self) -> I2C {
self.i2c
}
}go deeper
Recall the shape: a generic struct, an impl block bounded by I2c, new() taking the bus, and write_read to read a register.
Explain why the bus is owned, how the &mut blanket impl keeps lending possible, and how I2C::Error with kind() keeps error handling portable.
Show the transaction semantics of write_read, right-aligned addresses, bus sharing through a wrapper crate, and host tests against a fake I2c.
Argue for drivers that depend only on embedded-hal: they survive a change of microcontroller, can be shared across products, and are testable on the host.
## The goal: one driver, any chip A temperature sensor on an I2C bus speaks the same protocol whichever microcontroller talks to it: write the register number, read two bytes back. What differs between microcontrollers is how their I2C controllers are programmed. `embedded-hal` 1.0 separates the two: each chip's HAL crate implements the `embedded_hal::i2c::I2c` trait for its controller, and the driver is written against that trait alone. ## Anatomy of the driver 1. **A generic struct.** `TempSensor<I2C>` stores the bus and the device's 7-bit address. The struct needs no bound; the `impl<I2C: I2c>` block carries it. 2. **Ownership of the bus.** `new` takes `I2C` by value. The `embedded_hal::i2c` module docs say drivers should take the `I2c` instance in `new()` and store it, and should not take `&mut I2c` in every method. Owning does not restrict the caller: the blanket `impl<A: AddressMode, T: I2c<A> + ?Sized> I2c<A> for &mut T` means `TempSensor::new(&mut bus, 0x48)` works too. 3. **A way back.** `release(self) -> I2C` returns the bus, so the application can reuse it once the driver is done. 4. **The HAL's error type.** Every `I2c` has an associated `Error` (through `ErrorType`) that implements `embedded_hal::i2c::Error`. The driver returns `Result<_, I2C::Error>` or wraps it in its own error enum, and `kind()` maps any HAL's error onto `ErrorKind` variants, such as `NoAcknowledge(NoAcknowledgeSource::Address)` when the device is missing. Without the bound the method call does not resolve: rustc reports ``error[E0599]: no method named `write_read` found for type parameter `I2C` in the current scope``. ## The transaction the driver issues `I2c` has one required method, `transaction(address, &mut [Operation])`; `read`, `write` and `write_read` have default bodies built on it. `write_read(addr, &[TEMP_REG], &mut buf)` is one transaction of `[Operation::Write, Operation::Read]`: start, address with the write bit, the register byte, a **repeated start**, address with the read bit, two bytes, stop. Calling `write` and then `read` instead produces two transactions with a stop between them, which not every device accepts for a register read, so drivers use `write_read`. Addresses are `SevenBitAddress` (a `u8`) by default and are written **right-aligned**: a device whose address bits are `0b011_0010` is `0x32`, not the on-wire `0x64` or `0x65`. A driver for a 10-bit device bounds on `I2c<TenBitAddress>`. ## Using it on two microcontrollers - Firmware for the first chip takes its PAC peripherals, builds the HAL's I2C controller with the right pins and clock, and calls `TempSensor::new(i2c, 0x48)`. - Firmware for the second chip does the same with a different HAL crate; the driver's code and version stay identical. - The driver crate depends only on `embedded-hal`, is `#![no_std]`, and builds both for `thumbv7em-none-eabihf` and for the host. - Two drivers on one bus need a sharing wrapper; the `embedded-hal-bus` crate provides implementations that give each driver its own `I2c` value. - An async version of the same driver is written against the `I2c` trait of the `embedded-hal-async` crate. ## What each firmware's main does The application side is the only code that changes between the two boards: 1. Take the chip's PAC peripherals once with `Peripherals::take()`. 2. Configure clocks and put the two bus pins into the I2C alternate function, using that chip's HAL. 3. Build the HAL's I2C controller at the bus frequency the sensor supports (100 kHz or 400 kHz are common). 4. Pass the controller to `TempSensor::new` and read in the main loop, reacting to `e.kind()` where the error matters, for example retrying after a `NoAcknowledge` while the sensor powers up. Steps 1 to 3 differ per HAL; step 4 is identical text on both boards. ## Testing without hardware Because the driver needs only an `I2c`, a test can implement the trait on a fake struct: `ErrorType` with `type Error = ErrorKind` (which itself implements `Error`), and a `transaction` that fills `Operation::Read` buffers with canned bytes and returns `NoAcknowledge` for a wrong address. `cargo test` on the host then checks the raw-to-Celsius conversion, negative temperatures and the missing-device path. | Choice | Recommended | Why | |---|---|---| | Bus parameter | owned `I2C: I2c` | callers may still pass `&mut bus` | | Register read | `write_read` | one transaction with a repeated start | | Error type | `I2C::Error` or a wrapper | HAL-specific, classified with `kind()` | | Address form | right-aligned 7-bit `u8` | the trait's documented convention |
- How would this Rust driver add its own errors, such as an out-of-range reading, on top of the bus error?Define an enum generic over the bus error, such as `enum Error<E> { I2c(E), OutOfRange(i16) }`, return `Result<i32, Error<I2C::Error>>`, and map bus failures with `.map_err(Error::I2c)?`. Callers still reach the HAL's error and can classify it with `kind()`, while the driver's own conditions stay typed.
- Why should an embedded-hal driver not take `&mut I2C` in every method to allow sharing the bus?The `embedded_hal::i2c` docs call that much less ergonomic and unnecessary: owning the bus still lets callers pass `&mut bus` through the blanket impl, or pass a sharing implementation from `embedded-hal-bus`. Taking the bus per call also spreads the bus through every call site of the driver.
- The driver should take &mut I2C in every method so the bus can be shared.
- Supporting two chips means cfg branches on each chip's HAL inside the driver.
- Calling write and then read is identical to write_read on any device.
- A 7-bit address is passed shifted left together with the read or write bit.
- embedded-hal fixes one I2C error enum that every HAL must return.