← About PHYS 351

PHYS 351 · Advanced Instrumentation

Lecture 06 · Digital temperature sensing

1 Where Lab 6 Sits

Lab 4 and Lab 5 were about moving power around: a pin commands, a transistor switches, a motor turns. The MCP9808 is the opposite kind of device. It draws so little current that its VDD pin connects directly to the Pi's 3.3 V supply: no driver, no separate supply, no flyback diode.

What is difficult this week is not the power, it is the conversation. Until now every pin meant one thing: high or low, on or off. From this week a pin carries a protocol: a shared agreement about when a bit is valid, how a device is addressed, and how it says yes. Lab 6 is also, as the handout says plainly, a practical exercise in reading a datasheet, and that is a skill this course is deliberately building.

The one idea to carry out of this lecture

A digital sensor does not send you a temperature. It sends you bits from a numbered register, in a format the datasheet defines. Your job is to know which register to ask for, and how to turn what comes back into a physical quantity with units. The protocol delivers the bits; the datasheet gives them meaning.

1.1 Task map

Lab 6 taskWhat you doConcept & section
1Make a lab directory; enable I²C with raspi-config; rebootBringing the bus up (§13.2)
2Wire the sensor with the Pi off; run i2cdetect -y 1 and find address 18; use the provided module; note its limitationBus topology, addressing, resolution (§5, §7, §12)
3Write read_temp_high_res() for exactly 0.125 °C, from the datasheet, with correct sign handlingRegister bit layout and decoding (§10, §11)
4°C and °F; a critical-temperature warning; 100+ logged measurements; a plot; a CSV fileFrom a reading to a dataset (§14)
5Extra credit: a live scrolling animated plot§14.4

2 Parallel and Serial Communication

2.1 Two ways to move a byte

To move eight bits from one chip to another there are two obvious schemes.

Parallel: use eight wires, one per bit, and send D7 through D0 all at once. One clock tick moves a whole byte.

Serial: use one data wire and send the bits one after another, here most significant bit first (UART, as you will see in §4, sends the least significant bit first). Eight clock ticks move one byte.

So for one byte, parallel costs eight data wires and serial costs eight clock ticks. Both also need a ground, and usually a clock or strobe line; some serial links manage without a clock wire by recovering the timing from the data itself.

Timing diagram of the byte 0x33 sent two ways. Top: eight data wires D7 to D0 each hold one bit during a single clock tick, marked by one strobe pulse, leaving the next seven ticks free. Bottom: one data wire carries the bits 0 0 1 1 0 0 1 1 one per tick, most-significant bit first, with a clock pulse in every tick, taking eight ticks.
Figure 1. The byte 0x33 sent two ways. Top: eight data wires, D7 to D0, each hold one bit during a single clock tick, marked by one strobe pulse, leaving the next seven ticks free. Bottom: one data wire carries the bits 0 0 1 1 0 0 1 1 one per tick, most-significant bit first, with a clock pulse in every tick, taking eight ticks.

2.2 So which is faster?

Intuitively parallel should win by a factor of eight. The history says otherwise, and the comparison is worth remembering:

InterfaceIntroducedTypeThroughput
PATA
Parallel AT Attachment
1986parallel66 / 100 / 133 MB per second
SATA
Serial ATA
2003serial150 / 300 / 600 MB per second

PATA moved its data on 16 wires through a 40-pin plug; SATA uses two differential pairs and a 7-pin plug. The serial interface replaced the parallel one and is several times faster. The same story repeats everywhere: USB replaced the parallel printer port, PCI Express replaced PCI, many computer interconnects now use high-speed serial lanes.

Why serial wins: three reasons
  1. Skew. Eight parallel bits must arrive simultaneously. Traces differ slightly in length and loading, so bits drift apart in time as the clock rises. The fastest usable clock is set by the worst-case spread, not by any one wire. A single serial lane has no such spread to worry about, though it still has timing limits of its own, from jitter and signal distortion.
  2. Crosstalk. Eight wires switching together in a ribbon couple into one another capacitively and inductively. The noise grows with edge rate, so going faster makes it worse, and the problem limits itself.
  3. Cost and size. Eight wires, eight connector pins and eight driver circuits cost more than one. On a board with limited pins, like the Raspberry Pi with its 40-pin header, pins are the scarcest resource of all.

In short, serial trades cleverer electronics for fewer pins and faster clocks. Parallel is not dead, though: over very short distances, such as between a processor and its memory, width still wins.

Eight parallel data wires switching at slightly different times. With a slow clock a wide window remains between the latest edge and the next transition in which all eight are settled and safe to read. With a clock three times faster the skew regions of successive transitions overlap and there is no moment when all eight wires are settled.
Figure 2. Skew in pictures. Eight parallel data wires switch at slightly different times. With a slow clock, a wide window remains between the latest edge and the next transition, in which all eight are settled and safe to read. With a clock three times faster, the skew regions of successive transitions overlap and there is no moment when all eight wires are settled. Parallel timing must allow for the spread between wires; a serial lane avoids this particular source of skew.

This matters for the rest of the course. Every sensor from here on (the MCP9808 this week, the LIS3DH in Lab 7, the MCP3008 in Lab 8) uses two or four wires instead of eight or sixteen, and that is why several of them can share the same header.

3 Inside the MCP9808: Sensor, ADC, Registers

Inside the package are four blocks, and the datasheet describes each one:

  1. An analog temperature sensor: a bandgap circuit whose output voltage depends on absolute temperature.
  2. An ADC that digitizes it.
  3. A set of registers holding the result, the configuration, and the alert limits.
  4. An I²C interface giving access to those registers.

The datasheet’s block diagram shows them. A band-gap sensor makes a voltage that depends on temperature. A delta-sigma (ΔΣ) ADC turns it into a number every 30–250 ms, depending on the resolution chosen (§12). The number waits in a register, one of eight, until someone asks for it. The Pi never sees a voltage: it asks for a register over I²C, and the rest of this lecture is about how.

MCP9808 datasheet functional block diagram: a band-gap temperature sensor feeds a delta-sigma ADC with selectable resolution of 0.5 to 0.0625 degrees; its result goes to the temperature register, alongside configuration, limit, ID and resolution registers selected by a register pointer, all reached through an SMBus/I2C interface on pins SDA and SCL, with address pins A0 to A2.
Figure 3. The MCP9808 functional block diagram. A band-gap temperature sensor feeds a ΔΣ ADC with a selectable resolution of 0.5 to 0.0625 °C. Its result goes to the temperature register, alongside the configuration, limit, ID and resolution registers, all selected by a register pointer and reached through the SMBus/I²C interface on SDA and SCL, with address pins A0–A2. Source: Microchip DS20005095B.

This is the general shape of every modern digital sensor, and recognizing it is more useful than memorizing any one part. In Lab 7 the LIS3DH has exactly the same architecture with an accelerometer at the front; in Lab 8 the MCP3008 is essentially block 2 on its own, exposed over SPI.

4 Asynchronous and Synchronous

Serial links divide into two families by how the receiver knows when to sample.

FamilyHow timing is agreedExamples and consequences
AsynchronousNo clock is transmitted. Both ends are configured in advance for the same bit rate, and each byte carries start and stop bits so the receiver can re-align.UART (Universal Asynchronous Receiver Transmitter). Both ends must agree on baud rate and frame format; a mismatch produces framing errors or incorrect characters.
SynchronousA clock line is transmitted alongside the data. The transmitter says explicitly when each bit is valid.I²C and SPI. The controller supplies the clock, but its rate, edge timing and any pauses must meet the device specifications. This is what the lab sensors use.

USB is neither of these: it has its own packet protocol and recovers its timing from the signal itself, with no UART-style start and stop bits. It often looks like a serial port, though, because a USB-to-UART adapter, or a microcontroller with built-in USB, can present itself to the computer as one. And a terminal window on the Pi has nothing to do with UART at all; it is just a program.

Two timing diagrams. Top, UART: one transmit line carries a start bit, eight data bits least-significant first and a stop bit; the receiver samples the middle of each bit with its own clock, so both ends must agree on 9600 baud. Bottom, I2C: SDA carries eight bits most-significant first while SCL pulses with uneven periods; the receiver reads SDA on every SCL rising edge.
Figure 4. Asynchronous against synchronous. Top, UART: one transmit line carries a start bit, eight data bits least-significant first, and a stop bit; the receiver samples the middle of each bit with its own clock, so both ends must agree on the rate (9600 baud here). Bottom, I²C: SDA carries eight bits most-significant first while SCL pulses, even with uneven periods; the receiver reads SDA on every SCL rising edge. The clock travels with the data.

Lab 6 uses I²C; Lab 8 uses SPI. Both are synchronous, and comparing them is a natural report discussion.

5 The I²C Bus

I²C (Inter-Integrated Circuit) needs exactly two signal wires no matter how many devices are attached:

  • SDA: serial data
  • SCL: serial clock

Every device connects to the same two lines, in parallel. A controller (the Raspberry Pi) starts every transaction and generates the clock; each peripheral has an address and answers only when called. A temperature sensor, an accelerometer, a display and a real-time clock can all share those two wires, which is exactly what happens in Lab 7, where the MCP9808 joins the LIS3DH on the same bus.

I2C bus schematic: a Raspberry Pi controller and three MCP9808 sensors all connect to the same two lines, SDA and SCL, which are each pulled up to 3.3 volts by a resistor. The sensors' address pins A2 A1 A0 are 000, 001 and 010, giving addresses 0x18, 0x19 and 0x1A.
Figure 5. Every device hangs off the same two wires. Adding a sensor costs no extra pins on the Pi, only a distinct address. Here a Raspberry Pi controller and three MCP9808 sensors share SDA and SCL, each line pulled up to 3.3 V by a resistor. The sensors’ address pins A2 A1 A0 are 000, 001 and 010, giving addresses 0x18, 0x19 and 0x1A (§7.1). Only the chip whose 7-bit address is called answers.

5.1 Open drain, pull-ups, and why low wins

This is the piece of I²C that explains the rest of it, so it is worth getting straight.

Every device connects to SDA and SCL through an open-drain output: a transistor that can pull the line down to ground, but has no ability to drive it up. Pulling the line high is the job of the pull-up resistors, one on SDA and one on SCL, both to VDD = 3.3 V.

The transistor is the N-channel MOSFET of Lecture 04, with its source grounded and its drain on the bus line. Each chip can only pull the line low or let go. Nobody drives the line high.

Open-drain SDA line in two states. The line is pulled up to 3.3 volts by a resistor and three N-channel MOSFETs, for the Pi, the sensor and another chip, can each connect it to ground. With all switches off the line sits near 3.3 volts, high. With the sensor's switch on, current flows through the pull-up and the switch and the line sits near 0 volts, low.
Figure 6. An open-drain SDA line in two states. The line is pulled up to 3.3 V by a resistor, and three N-channel MOSFETs (one each for the Pi, the sensor and another chip) can each connect it to ground. With all switches off the line sits near 3.3 V, high. With the sensor’s switch on, current flows through the pull-up and the switch, and the line sits near 0 V, low.
MCP9808 datasheet Figure 5-9: the Alert output is an internal N-channel MOSFET to ground with an external pull-up resistor R_PU to V_DD.
Figure 7. The MCP9808’s own Alert output drawn the same way: an internal N-channel MOSFET to ground, with an external pull-up resistor RPU to VDD. Source: MCP9808 datasheet, Fig. 5-9.
Why it must be built this way

If two devices could actively drive the line, one driving high while another drove low would short the supply to ground through two transistors. That is called bus contention, and it can destroy chips. With open-drain outputs that cannot happen: the worst case is several devices pulling low at once, which is harmless.

The consequences follow directly:

  • Both lines sit high when the bus is idle, because nobody is pulling them down.
  • Low wins. A high needs every device to let go, but any one device holding the line low overrides everyone else. That is exactly what makes the acknowledge bit (§6.3) work, which is why ACK is a low. Ordinary data bits are still high for 1 and low for 0.
  • The pull-up resistors are not optional. Without them the lines never reach a valid high level and nothing works at all.

The pull-up value is a compromise. Too large, and the rise time is slow because the resistor must charge the bus capacitance, rounding the edges and limiting the clock rate. Too small, and the current when a device pulls low becomes excessive. A few kilohms is typical.

Good news for this lab

The Adafruit MCP9808 breakout board already has the pull-up resistors fitted, and the Raspberry Pi has its own on the I²C pins. You do not need to add any. This is one of the reasons a breakout board is worth using: it carries the sensor, its decoupling and its pull-ups, and it brings everything to a 0.1 inch header that fits a breadboard.

It is still worth knowing they are there. If you later put several breakout boards on one bus, their pull-ups sit in parallel and the effective resistance falls, occasionally enough to matter.

5.2 The pull-up sets how fast the line rises

The two edges of an I²C signal are not symmetric. Falling is fast: a MOSFET switched on discharges the wire’s capacitance almost instantly. Rising is slow: once every device lets go, only the pull-up resistor recharges that capacitance, with time constant

τ = Rpull-up Cbus(1)

On our bench the Pi’s own 1.8 kΩ pull-ups sit in parallel with the breakout’s 10 kΩ ones:

R = 1.8 kΩ × 10 kΩ1.8 kΩ + 10 kΩ ≈ 1.5 kΩ

The line reads as high once it passes 0.7 VDD = 2.31 V, which takes −τ ln(1 − 0.7) ≈ 1.2τ. For an illustrative bus capacitance of 100 pF, 1.5 kΩ gives τ = 0.15 µs and a crossing after about 0.18 µs. A 10 kΩ pull-up alone would give τ = 1 µs and a crossing after about 1.2 µs, a large slice of a clock period at 100 kHz (10 µs).

The price of the stiffer pull-up is current. While a device holds the line low, 3.3 V/1.5 kΩ ≈ 2.2 mA flows through the resistors into its transistor. That is the compromise described above, with numbers.

SDA voltage against time in microseconds. A chip pulls the line from 3.3 volts to 0 volts almost instantly, then releases it at 2 microseconds. With a 10 kilohm pull-up and 100 picofarads the line recovers with a 1 microsecond time constant and crosses the 2.31 volt input-high threshold about 1.2 microseconds later; with 1.5 kilohms, the Pi's 1.8 kilohm pull-up in parallel with the breakout's 10 kilohm one, the time constant is 0.15 microseconds and the crossing comes after about 0.18 microseconds. Capacitance is illustrative.
Figure 8. SDA against time. A chip pulls the line from 3.3 V to 0 V almost instantly, then releases it at 2 µs. With a 10 kΩ pull-up and 100 pF the line recovers with a 1 µs time constant and crosses the 2.31 V input-high threshold about 1.2 µs later. With 1.5 kΩ (the Pi’s 1.8 kΩ in parallel with the breakout’s 10 kΩ) the time constant is 0.15 µs and the crossing comes after about 0.18 µs. The capacitance is illustrative.

6 I²C Timing

Four events define the protocol. All of them are about the relationship between SDA and SCL, never about either line alone.

6.1 When data is valid

The rule that makes START and STOP unambiguous

During data transfer, SDA must hold steady for the whole time SCL is high. SDA is only permitted to change while SCL is low. The receiver samples on the rising edge of the clock, when the data is guaranteed stable.

(These are the rules for the standard and fast bus speeds used here; §3.1 of the NXP I²C specification has the details.) This is why a change on SDA while SCL is high is reserved: it cannot be data, so it can only be a START or a STOP. One rule gives the protocol both its sampling discipline and its framing.

The Pi makes the clock. Whoever is sending sets SDA while SCL is low; the receiver reads it while SCL is high.

I2C data-valid rule for the bits 1 0 1 1 0. SDA changes only in the shaded intervals where SCL is low; during each SCL high interval SDA is held steady, and arrows at the SCL rising edges mark where the receiver reads the bit.
Figure 9. The data-valid rule for the bits 1 0 1 1 0. SDA changes only in the shaded intervals where SCL is low; during each SCL-high interval SDA is held steady, and the arrows at the SCL rising edges mark where the receiver reads each bit.

6.2 START and STOP

ConditionWhat happens on the wiresMeaning
STARTSDA is pulled low while SCL stays highThe controller claims the bus. Everything that follows belongs to this transaction.
STOPSCL rises first, then SDA risesThe bus is released and returns to idle, both lines high.
Repeated STARTA second START with no intervening STOPThe controller keeps the bus and begins a new phase, typically switching from writing a register address to reading that register's contents (§9.2).
A short I2C frame. START: with SCL high, SDA falls. Then three data bits 1 0 1, with SDA changing only while SCL is low. STOP: SCL rises and then SDA rises while SCL is high. Both lines are high when the bus is idle.
Figure 10. START and STOP break the rule on purpose. A short frame: START (SDA falls while SCL is high), three data bits 1 0 1 with SDA changing only while SCL is low, then STOP (SCL rises, then SDA rises while SCL is high). START and STOP are the only times SDA is allowed to change while SCL is high, which is exactly what makes them unmistakable. When the bus is idle, both lines are high.

6.3 The ninth bit: ACK and NAK

Every byte on an I²C bus is nine clock pulses, not eight. After the eight data bits, the transmitter releases SDA. The controller generates the ninth clock, just as it generates the first eight, and the receiver supplies ACK or NAK:

Bit 9SDANameMeaning
0pulled lowACKReceived. Carry on: more to come.
1left highNAKNo acknowledgment. Either nobody is at that address, or the receiver has had enough: stop, done.

Notice that a low means yes. That is the active-low convention of §5.1 again: acknowledging takes deliberate effort (a device must pull the line down), whereas silence leaves the pull-up resistor to produce a high. An absent, misaddressed or dead device therefore returns NAK automatically, simply by doing nothing.

One I2C byte with its acknowledge. After START the Pi sends 0 0 1 1 0 0 0 0, most-significant bit first, on clocks 1 to 8; on clock 9 the sensor holds SDA low as ACK. Line color shows who holds SDA: Pi, sensor, or nobody (the pull-up).
Figure 11. Eight bits, then a ninth clock for the answer. After START the Pi sends 0 0 1 1 0 0 0 0, most-significant bit first, on clocks 1 to 8; on clock 9 the sender lets go of SDA and the sensor holds it low as ACK. The line color shows who holds SDA: the Pi, the sensor, or nobody (the pull-up).

A high on clock 9 therefore means different things depending on who is receiving. When the Pi is sending, a NAK after the address byte means no device answered to that address, and a NAK after a data byte means the device refused it or cannot take any more. When the Pi is receiving, the NAK is the Pi’s own, and it means “that was the last byte I want” (§9.2).

Three versions of clock 9. ACK: the receiver pulls SDA low. NAK: nobody pulls SDA low, so the pull-up keeps it high, meaning no chip answered that address. NAK from the Pi: after receiving the last byte it leaves SDA high to say it wants no more.
Figure 12. Three versions of clock 9. ACK: the receiver pulls SDA low. NAK: nobody pulls SDA low, so the pull-up keeps it high: no chip answered that address. NAK from the Pi: after receiving the last byte it leaves SDA high to say it wants no more.
This is your first diagnostic

When i2cdetect shows an address, it is reporting that something at that address pulled SDA low. When your Python raises an I/O error on a read, the usual cause is a NAK: nothing answered. Less often it is a wrong register number, a busy device, a transaction the chip does not support, or a fault on the bus. Check power, wiring and address first, then the transaction itself.

7 Device Addressing

The first byte after START carries a 7-bit device address in bits 7–1, with bit 0 as the direction flag:

bit 0 = 1 → read       bit 0 = 0 → write(2)
7-bit and 8-bit addresses are the same address

This is the most common confusion in I²C, and it produces a device that seems to be at two different places at once.

The MCP9808's default address is 0x18 as a 7-bit address. Shift it left by one to make room for the direction bit and you get 0x30, the “8-bit write address”; adding the read bit gives 0x31. All three numbers describe the same chip.

Linux tools and Python libraries on the Pi use the 7-bit convention, so i2cdetect shows 18 and that is what you pass to the library. Many datasheets list the 8-bit form instead, which is why you will sometimes see an address that looks doubled. i2cdetect always shows the 7-bit address.

The address is 7 bits; the 8th bit says the direction. 0x18 in code is 0x30 or 0x31 on the wire.

The MCP9808 address byte: bits 7 to 4 are fixed at 0011, bits 3 to 1 are the address pins A2 A1 A0, and bit 0 is read (1) or write (0). With the pins at 000 the 7-bit address is 0011000 = 0x18, used by Linux and Python; on the wire the write byte is 0x30 and the read byte is 0x31.
Figure 13. The MCP9808 address byte. Bits 7 to 4 are fixed at 0011, bits 3 to 1 are the address pins A2 A1 A0, and bit 0 is read (1) or write (0). With the pins at 000 the 7-bit address is 0011000 = 0x18, the number Linux and Python use; on the wire the write byte is 0x30 and the read byte 0x31.
MCP9808 datasheet Figure 4-1, device addressing: after START, SCL clocks 1 to 8 carry the address code 0 0 1 1, the pin-selected bits A2 A1 A0 and the read/write bit, and on clock 9 the MCP9808 responds with ACK.
Figure 14. The datasheet’s version: after START, SCL clocks 1 to 8 carry the address code 0011, the pin-selected bits A2 A1 A0 and the read/write bit, and on clock 9 the MCP9808 responds with ACK. Source: MCP9808 datasheet, Fig. 4-1.

7.1 The address pins

The MCP9808's three address pins A2, A1 and A0 occupy bits 3, 2 and 1 of the address byte, and are pulled low on the breakout used here, giving 000 and therefore the base address 0x18. (On a bare chip or a different board, check how those pins are wired; do not assume an unconnected pin reads low.) Tying them high in the eight possible combinations gives eight addresses, 0x18 through 0x1F, so eight of these sensors can share one bus.

Leave them unconnected for this lab. Their existence is worth understanding, though: it is the standard answer to “what if I need two of the same chip?”, and it is why an address collision between two different chip types is a real design constraint.

Practice 7

(a) Write out the eight bits of the first byte for a write to the MCP9808 at its default address, and give the byte in hexadecimal.

(b) Do the same for a read.

(c) A2, A1 and A0 are tied to 0, 1, 1. What 7-bit address does the device now have?

(d) A datasheet lists a write-address byte of 0x30. What address should i2cdetect show, and what address should Python use? If the scan really shows 0x30, why is that not simply a display convention?

(e) Decode the first byte of the trace below, the one from the lecture. Read SDA at the middle of each SCL high. Which 7-bit address is called? Is it a read or a write? Who answers on clock 9, and why? Our sensor sits at 0x18.

Unlabelled I2C trace for an exercise: START, then nine SCL clocks numbered 1 to 9 with SDA levels to be read at each clock, then STOP.
Figure 15. An unlabelled I²C trace for Practice 7(e): START, then nine SCL clocks numbered 1 to 9 with the SDA level to be read at each, then STOP.

8 Registers: Address, Pointer and the Register Map

8.1 The address picks the chip; the pointer picks the register

Two different numbers take part in every register access, and it is easy to blur them. The device address, 0x18, lives on the bus: it is set by the board and its address pins, and it picks one chip out of everything on SDA and SCL. The register pointer, 0x05 for the temperature, exists only inside the chip: it picks one of the MCP9808’s eight registers, and you send it as the first data byte after the address.

Two-level selection. On the bus, the address 0x18 picks one chip out of three. Inside that MCP9808, the register pointer 0x05 picks the ambient-temperature register from the list 0x01 CONFIG, 0x02 T_UPPER, 0x03 T_LOWER, 0x04 T_CRIT, 0x05 T_A, 0x06 manufacturer ID 0x0054, 0x07 device ID 0x0400 and 0x08 resolution.
Figure 16. Selection at two levels. On the bus, the address 0x18 picks one chip out of three. Inside that MCP9808, the register pointer 0x05 picks the ambient-temperature register from the list 0x01 CONFIG, 0x02 TUPPER, 0x03 TLOWER, 0x04 TCRIT, 0x05 TA, 0x06 manufacturer ID (0x0054), 0x07 device ID (0x0400) and 0x08 resolution.

8.2 The register map

Every exchange with the sensor reads or writes one numbered register, chosen by a one-byte pointer. Most registers are two bytes wide, including the temperature and the two IDs; the resolution register is the one-byte exception. Always read a register at its own width.

RegisterPointerAccessContents / power-up value
Configuration0x01read/write0x0000; alert behavior, hysteresis, shutdown, locks
T upper limit0x02read/write0x0000
T lower limit0x03read/write0x0000
T critical0x04read/write0x0000
Ambient temperature TA0x05read onlyThe measurement itself, and the subject of Task 3
Manufacturer ID0x06read only0x0054, a fixed, known value
Device ID / revision0x07read onlyDevice ID 0x04 in the high byte; silicon revision in the low byte (0x00 in this datasheet)
Resolution0x08read/write0x03 at power-up (see §12)
The best debugging trick in this lab

Register 0x06 contains manufacturer ID 0x0054. Register 0x07 has device ID 0x04 in its high byte and a revision number in its low byte; the datasheet lists revision 0x00, giving 0x0400. Neither value ever changes with temperature or settings.

So read one of them first. If the ID comes back right, your wiring, address, register read and byte order are working, at least for this read. If you get something else, or an error, the fault is upstream and there is no point studying your bit manipulation yet.

This split-the-problem-in-half move is worth remembering for Labs 7 and 8 as well; most sensors have an equivalent ID register.

8.3 The configuration register

Register 0x01 is 16 bits of behavior settings. Lab 6 does not require you to change it, but reading the bit map is good datasheet practice and explains what the sensor can do:

BitsFunctionBitsFunction
15–11unused5Clear alert
10–9Hysteresis4Alert status
8Shutdown mode3Alert output control
7Critical trip lock2Critical alert only
6Alarm window lock1Alert polarity
  0Alert comparator / interrupt mode

9 Reading and Writing Registers with smbus2

On the Pi, Python talks to the I²C bus through the smbus2 library (pypi.org/project/smbus2). It is already installed on the lab Pis; the provided mcp9808_mod.py uses it. The examples below assume bus is an open SMBus(1) object, as in §9.4 and §13.3. Each call runs one bus transaction, and each figure shows its bytes in order.

9.1 Writing a register: address, pointer, value

A write to a one-byte register uses three bytes, all sent by the Pi: the address byte with the write bit, the register pointer, and the new value. The sensor ACKs every byte. For example, to set the resolution register (0x08) to 0x01, the 0.25 °C setting of §12:

bus.write_byte_data(0x18, 0x08, 0x01)  # address, register, value

Example only. Do not copy this code as it is: read it, learn from it, then write your own.

Register-write transaction: START, 0x30 (address 0x18 plus write), ACK from the sensor, 0x08 (pointer to the resolution register), ACK, 0x01 (new value, 0.25 degree steps), ACK, STOP. All three bytes come from the Pi.
Figure 17. A register write: START, 0x30 (address 0x18 plus the write bit), ACK from the sensor, 0x08 (the pointer to the resolution register), ACK, 0x01 (the new value, 0.25 °C steps), ACK, STOP. All three bytes come from the Pi.

9.2 Reading a register: set the pointer, then read

Reading a register from an I²C sensor takes two phases in one transaction, which is exactly what the repeated START is for:

  1. START
  2. Send the 7-bit device address with the write bit, so the sensor listens, then ACK
  3. Send the register address you want (this is the “pointer”), then ACK
  4. Repeated START
  5. Send the same device address with the read bit, then ACK
  6. Read the first data byte; the controller sends ACK to say “another, please”
  7. Read the second data byte; the controller sends NAK to say “that is enough”
  8. STOP

Step 6 and 7 are worth pausing on: the ACK after the first byte is what tells the sensor to keep going, and the NAK after the second is what ends the read. The MCP9808's temperature register is 16 bits wide, so its read is exactly two bytes: a high byte and a low byte. The resolution register is the one-byte exception.

Register-read transaction in two parts. First the Pi sets the pointer: START, 0x30, sensor ACK, 0x05, sensor ACK. Then, after a repeated START with no STOP, the Pi sends 0x31, the sensor ACKs and sends the upper byte 0xC1, the Pi ACKs, the sensor sends the lower byte 0x1C, the Pi NAKs, and the Pi sends STOP.
Figure 18. A register read in two parts. First the Pi sets the pointer: START, 0x30, sensor ACK, 0x05, sensor ACK. Then, after a repeated START (Sr) that turns the bus around without a STOP, the Pi sends 0x31, the sensor ACKs and sends the upper byte 0xC1, the Pi ACKs, the sensor sends the lower byte 0x1C, the Pi NAKs, and the Pi sends STOP. The upper byte comes first.

The datasheet draws the same five bytes, bit by bit. In its example the sensor sent 0x01 0x94, which is +25.25 °C (decode it with §11 as a check). Its note makes a useful point: if the pointer is already at 0x05 from an earlier access, the first half can be skipped.

MCP9808 datasheet Figure 5-5, reading +25.25 degrees from the temperature register: START, address byte with write, ACK, T_A pointer 0000 0101, ACK; then START, address byte with read, ACK, MSB data 0000 0001, ACK from the master, LSB data 1001 0100, NAK from the master, STOP. A note says the pointer need not be sent again if it was already set.
Figure 19. Reading +25.25 °C from the temperature register: START, address byte with write, ACK, the TA pointer 0000 0101, ACK; then START, address byte with read, ACK, MSB data 0000 0001, ACK from the master, LSB data 1001 0100, NAK from the master, STOP. Source: MCP9808 datasheet, Fig. 5-5.

In your program a library performs all of this in one call, but knowing the sequence is what lets you interpret a logic-analyzer trace, and it is why the transaction can fail in several distinct ways.

9.3 smbus2: one call runs the whole read

All eight steps of §9.2 are one library call:

hi, lo = bus.read_i2c_block_data(0x18, 0x05, 2)   # address, register, count

Example only. Do not copy this code as it is: read it, learn from it, then write your own.

You give the 7-bit address; the Pi adds the R/W bit, the START, the repeated START, the ACKs, the final NAK and the STOP. The address 0x18 becomes both address bytes, 0x30 and 0x31. The register 0x05 becomes the pointer byte. The count 2 asks for the two data bytes, which come back as a list in wire order, upper byte first.

How bus.read_i2c_block_data(0x18, 0x05, 2) maps onto the wire: the address 0x18 becomes both address bytes 0x30 and 0x31, the register 0x05 becomes the pointer byte, and the count 2 asks for the two data bytes 0xC1 and 0x1C, which the call returns as the list [0xC1, 0x1C] in wire order.
Figure 20. How bus.read_i2c_block_data(0x18, 0x05, 2) maps onto the wire: the address 0x18 becomes both address bytes 0x30 and 0x31, the register 0x05 becomes the pointer byte, and the count 2 asks for the two data bytes 0xC1 and 0x1C, which the call returns as the list [0xC1, 0x1C] in wire order.

9.4 The same read, spelled out as two messages

smbus2 can also send plain I²C messages, which makes the structure of the read explicit. i2c_msg.write is the first half (address and pointer), i2c_msg.read the second half (address and two data bytes), and i2c_rdwr sends them as a single transaction with a repeated START between them and one STOP at the end:

from smbus2 import SMBus, i2c_msg

write = i2c_msg.write(0x18, [0x05])
read = i2c_msg.read(0x18, 2)
with SMBus(1) as bus:
    bus.i2c_rdwr(write, read)
hi, lo = list(read)      # 0xC1, 0x1C

Example only. Do not copy this code as it is: read it, learn from it, then write your own.

i2c_rdwr is plain I²C, not SMBus: any mix of writes and reads in one transaction. It is worth knowing for chips whose transactions do not fit the SMBus patterns.

The same read as two smbus2 messages: i2c_msg.write(0x18, [0x05]) covers the address byte and pointer, i2c_msg.read(0x18, 2) covers the read address byte and two data bytes, and bus.i2c_rdwr(write, read) sends them as one transaction with a repeated START between them and one STOP at the end.
Figure 21. The same read as two smbus2 messages: i2c_msg.write(0x18, [0x05]) covers the address byte and the pointer, i2c_msg.read(0x18, 2) covers the read address byte and the two data bytes, and bus.i2c_rdwr(write, read) sends them as one transaction with a repeated START between them and one STOP at the end.

9.5 read_word_data hands you the bytes swapped

smbus2 also has read_word_data(0x18, 0x05), which runs the identical bus transaction and returns one 16-bit number. But SMBus defines a “word” as low byte first, while the MCP9808 sends its high byte first. So for the bytes 0xC1, 0x1C, the call returns 0x1CC1, not 0xC11C.

With read_i2c_block_data you combine the bytes yourself: hi << 8 | lo gives 0xC11C, correct. With read_word_data you must swap the two bytes back first. The provided mcp9808_mod.py uses read_word_data and does exactly that swap, and i2cget ... w shows the same effect on the command line (§13.2).

Byte order. The sensor sends 0xC1 then 0x1C. read_i2c_block_data returns [0xC1, 0x1C], and shifting the first byte left by 8 gives 0xC11C, correct. read_word_data returns 0x1CC1 because SMBus words are low byte first; swapping the bytes gives 0xC11C.
Figure 22. Byte order. The sensor sends 0xC1 then 0x1C. read_i2c_block_data returns [0xC1, 0x1C], and shifting the first byte left by 8 gives 0xC11C, which is correct. read_word_data returns 0x1CC1 because SMBus words are low byte first; swapping the bytes gives 0xC11C.

10 The Ambient Temperature Register

Register 0x05 is where Task 3 lives. Its sixteen bits are not a plain integer: the top three are alert flags and the bottom thirteen form a signed fixed-point number.

The 16 bits of the MCP9808 ambient-temperature register. Bits 15 to 13 are alert flags (T at or above T_CRIT, above T_UPPER, below T_LOWER), bit 12 is the sign, bits 11 to 4 are whole degrees weighted 128 down to 1, and bits 3 to 0 are fractions weighted one half, one quarter, one eighth and one sixteenth of a degree. The upper byte is sent first.
Figure 23. The 16 bits of the ambient-temperature register. Bits 15 to 13 are alert flags (TA at or above TCRIT, above TUPPER, below TLOWER), bit 12 is the sign, bits 11 to 4 are whole degrees weighted 128 down to 1, and bits 3 to 0 are fractions weighted ½, ¼, ⅛ and 1/16 of a degree. The upper byte is sent first.
MCP9808 datasheet Register 5-4, the ambient-temperature register: bits 15 to 13 compare T_A with T_CRIT, T_UPPER and T_LOWER, bit 12 is the sign, and bits 11 to 0 weigh 2 to the 7 down to 2 to the minus 4 degrees Celsius.
Figure 24. The same register in the datasheet: bits 15 to 13 compare TA with TCRIT, TUPPER and TLOWER, bit 12 is the sign, and bits 11 to 0 weigh 27 down to 2−4 °C. Source: MCP9808 datasheet, Register 5-4.

The same layout as two tables, one per byte:

Bit15141312111098
MeaningTA ≥ TcritTA > TupperTA < TlowerSIGN
TA < 0°C
27262524
Bit76543210
Meaning232221202−1
0.5
2−2
0.25
2−3
0.125
2−4
0.0625
Read this layout carefully: Task 3 depends on it
  • Bits 15, 14, 13 are comparison flags against the limit registers. They are not part of the number and must be removed before any arithmetic.
  • Bit 12 is the sign: set means the temperature is below 0 °C. Together, bits 12–0 form a 13-bit two's-complement value. If you strip bit 12 off while assembling the lower twelve bits, remember whether it was set; you need it for the sign correction.
  • Bits 11–4 are the integer part, weights 27 down to 20: eight bits, so 0 to 255.
  • Bits 3–0 are the fraction, weights 0.5, 0.25, 0.125 and 0.0625.

The fractional weights are the crux of Task 3. Each bit you keep halves the size of the smallest step you can represent; each bit you discard doubles it. Work out from this table which fractional bits you must retain so that the smallest representable increment is exactly 0.125 °C, and which you must throw away, and justify the choice in your report. The lab is explicit that using the wrong number of fractional bits scores zero, so derive it from the table rather than guessing.

11 Decoding a Temperature

The register arrives as two bytes: an upper byte (bits 15–8) and a lower byte (bits 7–0). The decoding differs above and below zero, and Task 3 requires both to be right.

11.1 Positive temperatures

Worked example: +17.75 °C

The register reads upper = 0xC1, lower = 0x1C, i.e. 1100 0001 0001 1100.

  1. Strip the flags. The top four bits of the upper byte are 1100: three comparison flags, plus a sign bit that is 0 here. Mask them off, leaving 0001 as the meaningful part of the upper byte.
  2. Shift the upper part up. Those four bits carry weights 27–24, so shifting left by 4 gives 0001 0000 = 16.
  3. Shift the lower byte down. The lower byte is 0001 1100; its top nibble holds the integer weights 23–20, so shifting right by 4 gives 0001 = 1.
  4. Integer part: 16 + 1 = 17 °C.
  5. Fraction. The bottom nibble of the lower byte is 1100: the 0.5 bit and the 0.25 bit are set, the 0.125 and 0.0625 bits are not. So 0.5 + 0.25 + 0 + 0 = 0.75 °C.
  6. Result: 17 + 0.75 = 17.75 °C. ✓

A shortcut: once the flags are masked off, the remaining bits count sixteenths of a degree. 0x011C = 284, and 284/16 = 17.75.

Decoding 0xC1 0x1C: bits 1100 0001 0001 1100. The flag bits 1 1 0 are masked off, the sign bit is 0, the whole-degree bits give 16 + 1 = 17, and the fraction bits give one half plus one quarter = 0.75, so T = 17.75 degrees Celsius.
Figure 25. Decoding 0xC1 0x1C, bits 1100 0001 0001 1100. The flag bits 1 1 0 are masked off, the sign bit is 0, the whole-degree bits give 16 + 1 = 17, and the fraction bits give ½ + ¼ = 0.75, so T = 17.75 °C.

Why are two flags set in an ordinary room reading? At power-up the limit registers TUPPER, TLOWER and TCRIT are all 0x0000, which is 0 °C. Any positive temperature is therefore above TUPPER and at or above TCRIT, so bits 14 and 15 are set. Mask the flags first, every time.

11.2 Negative temperatures

Bits 12–0 are a signed, 13-bit two's-complement value with a scale of 1/16 °C per count. Bits 15–13 are alert flags. There are two equivalent ways to decode the signed result:

  • Interpret all thirteen temperature bits as a signed integer, then divide by 16.
  • Keep the sign bit separately, assemble the lower twelve bits and divide by 16. If bit 12 is set, subtract 256 °C from that complete value, including its fraction.
Worked example: −17.75 °C

Upper byte 0x3E, lower byte 0xE4: 0011 1110 1110 0100.

  1. Remove the alert flags. The thirteen temperature bits give 0x1EE4.
  2. Read the sign. Bit 12 is set. Keep that information while assembling the lower twelve bits.
  3. Assemble the full fractional value. 0x0EE4 is 3812 counts, so 3812/16 = 238.25 °C.
  4. Apply the sign correction. 238.25 − 256 = −17.75 °C.

Equivalently, the signed integer is 7908 − 8192 = −284 counts, and −284/16 = −17.75 °C. Subtracting only the integer part and then appending a negative fraction gives the wrong answer.

Decoding 0x3E 0xE4: bits 0011 1110 1110 0100. The flag bits are masked off; the sign bit is set and in two's complement weighs minus 256 degrees; the remaining bits sum to 128 + 64 + 32 + 8 + 4 + 2 + 0.25 = 238.25, so T = −256 + 238.25 = −17.75 degrees Celsius. In code: mask with 0x1FFF, subtract 8192, divide by 16.
Figure 26. Decoding 0x3E 0xE4, bits 0011 1110 1110 0100. The flag bits are masked off. The sign bit is set, and in two’s complement it weighs −256 °C. The remaining bits sum to 128 + 64 + 32 + 8 + 4 + 2 + 0.25 = 238.25, so T = −256 + 238.25 = −17.75 °C. In code: mask with 0x1FFF, subtract 8192 if the sign bit is set, divide by 16. Flag bit 13 is set because −17.75 °C is below TLOWER = 0 °C.

Interpret the whole 13-bit value as signed, fraction included: the sign bit weighs −256 °C, and everything else keeps its positive weight.

For comparison, the byte pair 0x3E, 0xFC represents −16.25 °C. Both follow the register layout in datasheet Register 5-4.

You must test the negative path

Room temperature is positive, so a sign-handling bug is completely invisible during normal testing, and then produces a wildly wrong number the one time it matters. This is a classic, and it is exactly why the lab asks you to handle the sign bit correctly.

Test it deliberately. The simple way is to feed your decoding function the raw byte pairs from the two worked examples above and check that it returns +17.75 and −17.75. Since the register values are known, you do not need a cold sensor to prove the code is right. That argument itself is worth a sentence in your report.

11.3 Test the formula, even the datasheet’s

The MCP9808 datasheet gives the conversion as Equation 5-1: for T ≥ 0, T = UpperByte × 24 + LowerByte × 2−4 (with the flag and sign bits cleared from the upper byte); for T < 0 it writes T = 256 − (UpperByte × 24 + LowerByte × 2−4).

MCP9808 datasheet Equation 5-1: for T at or above 0 degrees, T = UpperByte × 2^4 + LowerByte × 2^−4; for T below 0 degrees the datasheet writes T = 256 − (UpperByte × 2^4 + LowerByte × 2^−4).
Figure 27. MCP9808 datasheet Equation 5-1, the register-to-temperature conversion. The negative branch has the sign flipped. Source: Microchip DS20005095B.

Try it on the bytes whose answer you know from §11.2, 0x3E 0xE4. With the flags and the sign bit cleared, the upper byte is 0x0E = 14 and the lower byte 0xE4 = 228:

14 × 16 + 228/16 = 238.25       datasheet: 256 − 238.25 = +17.75 °C       correct: 238.25 − 256 = −17.75 °C

The printed negative branch has the wrong sign. A datasheet is usually right and occasionally is not, so check any formula (the datasheet’s, a library’s, or your own) against bytes whose answer you know before you trust it.

Practice 11

(a) Decode upper = 0x01, lower = 0x91. Show every step.

(b) Decode upper = 0x1F, lower = 0xA4. Is it above or below zero, and how do you know before doing any arithmetic?

(c) What register bytes correspond to exactly +25.0 °C with all flag bits clear?

(d) A student's code reports 239.75 °C on a cold morning. Which step did they omit?

(e) Using the §10 table, list the fractional weights and state the smallest increment representable if you keep only the 0.5 and 0.25 bits. Then work out what you need for exactly 0.125.

12 Resolution and Conversion Time

Register 0x08 selects how finely the ADC resolves, and there is a direct cost in speed. Bits 1–0 set the ADC step:

MCP9808 datasheet Table 5-2, temperature conversion time: 0.5 degree resolution takes 30 ms (33 samples per second), 0.25 degree 65 ms (15), 0.125 degree 130 ms (7), and 0.0625 degree, the power-up default, 250 ms (4).
Figure 28. Temperature conversion time against resolution: 0.5 °C takes 30 ms (33 samples per second), 0.25 °C 65 ms (15), 0.125 °C 130 ms (7), and 0.0625 °C, the power-up default, 250 ms (4). Source: MCP9808 datasheet, Table 5-2.
Bits 1–0ResolutionTypical conversion timeNote
00+0.5 °C30 msFastest, coarsest
01+0.25 °C65 ms
10+0.125 °C130 ms
11+0.0625 °C250 msPower-up default (register value 0x03); finest, slowest

The datasheet contradicts itself about the power-up setting. The resolution register’s description and Table 5-3 give 0x03, 0.0625 °C, while a note on p. 24 says 0.25 °C. Do not guess: read register 0x08 on your own sensor and see.

Two different meanings of “resolution”: keep them separate

The sensor's resolution is how finely the hardware measures, set by register 0x08. The reported resolution is the step between the values your code produces when it decodes register 0x05. Task 3 is about the second one.

This is what Task 2 is steering you towards when it asks what you notice about the values from the provided module and what its limitation is: the module reports whole degrees even though the hardware supplies fractions of a degree. Your Task 3 function reads the same register and keeps more of those fraction bits.

Note the direction of the constraint: your decoding can never be finer than the hardware setting. If the sensor were configured for 0.5 °C steps, asking your code for 0.125 would just give you zeros in the low bits.

Resolution is not accuracy. A 0.125 °C output step does not mean the temperature is accurate to ±0.125 °C. The MCP9808 datasheet specifies a maximum error of ±0.5 °C from −20 to +100 °C under its stated conditions. Thermal contact, self-heating and temperature gradients can add error in an experiment.

For Task 3, each fraction bit halves the step: ½, ¼, ⅛, 1/16 °C. Keep the bits you need, and drop the rest with a mask or a shift. The figure illustrates dropping low bits from a positive value; which bits give exactly 0.125 °C steps is for you to work out and justify.

Illustration of truncation: number lines with steps of 0.5, 0.25, 0.125 and 0.0625 degrees. Dropping lower bits from an ideal value of 17.80 gives 17.5 at the coarsest step and 17.75 at the finer steps; this is not a sensor accuracy specification.
Figure 29. Number lines from 17 to 18 °C with steps of 0.5, 0.25, 0.125 and 0.0625 °C. In this ideal truncation illustration, a value of 17.80 °C becomes 17.5 at 0.5 °C steps and 17.75 at the finer steps. It illustrates the decoding only; it says nothing about the sensor’s accuracy.

The conversion time limits how often the sensor supplies a new result. Task 4 asks for readings every 0.2 s, which is 200 ms: longer than a 130 ms conversion, but shorter than the 250 ms conversion at the finest setting. So check which resolution your sensor is actually set to; at the finest setting, not every reading will be new. Poll much faster than the conversion time and you simply re-read the same value, producing a plot with visible flat steps. (Flat steps can also come from the output step size, or from a temperature that really is steady, so repeated numbers on their own do not tell you which.)

Practice 12

(a) At the power-up setting, what is the fastest meaningful sampling rate in samples per second?

(b) You sample every 50 ms at that setting. What will the data look like, and why?

(c) What time separates the first and last readings in a 100-point run at exactly 0.2 s intervals? How long does the whole run take if the loop sleeps 0.2 s after every read, including the last? Does the conversion time change either interval, or the number of fresh readings?

13 In the Lab: Wiring, Bus Check and a First Script

13.1 The breakout board and its four wires

Only four connections are needed:

Sensor pinRaspberry PiNote
VDD3.3 V, physical pin 1 or 17Direct connection is fine; the sensor draws very little. Not 5 V: that would put 5 V logic on the Pi's I²C lines.
GNDany ground, e.g. physical pin 6 or 9The usual shared reference.
SDABCM 2, physical pin 3The Pi's hardware I²C data line.
SCLBCM 3, physical pin 5The Pi's hardware I²C clock line.
Wiring from the Raspberry Pi header to the MCP9808 breakout: physical pin 1 (3.3 V) to Vdd, pin 6 (ground) to Gnd, pin 5 (SCL) to SCL and pin 3 (SDA) to SDA. The 5 V pins 2 and 4 are not used.
Figure 30. Wiring from the Pi header to the MCP9808 breakout: physical pin 1 (3.3 V) to Vdd, pin 6 (ground) to Gnd, pin 5 (SCL) to SCL and pin 3 (SDA) to SDA. The 5 V pins 2 and 4 are not used.

The remaining breakout pins (Alert, A0, A1, A2) are left unconnected. Alert is an open-drain output the sensor can assert when a temperature limit is crossed, which is a hardware alternative to the software threshold you will implement in Task 4.

Wire it with the Pi powered off

Lab 6 Task 2 says this explicitly, and it is worth following. Connecting a sensor to a live bus can momentarily short a signal line to a supply pin as the header makes contact.

Check the wiring twice before applying power. Swapping VDD and GND can destroy the sensor, and the pin order on the board is not the same as the order in the table above.

13.2 Bringing the bus up

Task 1 and the start of Task 2 are pure system setup.

# 1. Enable the I2C interface: Interface Options -> I2C -> <Yes>, then reboot
sudo raspi-config

# 2. After the reboot, confirm the bus device exists
ls /dev/i2c-*

# 3. Scan bus 1 for devices. The MCP9808 appears as 18.
i2cdetect -y 1

# 4. Read a register directly from the command line -- no Python needed.
#    Device 0x18, register 0x06 (manufacturer ID), word read.
#    Note: i2cget returns a word byte-swapped; 0x5400 here means 0x0054.
i2cget -y 1 0x18 0x06 w

With the sensor wired and I²C enabled, the scan looks like this. The 18 in the grid means a chip ACKed address 0x18:

$ i2cdetect -y 1
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:                         -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- 18 -- -- -- -- -- -- --
What the i2cdetect grid is telling you

i2cdetect knocks on each ordinary 7-bit address in turn and reports which ones answer with an ACK. That works well for the course sensors, but an ACK only tells you something is there, not what it is, and a few other kinds of chip do not like being probed. So:

  • 18 appears. Something acknowledges 0x18. Read its ID to check which device answered.
  • The grid is empty. Nothing acknowledged. Check VDD and GND first, then SDA and SCL, then that they are not swapped.
  • No /dev/i2c-1. I²C is not enabled yet; enable it and reboot. (If the file exists but the command fails, read the error message: it may be a permissions problem or a bus fault.)
  • A different address appears. Check the address pins, and whether another device is on the bus. It is not the 7-bit/8-bit mix-up: the scan already shows 7-bit addresses.

Run i2cdetect before you write a single line of Python, and read an ID register before you trust any temperature.

13.3 A first script: check the chip, then read TA

The first Python should prove the channel before it decodes anything. Read the manufacturer ID, whose answer you know, and then the two raw bytes of the temperature register:

from smbus2 import SMBus

ADDR = 0x18                 # 7-bit address

with SMBus(1) as bus:       # /dev/i2c-1
    mid = bus.read_i2c_block_data(ADDR, 0x06, 2)
    print(mid)              # [0, 84] = 0x0054
    hi, lo = bus.read_i2c_block_data(ADDR, 0x05, 2)
    print(hex(hi), hex(lo)) # 0xc1 0x1c, say

raw = hi << 8 | lo          # 0xc11c: now decode it

Example only. Do not copy this code as it is: read it, learn from it, then write your own.

[0, 84] is 0x00, 0x54: the manufacturer ID 0x0054 of §8.2. Decoding raw is Task 3 (§10–12). When something is wrong, the symptom tells you the layer:

SymptomLayer to fix
No 18 in i2cdetectWiring or power (§13.1, §13.2)
Wrong manufacturer IDRegister pointer or byte order (§8, §9.5)
Odd temperaturesMasks or sign handling (§11)

Fix one layer before the next.

13.4 Poll no faster than the sensor converts

At the power-up resolution, 0.0625 °C, the register updates every 250 ms: four new values per second (§12). A loop that reads every 50 ms returns each value five times in a row. You get more rows in your CSV, but no more information.

Illustration of polling faster than conversion: the true temperature rises smoothly; the register updates in steps every 250 milliseconds; the Pi reads every 50 milliseconds, so each register value appears five times in a row.
Figure 31. Polling faster than the sensor converts, as an illustration. The true temperature rises smoothly; the register updates in steps every 250 ms; the Pi reads every 50 ms, so each register value appears five times in a row.

14 From a Reading to a Dataset

Task 4 turns a working sensor into an experiment. Each part is small; together they are the standard shape of a data-acquisition program.

14.1 Unit conversion

T°F = 95T°C + 32(3)

Label both values with units in the output. An unlabelled column of numbers is the most common presentation fault in lab reports, and it costs marks for no good reason.

14.2 The threshold warning

Task 4 asks for a software warning threshold (28 °C is suggested) above which the program prints a distinct warning. Put the threshold in a named constant at the top of the file rather than burying the number in a comparison, so you can demonstrate it by touching the sensor and, if the room is warm, retune it in one place.

Worth noticing: the MCP9808 can do this in hardware. Registers 0x02–0x04 hold the limits, bits 15–13 of the temperature register report the comparisons, and the Alert pin can be asserted without the Pi involved at all. Your software check and the sensor's hardware alert are two solutions to the same problem, and it is worth comparing how quickly each responds and whether each depends on your program running.

14.3 Logging, plotting and the CSV

The requirements are 100+ measurements, elapsed time in seconds since the program started, a plot with lines joining the measured points and individual markers, a title and labeled axes with units, a horizontal dashed line at the threshold, and a temp_data.csv with the headers “Time (s)” and “Temperature (C)”.

Four things that will improve the result
  1. Use time.perf_counter() for elapsed time, taking a reference once before the loop and subtracting. It is the interval clock from Lecture 03, used for the same reasons.
  2. Collect first, plot afterwards. Appending to a list inside the loop and plotting once at the end keeps the sampling interval clean. Drawing inside the loop adds large, variable delays: the print() problem of Lecture 03 §6.6, in a more expensive form.
  3. Write the CSV exactly as specified, headers included. Then open it in a spreadsheet and look at it. Check that the headers, column order and units agree.
  4. Give the experiment something to show. A flat line at room temperature is a correct but dull result. Warm the sensor with a finger partway through the run and let it cool: you get a rise, a peak and an exponential-looking decay, which crosses your threshold line and makes every feature of the plot meaningful.

14.4 The extra-credit live plot

In the extra-credit task (Task 5), the plot updates in real time and scrolls to show the most recent N seconds. The idea is to update the data behind an existing plot rather than redrawing the figure each time; redrawing from scratch is what makes naive live plots slow and jerky. Keep a fixed-length buffer of the most recent points, and set the x-limits from the newest timestamp so the window scrolls. Look up Matplotlib’s animation functions with Python’s built-in help(), and write the code yourself, as the lab’s code policy requires.

15 Common Mistakes and Debugging

15.1 Things that damage hardware

  • VDD and GND swapped. Can destroy the sensor. Check twice before powering on.
  • 5 V to the sensor's VDD. Puts 5 V logic on the Pi's I²C lines, which are 3.3 V only and not tolerant.
  • Wiring a live bus. Power the Pi down first, as Task 2 instructs.

15.2 A debugging order that works

  1. Does /dev/i2c-1 exist? No → enable I²C and reboot.
  2. Does i2cdetect -y 1 show 18? No → check power, wiring, address selection, bus configuration and permissions.
  3. Does the manufacturer ID read back as 0x0054? No → check that it is the right chip, the register number and the byte order. Yes → the channel works; move on to the temperature register.
  4. Does the raw register look plausible? Print the two bytes in hex before converting. Compare against §11 by hand.
  5. Does the decoding handle both signs? Feed it the two known byte pairs from §11.

15.3 Things that waste your afternoon

  • SDA and SCL swapped. Nothing is damaged, and nothing is detected.
  • 7-bit versus 8-bit address confusion (§7).
  • Byte order reversed when combining the two bytes into a 16-bit value: the number moves wildly for tiny temperature changes.
  • Forgetting to mask off bits 15–13 before arithmetic. At power-up every limit register is 0 °C, so at room temperature bits 15 and 14 are set (the 0xC1 of §11.1), and an unmasked reading is wildly wrong. The bug only hides if someone has already set the limits above room temperature.
  • Sampling faster than the conversion time and wondering why the data is stair-stepped (§12).
  • Warming the sensor with a finger and expecting instant response; the package has thermal mass and takes seconds.
  • Loose breadboard jumpers. Intermittent I²C failures are very often mechanical.

15.4 Before you leave

Copy your scripts, the CSV and the plots to your own computer; verify they open there; then remove your directory from the shared Pi and shut down cleanly.

16 Self-Check

  1. Give three reasons a serial link can outperform a parallel one, and cite the PATA/SATA numbers.
  2. What distinguishes an asynchronous link from a synchronous one? Which family does I²C belong to, and what does that spare you from configuring?
  3. Why are the pull-up resistors mandatory on an I²C bus, and what would happen without them?
  4. Describe the START and STOP conditions in terms of SDA and SCL. Why can neither be mistaken for data?
  5. During data transfer, when is SDA permitted to change, and when does the receiver sample?
  6. On the ninth clock, what does a low SDA mean? Why does a missing device automatically produce the opposite?
  7. The MCP9808's address is 0x18. Write the full first byte for a read and for a write, in binary and hex.
  8. List the bit fields of the ambient temperature register: which bits are flags, which is the sign, which are integer, which are fractional?
  9. Decode upper = 0xC1, lower = 0x1C. Then decode upper = 0x3E, lower = 0xE4.
  10. Which two registers hold fixed known constants, what are they, and how does that help you debug?
  11. Distinguish the sensor's configured resolution from the resolution your decoding reports. Which does Task 3 concern?
  12. Why does sampling every 50 ms at the finest resolution setting not give you finer time detail?
Lab takeaway

Two wires, shared by every device, with open-drain outputs and pull-ups, so a low level always wins and no two outputs ever fight. A transaction is START, address plus direction, register pointer, data, acknowledge at every byte, STOP. What comes back is not a temperature but sixteen bits whose meaning the datasheet defines: flags, a sign, an integer part and a fraction. Reading that layout correctly, and proving it against known values, is the whole of Task 3.

17 Practical Engineering Connections

  1. I²C everywhere. Laptop battery gauges, monitor identification (EDID over I²C), phone sensor hubs, server temperature monitoring and camera modules all use this bus. It is roughly forty years old and completely unavoidable.
  2. Serial beat parallel. SATA over PATA, USB over the parallel port, PCI Express over PCI, and today’s high-speed storage and expansion links all cut the pin count while raising the data rate.
  3. Register-based devices. Almost every modern peripheral (sensors, radios, power controllers, displays) is a set of numbered registers behind a serial interface. Learn the pattern once and every new datasheet gets easier.
  4. Fixed-point arithmetic. The MCP9808's integer-plus-fraction format is how embedded systems represent non-integers without floating-point hardware, and it appears in audio codecs, motor controllers and DSP throughout.
  5. Two's complement. The negative-temperature handling is the same representation every processor uses for signed integers, and the same trap appears with every signed sensor, including the accelerometer in Lab 7.
  6. Resolution versus speed. For this sensor, finer steps take longer. Every ADC trades resolution against speed, power and cost in some way, and you will meet the trade again in Lab 8.
  7. Hardware alerts. The Alert pin lets a sensor interrupt a processor instead of being polled. That is the basis of low-power design, where a device sleeps until something happens.
  8. Known-value debugging. Reading an ID register to prove the channel works before trusting the data is the same discipline as a calibration standard, a checksum or a test pattern. It is how experienced engineers avoid debugging two things at once.

← All course materials