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.
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 task | What you do | Concept & section |
|---|---|---|
| 1 | Make a lab directory; enable I²C with raspi-config; reboot | Bringing the bus up (§13.2) |
| 2 | Wire the sensor with the Pi off; run i2cdetect -y 1 and find address 18; use the provided module; note its limitation | Bus topology, addressing, resolution (§5, §7, §12) |
| 3 | Write read_temp_high_res() for exactly 0.125 °C, from the datasheet, with correct sign handling | Register bit layout and decoding (§10, §11) |
| 4 | °C and °F; a critical-temperature warning; 100+ logged measurements; a plot; a CSV file | From a reading to a dataset (§14) |
| 5 | Extra 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.

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:
| Interface | Introduced | Type | Throughput |
|---|---|---|---|
| PATA Parallel AT Attachment | 1986 | parallel | 66 / 100 / 133 MB per second |
| SATA Serial ATA | 2003 | serial | 150 / 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.
- 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.
- 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.
- 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.

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:
- An analog temperature sensor: a bandgap circuit whose output voltage depends on absolute temperature.
- An ADC that digitizes it.
- A set of registers holding the result, the configuration, and the alert limits.
- 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.

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.
| Family | How timing is agreed | Examples and consequences |
|---|---|---|
| Asynchronous | No 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. |
| Synchronous | A 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.

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.

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.


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.
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
On our bench the Pi’s own 1.8 kΩ pull-ups sit in parallel with the breakout’s 10 kΩ ones:
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.

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

6.2 START and STOP
| Condition | What happens on the wires | Meaning |
|---|---|---|
| START | SDA is pulled low while SCL stays high | The controller claims the bus. Everything that follows belongs to this transaction. |
| STOP | SCL rises first, then SDA rises | The bus is released and returns to idle, both lines high. |
| Repeated START | A second START with no intervening STOP | The controller keeps the bus and begins a new phase, typically switching from writing a register address to reading that register's contents (§9.2). |

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 9 | SDA | Name | Meaning |
|---|---|---|---|
| 0 | pulled low | ACK | Received. Carry on: more to come. |
| 1 | left high | NAK | No 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.

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

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


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

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.

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.
| Register | Pointer | Access | Contents / power-up value |
|---|---|---|---|
| Configuration | 0x01 | read/write | 0x0000; alert behavior, hysteresis, shutdown, locks |
| T upper limit | 0x02 | read/write | 0x0000 |
| T lower limit | 0x03 | read/write | 0x0000 |
| T critical | 0x04 | read/write | 0x0000 |
| Ambient temperature TA | 0x05 | read only | The measurement itself, and the subject of Task 3 |
| Manufacturer ID | 0x06 | read only | 0x0054, a fixed, known value |
| Device ID / revision | 0x07 | read only | Device ID 0x04 in the high byte; silicon revision in the low byte (0x00 in this datasheet) |
| Resolution | 0x08 | read/write | 0x03 at power-up (see §12) |
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:
| Bits | Function | Bits | Function |
|---|---|---|---|
| 15–11 | unused | 5 | Clear alert |
| 10–9 | Hysteresis | 4 | Alert status |
| 8 | Shutdown mode | 3 | Alert output control |
| 7 | Critical trip lock | 2 | Critical alert only |
| 6 | Alarm window lock | 1 | Alert polarity |
| 0 | Alert 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, valueExample only. Do not copy this code as it is: read it, learn from it, then write your own.

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:
- START
- Send the 7-bit device address with the write bit, so the sensor listens, then ACK
- Send the register address you want (this is the “pointer”), then ACK
- Repeated START
- Send the same device address with the read bit, then ACK
- Read the first data byte; the controller sends ACK to say “another, please”
- Read the second data byte; the controller sends NAK to say “that is enough”
- 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.

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.

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, countExample 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.](/_astro/i2c-smbus2-block.DViPhC5U_1sO0p8.webp)
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, 0x1CExample 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.](/_astro/i2c-smbus2-rdwr.p86DcXVo_W7a4z.webp)
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.](/_astro/i2c-word-swap.DtXDfuTq_ZOXoOd.webp)
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 same layout as two tables, one per byte:
| Bit | 15 | 14 | 13 | 12 | 11 | 10 | 9 | 8 |
|---|---|---|---|---|---|---|---|---|
| Meaning | TA ≥ Tcrit | TA > Tupper | TA < Tlower | SIGN TA < 0°C | 27 | 26 | 25 | 24 |
| Bit | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
|---|---|---|---|---|---|---|---|---|
| Meaning | 23 | 22 | 21 | 20 | 2−1 0.5 | 2−2 0.25 | 2−3 0.125 | 2−4 0.0625 |
- 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
The register reads upper = 0xC1, lower = 0x1C, i.e. 1100 0001 0001 1100.
- 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, leaving0001as the meaningful part of the upper byte. - Shift the upper part up. Those four bits carry weights 27–24, so shifting left by 4 gives
0001 0000= 16. - 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 gives0001= 1. - Integer part: 16 + 1 = 17 °C.
- 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. - 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.

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.
Upper byte 0x3E, lower byte 0xE4: 0011 1110 1110 0100.
- Remove the alert flags. The thirteen temperature bits give
0x1EE4. - Read the sign. Bit 12 is set. Keep that information while assembling the lower twelve bits.
- Assemble the full fractional value.
0x0EE4is 3812 counts, so 3812/16 = 238.25 °C. - 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.

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

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:
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.
(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:

| Bits 1–0 | Resolution | Typical conversion time | Note |
|---|---|---|---|
| 00 | +0.5 °C | 30 ms | Fastest, coarsest |
| 01 | +0.25 °C | 65 ms | |
| 10 | +0.125 °C | 130 ms | |
| 11 | +0.0625 °C | 250 ms | Power-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.
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.

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.)
(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 pin | Raspberry Pi | Note |
|---|---|---|
| VDD | 3.3 V, physical pin 1 or 17 | Direct connection is fine; the sensor draws very little. Not 5 V: that would put 5 V logic on the Pi's I²C lines. |
| GND | any ground, e.g. physical pin 6 or 9 | The usual shared reference. |
| SDA | BCM 2, physical pin 3 | The Pi's hardware I²C data line. |
| SCL | BCM 3, physical pin 5 | The Pi's hardware I²C clock line. |

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.
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 -- -- -- -- -- -- --
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 itExample 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:
| Symptom | Layer to fix |
|---|---|
No 18 in i2cdetect | Wiring or power (§13.1, §13.2) |
| Wrong manufacturer ID | Register pointer or byte order (§8, §9.5) |
| Odd temperatures | Masks 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.

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
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)”.
- 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. - 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. - 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.
- 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
- Does
/dev/i2c-1exist? No → enable I²C and reboot. - Does
i2cdetect -y 1show 18? No → check power, wiring, address selection, bus configuration and permissions. - 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.
- Does the raw register look plausible? Print the two bytes in hex before converting. Compare against §11 by hand.
- 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
- Give three reasons a serial link can outperform a parallel one, and cite the PATA/SATA numbers.
- What distinguishes an asynchronous link from a synchronous one? Which family does I²C belong to, and what does that spare you from configuring?
- Why are the pull-up resistors mandatory on an I²C bus, and what would happen without them?
- Describe the START and STOP conditions in terms of SDA and SCL. Why can neither be mistaken for data?
- During data transfer, when is SDA permitted to change, and when does the receiver sample?
- On the ninth clock, what does a low SDA mean? Why does a missing device automatically produce the opposite?
- The MCP9808's address is 0x18. Write the full first byte for a read and for a write, in binary and hex.
- List the bit fields of the ambient temperature register: which bits are flags, which is the sign, which are integer, which are fractional?
- Decode upper = 0xC1, lower = 0x1C. Then decode upper = 0x3E, lower = 0xE4.
- Which two registers hold fixed known constants, what are they, and how does that help you debug?
- Distinguish the sensor's configured resolution from the resolution your decoding reports. Which does Task 3 concern?
- Why does sampling every 50 ms at the finest resolution setting not give you finer time detail?
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
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.