Writing Drivers and Hardware Abstraction
A driver is a contract between a datasheet and the rest of your code. Most bugs are contract violations.
🎯 By the end you'll understand
What a driver actually promises — identity, initialisation, timing, validity, and error semantics — and how to write each clause so that the rest of the firmware cannot violate it by accident. Why the SHT40's eight-millisecond conversion and the LIS2DH12's turn-on time belong in the driver's API rather than in a comment. How to check Sensirion's CRC-8 and what it catches that a range check never will. Why "return the last good value on error" is the single most expensive line of code in this course, and what to return instead. Where a hardware abstraction layer earns its keep — the bus interface, which lets you unit-test the driver on your laptop — and where it is just ceremony you will maintain forever for one implementation.
KEY INSIGHTA driver's most important output is "I don't know"
The dashboard shows 24.6 °C. It showed 24.6 °C yesterday, and last week, and — when someone finally scrolls back — every single report since the fourteenth of April, to two decimal places, on a tag sitting next to a window. The humidity sensor died six weeks ago. Nobody noticed, because the driver's error path did the polite thing and returned the last value it had.
A driver is a translation layer between a datasheet and the rest of your program, and it is judged on how faithfully it translates everything the datasheet says — including the parts that are not measurements. The SHT40's datasheet does not only say how to convert a 16-bit word into degrees; it also says how long the conversion takes, what the device does if you talk to it too early, and that every two bytes of data are followed by a checksum precisely because bits get flipped on real wires. A driver that implements the arithmetic and skips the rest has translated the flattering half of the contract. The clause it dropped is the one that tells the system when to stop believing it, and a system that cannot stop believing a dead sensor has no way to be honest with anyone downstream.
Every reading a driver hands upward carries two pieces of information: the value, and whether the value means anything. Lose the second and the first becomes indistinguishable from a lie. The correct error return is never a plausible number — it is a status code, with the last known value marked stale and its age attached, so the layer above can decide whether a six-week-old temperature is useful (sometimes it is) or dangerous (usually it is). Deciding for that layer, silently, inside the driver, is what turned a dead part into six weeks of clean-looking data.
CORE CONCEPTThe five clauses of a driver contract
Read any good sensor driver and you find the same five clauses, whether or not the author named them. Read a bad one and you find that two or three are missing — always the same ones.
| Clause | What it promises | SHT40 | LIS2DH12 | Missing it looks like |
|---|---|---|---|---|
| Identity | The part on the bus is the part you think it is | Read the serial number command (0x89) and check the CRC | Read WHO_AM_I (0x0F); it must return 0x33 | A driver that "works" against an unpopulated footprint because the bus floats high and 0xFF passes for data |
| Initialisation | The device is in a defined state, whatever it was in before | Soft reset (0x94), then wait for the reset time | Reboot the memory content (CTRL_REG5 bit 7), then write every control register you depend on | Firmware that works after a power cycle and fails after a watchdog reset, because the part kept its old configuration and the code assumed defaults |
| Timing | Every wait the datasheet requires is enforced by the driver, not by the caller | Up to 8.2 ms between the 0xFD command and the read | Turn-on time after changing the output data rate or power mode; the first sample is invalid | A read that NACKs, or a first sample that is garbage, blamed on the bus |
| Validity | Data that arrives is checked before it is believed | CRC-8 over each two-byte word | Range and self-consistency checks (there is no CRC on this part) | Occasional impossible values that get "filtered" by a moving average, which is how a corrupt reading becomes a corrupt trend |
| Error semantics | A defined, honest result for every failure, with a bound on time | Status code + stale flag + age | Status code + stale flag + age | The six weeks of 24.6 °C |
Notice that only one of the five is about reading data. The other four are about being sure — about identity, state, time, and truth. That ratio is roughly right for real driver code, too: in the driver below, the arithmetic that converts a raw word into degrees is two lines, and everything else is the contract.
Vendors publish register maps; that is their job. Turning one into an API is yours, and the transformation is not mechanical. sht40_write_reg(0xFD) is a register map with a function around it — the caller still has to know the command, the delay, the byte order, and the checksum. sht40_read(&t_milli_c, &rh_permille) is an API: the caller cannot get the delay wrong because the delay is not the caller's business. The test is simple. If using your driver correctly requires reading the datasheet, you have written a register map.
HOW IT WORKSTiming is part of the API, not a comment
The single most common driver defect is a missing wait, and it is common because waits are invisible: no compiler warns about them, no return code reports them, and the failure they cause looks like a bus problem. Here are the waits Beacon's two parts require and what each one costs if skipped.
| Part | Wait | Datasheet value | Skip it and… |
|---|---|---|---|
| SHT40 | Between the measurement command and the read | Up to 8.2 ms at high precision (4.5 ms medium, 1.7 ms low — verify against your revision) | The sensor NACKs its own address because it is still converting; the read fails (3.5) |
| SHT40 | After a soft reset (0x94) | About 1 ms | The first command is ignored, so initialisation "randomly" fails on cold boots and never on warm ones |
| LIS2DH12 | After changing ODR or power mode | The datasheet's turn-on time, expressed in ODR periods | The first samples are from the old configuration or from a filter that has not settled — motion detection fires on nothing, or misses a real event |
| LIS2DH12 | After a memory reboot (CTRL_REG5 bit 7) | A few milliseconds | Register writes issued during the reboot are silently discarded, so the interrupt you armed is not armed |
| Either | After power is applied | Both parts specify a short power-up time | Bring-up failures that only happen on the bench when someone plugs the battery in and immediately presses reset |
How the driver enforces a wait matters as much as whether it does. A busy-wait is accurate and costs the full active current for its duration; a vTaskDelay yields but rounds up to the tick (3.3); a one-shot esp_timer is accurate, yields, and turns the wait into an event. For an 8.5 ms wait that happens every single wake, the difference between a busy-wait and a timer is not stylistic: it is milliamps of average current against R1, on every one of the 43,200 wakes in a month.
#include "sht40.h" #define CMD_MEASURE_HI 0xFD #define CMD_SOFT_RESET 0x94 #define CMD_SERIAL 0x89 #define CONV_US 8500 // datasheet max 8.2 ms + margin #define RESET_US 1500 // Sensirion CRC-8: polynomial 0x31, init 0xFF, MSB first, no final XOR. static uint8_t crc8(const uint8_t *d, size_t n) { uint8_t c = 0xFF; for (size_t i = 0; i < n; i++) { c ^= d[i]; for (int b = 0; b < 8; b++) c = (c & 0x80) ? (uint8_t)((c << 1) ^ 0x31) : (uint8_t)(c << 1); } return c; } esp_err_t sht40_init(sht40_t *s, bus_t *bus) // clauses 1 and 2 { s->bus = bus; s->valid = false; s->fail_count = 0; uint8_t cmd = CMD_SOFT_RESET; ESP_RETURN_ON_ERROR(bus_write(bus, &cmd, 1), TAG, "reset"); bus_delay_us(RESET_US); uint8_t rx[6]; cmd = CMD_SERIAL; // identity: a real part answers ESP_RETURN_ON_ERROR(bus_write(bus, &cmd, 1), TAG, "serial cmd"); bus_delay_us(1000); ESP_RETURN_ON_ERROR(bus_read(bus, rx, 6), TAG, "serial"); if (crc8(rx, 2) != rx[2] || crc8(rx + 3, 2) != rx[5]) return ESP_ERR_INVALID_CRC; s->serial = ((uint32_t)rx[0] << 24) | (rx[1] << 16) | (rx[3] << 8) | rx[4]; return ESP_OK; } esp_err_t sht40_trigger(sht40_t *s) // clause 3, part one: start, do not wait { uint8_t cmd = CMD_MEASURE_HI; return bus_write(s->bus, &cmd, 1); // caller arms an 8.5 ms one-shot (3.3) } esp_err_t sht40_fetch(sht40_t *s, sht40_sample_t *out) // clauses 4 and 5 { uint8_t rx[6]; esp_err_t err = bus_read(s->bus, rx, 6); if (err != ESP_OK) { s->fail_count++; return err; } if (crc8(rx, 2) != rx[2]) { s->fail_count++; return ESP_ERR_INVALID_CRC; } if (crc8(rx + 3, 2) != rx[5]) { s->fail_count++; return ESP_ERR_INVALID_CRC; } uint16_t st = (rx[0] << 8) | rx[1], sh = (rx[3] << 8) | rx[4]; out->t_milli_c = (int32_t)(-45000 + (175000LL * st) / 65535); // datasheet formula out->rh_permille = (int32_t)(-60 + (1250LL * sh) / 65535); if (out->rh_permille < 0) out->rh_permille = 0; // the datasheet says to clamp if (out->rh_permille > 1000) out->rh_permille = 1000; s->valid = true; s->fail_count = 0; s->last = *out; return ESP_OK; }
Three design decisions in that listing are worth defending. Trigger and fetch are separate functions because the 8.5 ms in between belongs to the state machine, not to a blocked task — the driver refuses to hide a wait it cannot afford to spend. Values are integers in milli-degrees and per-mille, not floats: there is no floating-point unit in the ESP32-C3's RISC-V core for this to be free, the BLE payload carries a scaled integer anyway (canon: temperature as int16 × 100), and integer arithmetic cannot silently produce a NaN that propagates into a report. And the driver counts its own failures, because a sensor that fails one read in a thousand and a sensor that has been dead since April are the same single error to the caller and completely different facts about the product.
SEE ITDriver state machine: five wake cycles, one dying sensor
Assemble the SHT40 driver from the choices below, then run five of Beacon's one-minute wake cycles. The first cycle is always healthy, which is what makes the rest interesting: it gives a "last good value" of 24.6 °C for a lazy error path to reach for. From cycle two onward the fault you selected is present. Watch what reaches the dashboard, what reaches the battery, and — the question that matters — whether anybody downstream could possibly tell that something is wrong.
The result to sit with is "sensor dead" combined with "returns the last good value". Every number on the dashboard is plausible, the battery life is perfect, no log line is red, and the product has been reporting fiction for as long as you care to run it. Compare it with the same fault and the stale policy: the dashboard shows the last known reading with its age, the flags byte in the BLE payload says the sensor is failing, and a gateway-side rule can raise it after three consecutive reports. The difference in code is about four lines. The difference in what the product knows about itself is total.
IN PRACTICEErrors: return, retry, or lie
Every driver call can fail, and there are exactly four things a driver can do about it. Three are defensible.
| Policy | When it is right | When it is a disaster |
|---|---|---|
| Return the error immediately | Almost always. The caller has context the driver does not: whether this reading is critical, whether there is time for another attempt, whether the device should give up and sleep. | When the failure is genuinely transient and the caller has no sensible way to handle it — a single NACK from an EEPROM mid-write, for instance. |
| Bounded retry, then return | Transient bus errors: a NACK, a CRC mismatch, a timeout. Two or three attempts with the bus recovery from 3.5 between them, and a hard limit on total time. | When the retries are unbounded in time. Three retries of a call with a 20 ms timeout is 60 ms — more than Beacon's whole 45 ms active window, and worth budgeting deliberately. |
| Retry until success | Never, in battery-powered firmware. | Always. A dead sensor turns a 45 ms wake into a permanent 40 mA loop, and a device whose battery dies is worse than one that reports an error: it stops telling you anything at all. |
| Return the last good value | Never inside the driver. Staleness is a decision for the layer that knows how the value is used. | Always — because it converts a loud, cheap failure into a silent, expensive one, and because the code that does it usually looks like kindness. |
The useful discipline is to make staleness explicit and let it travel. A sample carries a value, a validity flag, and an age; the state machine (3.7) decides whether to advertise it; the payload's flags byte carries the verdict to the gateway; the gateway's rules decide whether a human hears about it. Each layer makes the decision it is qualified to make, and no layer invents data.
#define MAX_TRIES 2 // 2 × 20 ms worst case — budgeted against the 45 ms window esp_err_t sample_environment(app_t *a, report_t *rep) { esp_err_t err = ESP_FAIL; for (int try = 0; try < MAX_TRIES; try++) { err = sht40_fetch(&a->sht, &a->sample); if (err == ESP_OK) break; ESP_LOGW(TAG, "sht40 try %d: %s", try, esp_err_to_name(err)); if (i2c_bus_is_stuck()) i2c_bus_recover(); // 3.5 — cheap, and it works } if (err == ESP_OK) { rep->t_centi_c = a->sample.t_milli_c / 10; // canon payload: int16 ×100 rep->rh_pct = (uint8_t)(a->sample.rh_permille / 10); rep->flags &= ~(FLAG_T_STALE | FLAG_SENSOR_FAIL); a->last_good_s = now_s(); } else { rep->flags |= FLAG_T_STALE; // the value is old and we say so rep->age_s = now_s() - a->last_good_s; if (a->sht.fail_count >= 3) rep->flags |= FLAG_SENSOR_FAIL; buglog_note(BUG_SHT40, err); // 3.9 / 6.7: evidence, not a guess } return err; // the FSM still advertises: a stale report beats no report (3.7) }
Note what happens on failure: the tag still advertises. That is a deliberate product decision, not a fallback. A report that says "I am alive, my battery is 3.81 V, I moved, and my temperature reading is 41 minutes old" is enormously more useful than silence, which is indistinguishable from a tag that has been stolen, flattened, or dropped behind a cabinet. Making failure visible and specific is most of what separates a pilot that produces knowledge from one that produces a shrug.
COMPARISONWhat to abstract, and what not to
"Hardware abstraction layer" is one of those phrases that arrives with a folder structure attached. Before you create it, ask the only question that matters: what are the two things I need to swap? If the honest answer is "nothing yet", you are about to maintain an interface with one implementation forever, and every future change will cost two edits instead of one.
For Beacon there are exactly two real substitutions, and they are not the same shape:
| What changes | How different is it? | Right mechanism | Wrong mechanism |
|---|---|---|---|
| Dev kit → Beacon Rev A | Pin numbers, the LED type (dev-kit LEDC versus the WS2812B behind a PMOS), and whether the battery divider exists | A board header: board_devkit.h / board_rev_a.h, selected by one Kconfig option. Constants, not function pointers. | A board_t struct of function pointers for pins that never change at run time — indirection with a cost and no benefit |
| Real I2C bus → a fake bus on your laptop | Totally: no ESP-IDF, no hardware, no timing | A four-function bus interface (write, read, write_read, delay_us) that the driver calls and the test replaces | Calling i2c_master_transmit() directly from the driver, which welds the driver to the platform and makes host testing impossible |
That is the whole abstraction budget, and it is deliberately small. The bus interface earns its indirection because it has two genuinely different implementations and one of them makes the driver testable in a second on a laptop. The board header earns nothing at run time because it is resolved at compile time, which is the cheapest abstraction there is. Everything else — a "sensor interface" with one sensor behind it, a "platform layer" wrapping four ESP-IDF calls, a driver registry — is architecture you will read at three in the morning while looking for a bug that is two files away.
Write the abstraction when you have the second implementation in front of you, not when you can imagine it. The second one always differs from what you imagined, which means the interface you designed in advance will need changing anyway — and now it has a user. For Beacon, the fake bus is a real second implementation on day one, which is precisely why the bus interface exists and the sensor interface does not.
EXAMPLETesting a driver without hardware
The SHT40 driver above depends on nothing but four bus functions and the C standard library. That means it compiles on your laptop, which means the error paths that are almost impossible to produce on a bench — a flipped bit, a NACK, a CRC that fails on the second word only — become three-line test cases. This is the single highest-value practice in firmware, and it needs no framework.
#include <assert.h> #include "sht40.h" // The fake bus: a script of bytes the "sensor" will return, and a failure to inject. static uint8_t canned[6]; static esp_err_t next_err = ESP_OK; esp_err_t bus_write(bus_t *b, const uint8_t *d, size_t n) { (void)b;(void)d;(void)n; return next_err; } esp_err_t bus_read(bus_t *b, uint8_t *d, size_t n) { (void)b; memcpy(d, canned, n); return next_err; } void bus_delay_us(uint32_t us) { (void)us; } // time is free on a laptop int main(void) { sht40_t s = {0}; sht40_sample_t out; // 1. A real capture from the bench: 24.59 °C, 51.6 %RH, both CRCs correct. const uint8_t good[6] = { 0x65, 0xCB, 0x0E, 0x76, 0x0B, 0x0A }; memcpy(canned, good, 6); assert(sht40_fetch(&s, &out) == ESP_OK); assert(out.t_milli_c > 24500 && out.t_milli_c < 24700); // 2. One flipped bit in the temperature MSB. Plausible value, wrong CRC. canned[0] ^= 0x10; assert(sht40_fetch(&s, &out) == ESP_ERR_INVALID_CRC); // the point of the CRC // 3. A dead sensor that reads as zeros: the CRC of 0x0000 is not 0x00. memset(canned, 0, sizeof canned); assert(sht40_fetch(&s, &out) == ESP_ERR_INVALID_CRC); // no more −45.00 °C reports // 4. A bus error must not touch the caller's buffer or the cached sample. next_err = ESP_ERR_TIMEOUT; s.valid = true; assert(sht40_fetch(&s, &out) == ESP_ERR_TIMEOUT); assert(s.fail_count == 3); printf("all driver contract tests passed\n"); return 0; }
Test 3 is the one to notice. A dead I2C device that returns all zeros produces a temperature of exactly −45.00 °C through the datasheet formula, which is a value that looks like a sensor reading and passes a naive range check for an indoor product. It does not pass the CRC, because the CRC of two zero bytes with an initial value of 0xFF is not zero. That is the checksum earning its two bytes of bus traffic: it distinguishes "the sensor said zero" from "nothing said anything", which no amount of plausibility filtering downstream can do.
BEACONBeacon's driver layer, fixed for firmware v0
| Function | Contract | Worst-case time |
|---|---|---|
sht40_init() | Soft reset, 1.5 ms wait, serial number read with CRC. Returns ESP_ERR_INVALID_CRC if the part is absent or the bus is bad. | ~5 ms, cold boot only |
sht40_trigger() / sht40_fetch() | Split across the 8.5 ms conversion, which the FSM owns as a timer event. Fetch validates both CRCs and never returns a value it did not verify. | 2 × 20 ms bus timeout worst case |
lis2dh12_init() | WHO_AM_I must read 0x33; memory reboot; then every control register written explicitly — never assume reset defaults after a warm reset. | ~10 ms, cold boot only |
lis2dh12_arm_motion() | 25 Hz low-power, 256 mg threshold, 1-sample duration, latched INT1, source register cleared before sleep (3.4) | ~2 ms |
sample_environment() | At most 2 attempts; bus recovery between them; sets FLAG_T_STALE and, after 3 consecutive failures, FLAG_SENSOR_FAIL; always leaves a report fit to advertise. | ~45 ms typical, ~90 ms worst case |
The flags byte in the canon's 14-byte payload — [company id 2][fw ver 1][seq 1][temp int16 ×100][rh uint8][batt mV uint16][flags 1][moved 1][crc8 1] — is where all of this becomes visible outside the device. Beacon assigns its low bits to exactly the facts a driver can know and a gateway cannot guess: temperature stale, humidity stale, sensor failing, bus recovered since the last report, and the reset reason class from 3.9. Eight bits is not much; that is a feature, because it forces you to choose the five facts that would actually change what someone does.
(1) Drivers depend on a four-function bus interface, not on ESP-IDF directly, so they compile and run on a laptop. (2) Both parts are identified before use — serial number with CRC, and WHO_AM_I = 0x33. (3) Every datasheet wait is enforced inside the driver, and the 8.5 ms conversion is a timer event rather than a blocked task. (4) Both CRC-8 bytes are checked on every SHT40 read; a failure is an error, never a value. (5) Two attempts maximum, with bus recovery between them, then an honest stale report with an age and flag bits. (6) A host test file that covers the good path, a flipped bit, an all-zero sensor, and a bus timeout, run on every commit.
WEAKNESSWhere this bites
Returning the last good value, substituting a default, or averaging over the failure all come from the same decent instinct: do not let one bad reading spoil the data. In a product they do the opposite. They convert a failure the system could have reported into a silence it cannot detect, and the longer the substitution runs the more convincing the fiction becomes — six weeks of two-decimal-place stability is much more persuasive than the truth. If you want smoothing, smooth in the layer that knows what the data is for, on values that arrived with their validity attached. Inside the driver, the only honest outputs are a verified value or a status code.
Datasheets list register defaults "after power-on reset", and firmware that initialises only the registers it wants to change is relying on that list. But an ESP32-C3 reset is not necessarily a power-on reset: a watchdog, a brown-out (2.9), a software reset, and every deep-sleep wake restart the MCU while the sensors on the bus keep their supply and their configuration. The classic symptom is firmware that works perfectly from a cold start and behaves oddly after an OTA update or a crash, because the accelerometer is still in a mode the previous build left it in. The fix is a discipline, not a line of code: initialisation writes every register the driver depends on, explicitly, every time — and starts with the part's own reboot or soft-reset command so that the ones you do not write are at least known.
"Retry until it works" is easy to spot in review. Its cousin is not: three retries of a call whose timeout is 20 ms, wrapped in an outer loop that runs three times, inside a function called from a state that can be re-entered. Nobody wrote an infinite loop; the arithmetic just produced 180 ms of retrying in a 45 ms window, every minute, for a fault that will never clear. Bound retries by total time, not by count, put the bound in a named constant next to the active-window budget it has to fit inside, and log the retry count in the report so the pilot data tells you how often the second attempt was needed. If the answer is "never", delete the retry.
KEY INSIGHTHow this connects
- Serial Buses: UART, I2C, and SPI (3.5) — the transactions this driver issues, the NACK it must interpret, and the bus recovery it calls between retries.
- How to Read a Datasheet (1.6) — the conditions attached to every number. A driver is what a carefully read datasheet looks like once it is executable.
- State Machines and Event-Driven Firmware (3.7) — next: the 8.5 ms conversion the driver refuses to block on becomes a state with a timer, and the error return becomes a transition rather than an exception.
- Debugging Firmware (3.9) —
buglog_note()and the fail counters become the evidence you reason from instead of guessing. - First Power-Up: Bring-Up Order and the Smoke Test (6.1) — the identity checks in this lesson are the first thing that runs on a brand-new board, and they are what makes "it doesn't work" into a specific sentence.
The transferable habit: write the driver's failure behaviour first. Decide what it returns when the part is missing, when the bus is stuck, when the checksum fails, and when the value is impossible — then write the happy path, which is usually four lines and the least interesting part of the file.
GLOSSARYKey terms introduced
- Driver contract
- The five things a driver guarantees: identity, initialisation, timing, validity, and error semantics. Bugs are almost always a missing clause rather than wrong arithmetic.
- Identity check
- Reading a known constant from the device —
WHO_AM_I= 0x33 on the LIS2DH12, the CRC-checked serial number on the SHT40 — before believing anything else it says. - CRC-8 (Sensirion)
- Polynomial 0x31, initial value 0xFF, MSB first, no final XOR, computed over each two-byte word. Catches the flipped bit that a plausibility check cannot, including the all-zero read from a dead part.
- Stale value
- A last-known reading that is explicitly marked as old and carries its age. The honest alternative to silently returning it as if it were fresh.
- Bounded retry
- A retry policy limited by total elapsed time, not by attempt count, so that the worst case fits inside a known budget — for Beacon, the 45 ms active window.
- Turn-on time
- The interval after a power-mode or data-rate change during which a sensor's output is not yet valid. Expressed in output-data-rate periods for the LIS2DH12; the driver, not the caller, must absorb it.
- Board header
- Compile-time constants describing one physical board (pin numbers, fitted parts). The cheapest abstraction: no indirection at run time, one file per board.
- Fake bus
- A test implementation of the driver's bus interface that returns scripted bytes and injects errors, letting the driver's contract be tested on a host in milliseconds instead of on hardware in hours.
ACTIVE RECALLCheck your understanding
Answer in your own words first, then reveal.
1A reviewer proposes: "if the SHT40 read fails, return the previous reading — it's only a minute old and it smooths the data." Give the strongest version of their argument, then the reason it is still wrong, and say what you would do instead.›
The strong version: temperature is a slow-moving physical quantity, a one-minute-old reading is genuinely almost as good as a fresh one, gateways and dashboards are simpler when every report has a number, and a transient bus glitch should not produce a visible gap. All of that is true — for one minute. It fails because the driver cannot tell a one-minute-old value from a six-week-old one, and the policy does not degrade: it produces the same confident number forever, so the failure becomes undetectable exactly when it becomes serious. Do it in the right place instead. The driver returns a status code. The layer above keeps the last good value with its age and a stale flag, still advertises a report (silence is worse), and sets FLAG_SENSOR_FAIL after three consecutive failures. The gateway then applies the policy the reviewer actually wants — "show the last value if it is under five minutes old, otherwise show a warning" — with the information needed to apply it.
2Why does an all-zero response from the SHT40 fail its CRC, and why does that matter more than a range check?›
Sensirion's CRC-8 starts from an initial value of 0xFF, so processing two zero bytes does not yield zero; the checksum byte a dead or absent device supplies (also zero, or 0xFF from a floating bus) will not match. That matters because the all-zero read is precisely the case that survives plausibility filtering: the datasheet formula turns 0x0000 into −45.00 °C, a value with a decimal point, a sign, and the shape of a measurement. A range check tuned for an indoor product might reject it, but the same check will happily pass the more dangerous corruption — a single flipped bit that turns 24.59 °C into 35.52 °C, which is inside every plausible range you would write. The CRC catches both, at a cost of two bytes on the bus and about twenty bytes of code, which is why the sensor sends it.
3Beacon's firmware works from a cold boot but the motion interrupt sometimes fails to arm after a firmware update. What class of bug is this, and which clause of the driver contract was violated?›
It is a reset-defaults assumption, and the clause is initialisation. An OTA update restarts the MCU without removing power from the sensors, so the LIS2DH12 keeps whatever configuration the previous firmware left in it — including, for instance, a latched interrupt whose source register was never read, or an output data rate the new build does not expect. Initialisation that only writes the registers it wants to change relies on power-on defaults that are not present after a warm reset. The fix: begin initialisation with the part's memory reboot (CTRL_REG5 bit 7), wait the specified few milliseconds, then write every control register the driver depends on explicitly, and finish by reading INT1_SRC to clear any stale latch (3.4). The same reasoning applies after a watchdog reset, a brown-out, and every deep-sleep wake, all of which are resets to the MCU and nothing at all to the sensor.
4You are asked to add a hardware abstraction layer so the firmware can run on both a dev kit and Beacon Rev A. What do you build, and what do you refuse to build?›
Build two things. A board header of compile-time constants — pin numbers, whether the battery divider is fitted, which LED type is present — selected by one build option; it costs nothing at run time because it disappears into the compiler. And a four-function bus interface (write, read, write-then-read, delay) that the sensor drivers call instead of ESP-IDF, because that one has a genuine second implementation: the fake bus that lets the drivers be tested on a laptop with scripted bytes and injected errors. Refuse the rest: a sensor interface with one sensor behind it, a platform layer wrapping four ESP-IDF calls, a run-time board object of function pointers for values that are fixed at compile time. Each of those is an interface with one implementation, which is a maintenance cost with no user, and it makes every change two edits instead of one. Write the abstraction when the second implementation is in front of you — as the fake bus is, on day one.