Write a Portable Sensor Driver With embedded-hal 1.0 Traits
Build a TMP102 temperature driver generic over the embedded-hal 1.0 I2c trait, with typed errors, a release method and host unit tests using embedded-hal-mock.

A sensor driver that names stm32f4xx-hal in its dependencies works on one chip family and nowhere else, and most drivers on crates.io avoid that by depending on embedded-hal instead. The trick is small: the driver is generic over any type that implements the I2c trait, so the same code runs on an STM32, an RP2040 or an nRF52 and, with a mock bus, on your laptop's test runner. This post builds a driver for the Texas Instruments TMP102 temperature sensor with embedded-hal 1.0 (stable since January 2024), Rust 1.85 and embedded-hal-mock 0.11, and tests it without any hardware. It sits above the PAC, HAL and BSP layers and is the pattern the whole driver ecosystem follows.
What the sensor does
The TMP102 is an I2C temperature sensor with a 7-bit address of 0x48 when its ADD0 pin is tied to ground, according to its datasheet. It has a pointer register selecting one of four registers. Writing a pointer value of 0x00 and then reading two bytes returns the temperature register: 12 bits, left-justified in a 16-bit big-endian word, two's complement, 0.0625 degrees Celsius per least significant bit. So the raw reading is the 16-bit word shifted right by four, and 0x1900 means 0x190, which is 400 counts, which is 25.0 degrees.
That fixes the whole bus transaction: one write_read with the register pointer out and two bytes back.
The trait you depend on
embedded-hal 1.0 defines the I2C trait in embedded_hal::i2c:
pub trait I2c<A: AddressMode = SevenBitAddress>: ErrorType {
fn read(&mut self, address: A, read: &mut [u8]) -> Result<(), Self::Error>;
fn write(&mut self, address: A, write: &[u8]) -> Result<(), Self::Error>;
fn write_read(&mut self, address: A, write: &[u8], read: &mut [u8]) -> Result<(), Self::Error>;
fn transaction(&mut self, address: A, operations: &mut [Operation<'_>]) -> Result<(), Self::Error>;
}ErrorType supplies the associated Error type, which each HAL defines. Your driver does not know what it is, so it carries it through generically. The method names and shapes are in the embedded-hal 1.0 documentation.
The driver
#![no_std]
use embedded_hal::i2c::I2c;
/// 7-bit address with ADD0 tied to ground.
pub const DEFAULT_ADDRESS: u8 = 0x48;
const REG_TEMPERATURE: u8 = 0x00;
/// A TMP102 on an I2C bus of type `I2C`.
pub struct Tmp102<I2C> {
i2c: I2C,
address: u8,
}
impl<I2C: I2c> Tmp102<I2C> {
/// Takes ownership of the bus handle, using the default address.
pub fn new(i2c: I2C) -> Self {
Self::with_address(i2c, DEFAULT_ADDRESS)
}
pub fn with_address(i2c: I2C, address: u8) -> Self {
Self { i2c, address }
}
/// Reads the temperature in millidegrees Celsius.
pub fn read_millicelsius(&mut self) -> Result<i32, I2C::Error> {
let mut buf = [0u8; 2];
self.i2c
.write_read(self.address, &[REG_TEMPERATURE], &mut buf)?;
// The 12-bit value sits in the top bits; the arithmetic shift keeps the sign.
let counts = i16::from_be_bytes(buf) >> 4;
Ok(i32::from(counts) * 625 / 10)
}
/// Gives the bus back, so another driver can use it.
pub fn release(self) -> I2C {
self.i2c
}
}Look at what the driver does not contain. There is no HAL import, no pin type, no clock and no delay. The only dependency on hardware is the I2C: I2c bound. Three details are worth stating.
The error type is I2C::Error, passed straight to the caller. A driver that invented its own error enum would force every caller to map HAL errors into it; returning the bus error unchanged is the convention for simple drivers. When a driver has its own failure modes (a bad chip ID, say) it defines enum Error<E> { I2c(E), BadId } and wraps the bus error.
The arithmetic is integer on purpose. counts * 625 / 10 converts 0.0625 degrees per count into millidegrees: 0.0625 degrees is 62.5 millidegrees, and 625 / 10 keeps that as an integer division after the multiply, so 400 counts become 25000 millidegrees. Floating point would pull in soft-float code on a core with no FPU, and the caller can convert if it wants.
release() takes self by value and returns the bus. That is how drivers hand a bus back. Without it, the driver owns the only handle for the life of the program.
Testing on the host
embedded-hal-mock provides a fake I2C bus that checks the transactions you expect. Declare it as a dev-dependency with the eh1 feature, which selects the embedded-hal 1.0 mocks:
[package]
name = "tmp102-driver"
version = "0.1.0"
edition = "2021"
[dependencies]
embedded-hal = "1.0"
[dev-dependencies]
embedded-hal-mock = { version = "0.11", features = ["eh1"] }use embedded_hal_mock::eh1::i2c::{Mock as I2cMock, Transaction as I2cTransaction};
use tmp102_driver::{Tmp102, DEFAULT_ADDRESS};
#[test]
fn reads_positive_temperature() {
// 0x1900 is 0x190 counts: 400 * 0.0625 = 25.0 degrees.
let expectations = [I2cTransaction::write_read(
DEFAULT_ADDRESS,
vec![0x00],
vec![0x19, 0x00],
)];
let mut sensor = Tmp102::new(I2cMock::new(&expectations));
assert_eq!(sensor.read_millicelsius().unwrap(), 25_000);
sensor.release().done();
}
#[test]
fn reads_negative_temperature() {
// 0xE700 arithmetic-shifted right by four is -400 counts: -25.0 degrees.
let expectations = [I2cTransaction::write_read(
DEFAULT_ADDRESS,
vec![0x00],
vec![0xE7, 0x00],
)];
let mut sensor = Tmp102::new(I2cMock::new(&expectations));
assert_eq!(sensor.read_millicelsius().unwrap(), -25_000);
sensor.release().done();
}release().done() is why release exists: the mock checks at done() that every expected transaction happened, so a driver that forgot to read the bus would fail the test. Running cargo test prints:
running 2 tests
test reads_negative_temperature ... ok
test reads_positive_temperature ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered outThe negative case is the one that catches the classic bug of shifting an unsigned value, which would turn -25 into a large positive number. Casting [0xE7, 0x00] through i16 before the shift is what keeps the sign.
Using it on a real chip
The caller supplies a bus from any HAL. With stm32f4xx-hal the I2C peripheral implements the 1.0 trait:
#![no_std]
#![no_main]
use cortex_m_rt::entry;
use defmt_rtt as _;
use panic_probe as _;
use stm32f4xx_hal::{i2c::I2c, pac, prelude::*};
use tmp102_driver::Tmp102;
#[entry]
fn main() -> ! {
let dp = pac::Peripherals::take().unwrap();
let rcc = dp.RCC.constrain();
let clocks = rcc.cfgr.freeze();
let gpiob = dp.GPIOB.split();
let scl = gpiob.pb8;
let sda = gpiob.pb9;
let i2c = I2c::new(dp.I2C1, (scl, sda), 100.kHz(), &clocks);
let mut sensor = Tmp102::new(i2c);
match sensor.read_millicelsius() {
Ok(mc) => defmt::info!("temperature: {} mC", mc),
Err(_) => defmt::error!("i2c read failed"),
}
loop {
cortex_m::asm::wfi();
}
}The driver crate did not change. On an RP2040 you would build the bus with rp2040-hal and the call to Tmp102::new stays identical. A logged value would look like temperature: 25000 mC, with the number depending on the room.
Writing registers: shutdown mode
Reads are half of a driver. The TMP102 has a configuration register at pointer 0x01, two bytes long, with a reset value of 0x60A0 according to the datasheet. Bit 0 of the first byte is the shutdown bit, SD, which stops continuous conversions to save power. Setting it means writing the pointer and both configuration bytes in one write, with the other bits preserved from their reset values:
const REG_CONFIG: u8 = 0x01;
const CONFIG_RUNNING: [u8; 2] = [0x60, 0xA0];
const CONFIG_SHUTDOWN: [u8; 2] = [0x61, 0xA0];
impl<I2C: I2c> Tmp102<I2C> {
/// Stops conversions; the sensor draws less current until `wake`.
pub fn shutdown(&mut self) -> Result<(), I2C::Error> {
self.i2c.write(
self.address,
&[REG_CONFIG, CONFIG_SHUTDOWN[0], CONFIG_SHUTDOWN[1]],
)
}
/// Returns to continuous conversion mode.
pub fn wake(&mut self) -> Result<(), I2C::Error> {
self.i2c.write(
self.address,
&[REG_CONFIG, CONFIG_RUNNING[0], CONFIG_RUNNING[1]],
)
}
}This version overwrites the whole register, which is only correct if you never changed the other fields. A fuller driver reads the register, flips the bit and writes it back. The write path is as easy to test as the read path, because the mock checks the exact bytes on the wire:
use embedded_hal_mock::eh1::i2c::{Mock as I2cMock, Transaction as I2cTransaction};
use tmp102_driver::{Tmp102, DEFAULT_ADDRESS};
#[test]
fn shutdown_sets_the_sd_bit() {
let expectations = [I2cTransaction::write(
DEFAULT_ADDRESS,
vec![0x01, 0x61, 0xA0],
)];
let mut sensor = Tmp102::new(I2cMock::new(&expectations));
sensor.shutdown().unwrap();
sensor.release().done();
}running 1 test
test shutdown_sets_the_sd_bit ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered outIf the driver wrote [0x01, 0x60, 0xA0] instead, the mock would panic with a mismatch between the expected and actual bytes, which is the quickest way to catch a register map transcription error before it meets silicon.
Sharing the bus
Tmp102::new(i2c) moves the bus into the driver, so a second sensor on the same wires cannot have it. The fix is a bus-sharing wrapper that implements I2c itself and hands out handles; sharing an I2C bus between drivers with embedded-hal-bus shows it. Because your driver is generic over I2c, it accepts the shared handle with no change.
When not to make a driver generic
A driver for a one-off board that will never leave one HAL gains little from generics, and a generic driver costs a longer type in every struct that holds it. If your driver needs a feature the traits do not model, such as DMA or a particular interrupt, you end up bounding on HAL-specific traits and the portability is gone. The async variant of the trait is in embedded-hal-async, and a driver that must serve both blocking and async callers often keeps its logic in a shared core and ships two thin wrappers.
Publishing the crate
A driver meant for other people carries a few extra duties. Keep no_std in the crate root and put the mock in dev-dependencies only, so downstream builds never see it. List embedded-hal = "1.0" as the only runtime dependency, and say in the readme which minimum Rust version you support. Add the embedded-hal trait version to the crate's keywords and categories (embedded, no-std, hardware-support) so that people searching crates.io for a TMP102 driver find yours. If you later add an async API, put it behind a Cargo feature and depend on embedded-hal-async only when that feature is on, so blocking users do not pay for it.


