Read the datasheet
A driver is the code that turns a chip's bytes into a useful value. Ours runs on an Arduino Uno R3 and reads a Microchip MCP9808 temperature sensor over I2C. Everything it needs is in the sensor's datasheet.
The datasheet gives the address as 0011 followed by pins A2, A1, A0. Ours are wired to ground, so it is 0x18. The Uno sends 0x18 on SDA, and the sensor answers ACK: it pulls the line low.
Inside the sensor are 16-bit registers, each picked by a pointer number. Pointer 0x05 holds the temperature, 0x06 the maker's ID and 0x07 the device ID. To read one, you write its pointer, then read two bytes.
Write the driver
Our helper read16(reg) writes the pointer byte, here 0x06 for the maker's ID. endTransmission(false) ends without a stop, so the read follows at once with a repeated start and no other controller can take the bus.
requestFrom asks for two bytes, high byte first: 0x00, then 0x54. 0x0054 is Microchip's ID, as the datasheet promises. If begin() reads anything else, the wiring or address is wrong, so the driver stops and says so.
Now read16(0x05): the bytes 0xC1 and 0x94 arrive, so r = 0xC194. The logic analyser clipped onto SDA and SCL records the same two bytes, so we know exactly what the chip sent.
Debug and fix
Our first line 7 was t = r / 16.0, because each step is 1/16 of a degree. It prints 3,097.25 degrees. The analyser showed the bytes on the wire were right, so the bug is in our code.
The datasheet says the top three bits are alert flags, not temperature. At power-up the alert limits are 0 °C, so in a warm room two flags are set: 0xC1 begins 110. Bit 12 is the sign; only the low 12 bits count.
Line 7 now keeps only the low 12 bits: r & 0x0FFF is 0x194, which is 404. Each step is 0.0625 degree, so 404 / 16 = 25.25 °C. One mask turns nonsense into a sensible room temperature.
Now try the freezer. At -5 °C the register holds 0x3FB0. The low 12 bits give 4,016 / 16 = 251, and the sign bit makes line 8 subtract 256: -5 °C. Test edge cases like this before trusting any driver.
What happens
;; step 1/10 · datasheet driver code that talks to one chip and hides its bytes board Arduino Uno R3 (ATmega328P), I2C on A4 = SDA, A5 = SCL sensor Microchip MCP9808, 2.7 to 5.5 V, I2C up to 400 kHz from the datasheet we need three things: 1 the bus address 2 the register map 3 what each bit of the data means
The card shows the heart of the driver. In the full sketch, lines 1 to 6 live in read16(reg), which returns r; mcpBegin() checks read16(0x06) == 0x0054; mcpReadC() runs lines 7 and 8 on read16(0x05). The MCP9808 datasheet (Register 5-4) puts three alert flags in bits 15 to 13, comparing the temperature with the TCRIT, TUPPER and TLOWER limit registers. Those limits are 0 °C at power-up, so a fresh sensor in a warm room reports flags 110 and in a freezer 001.