One interface, two sensors
Put two temperature sensor drivers behind one ops table so the application does not care which chip is fitted. A medium embedded C problem (Driver design:…
medium · Driver design: HAL versus bare metal · driver · function-pointers · interface
The application reads temperatures with sensor_read(s, &mc) and should not need to know which chip is fitted: boards ship with either a TMP102 or an LM75. Each driver turns the chip's two register bytes raw[0] (high) and raw[1] (low) into thousandths of a degree.
- TMP102: a 12-bit two's complement value in the top 12 bits of the 16, at 0.0625 °C per step.
- LM75: a 9-bit two's complement value in the top 9 bits of the 16, at 0.5 °C per step.
Both return SENSOR_EIO if bus_ok is false. The TMP102 driver is done. Write the LM75 driver and its ops table lm75_ops, and make sensor_read call whichever driver the sensor has, returning SENSOR_ENODEV if it has none.
Starter code
static int tmp102_read(sensor_t *s, int32_t *milli_c) {
if (!s->bus_ok) return SENSOR_EIO;
int16_t steps = (int16_t)(s->raw[0] << 8 | s->raw[1]) >> 4;
*milli_c = steps * 125 / 2; // 62.5 mC per step
return SENSOR_OK;
}
const sensor_ops_t tmp102_ops = { tmp102_read };
static int lm75_read(sensor_t *s, int32_t *milli_c) {
return SENSOR_EIO; // not written yet
}
const sensor_ops_t lm75_ops = { lm75_read };
int sensor_read(sensor_t *s, int32_t *milli_c) {
return tmp102_read(s, milli_c);
}Example tests
The same register bytes from each chip
sensor_t a = { &tmp102_ops, { 0x19, 0x00 }, true };
sensor_t b = { &lm75_ops, { 0x19, 0x00 }, true };
sensor_t c = { &lm75_ops, { 0x19, 0x80 }, true };
sensor_t d = { &lm75_ops, { 0x19, 0x70 }, true }; // the LM75 ignores the low 7 bits
show(&a);
show(&b);
show(&c);
show(&d);Expected output:
25000 mC
25000 mC
25500 mC
25000 mCLearn it first
- Driver design: HAL versus bare metal · Layering a driver so it is testable, portable and still fast.
More Driver design: HAL versus bare metal problems
- A non-blocking driver · Start a conversion and poll for it, with a timeout, instead of waiting in a loop.
- Retries, backoff and bus recovery · Decide which bus errors to retry, how long to wait, and when to recover a stuck bus.
- A driver and its interface: led.h and led.c · Split an LED driver into the header the application includes and the source file that keeps the register work to itself.