SDASCLUNO328Prt °C0x05C1940x0600540x0704001Wire.beginTransmission(0x18);2Wire.write(reg);3Wire.endTransmission(false);4Wire.requestFrom(0x18, 2);5r = (uint16_t)Wire.read() << 8;6r |= Wire.read();7t = (r & 0x0FFF) / 16.0;t = r / 16.0;8if (r & 0x1000) t -= 256;MCP9808DS25095Adatasheetflags 15-13sign 12temp 11-018ACK06005405C194/1611001944043FB0
Back: the Uno's chip, the I2C bus, the MCP9808 sensor and a logic analyserFront: the driver code, the datasheet and the register split into its bitsTokens: the address, register pointers and data bytes on the SDA wireAn Arduino Uno R3 reads a Microchip MCP9808 over I2C, using only what the datasheet says: address 0x18, pointer 0x05 for the temperature and 0x06 for the maker's ID 0x0054. The first conversion turns 0xC194 into 3097.25 degrees; the analyser shows the bytes are right, the datasheet shows the top three bits are alert flags, and masking them gives 25.25 °C. A cold reading, 0x3FB0, tests the sign bit: -5 °C.

Read the datasheet

  1. 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.

Write the driver

Debug and fix

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.