1 Where Lab 8 Sits
This is the last lab before the group project, and it closes a circle that opened in Lab 1.
In Lab 1 you built analog circuits and read them with a DMM and an oscilloscope, instruments someone else built. This week you build the instrument. The MCP3008 turns a voltage into a number, which is exactly what the front end of every digital multimeter, oscilloscope and data logger does. Once you have an ADC and a Pi, you have a general-purpose measuring instrument that you programmed yourself.
SPI adds a second synchronous serial protocol to compare with the I²C of Labs 6 and 7. Remote access lets you run the Pi from your laptop while the circuit stays on the bench.
An ADC replaces a continuous voltage with a number drawn from a finite set, sampled at particular instants. Both of those are approximations, and both have consequences you can calculate: quantization sets how finely you can resolve a value, and sampling rate sets what frequencies you can faithfully represent. No software can recover what was lost to clipping or to sampling too slowly, and averaging, though it reduces random noise, cannot fix a calibration error.
Task 1 asks you to connect the Pi to the internet, update the operating system, and download ADC3008_SPI.py. Allow time for the update before beginning the later tasks.
1.1 Task map
| Lab 8 task | What you do | Concept & section |
|---|---|---|
| 1 | Network, lab directory, OS update, enable SPI, download ADC3008_SPI.py | Bringing SPI up (§3.2) |
| 2 | Wire the MCP3008; read a channel as a voltage; demonstrate | Wiring; the three-byte conversation; counts to volts (§10, §11, §12.1) |
| 3 | Build a 0–3.3 V source; compare your readings against a DMM; error handling | Quantization; calibration and accuracy (§8, §12.3) |
| 4 | Record counts, calculated volts and DMM volts for 20+ points; fit DMM volts against counts and examine residuals | The transfer function (§12) |
| 5–6 | SSH from your laptop; VNC desktop; run your programs remotely | Remote access (§15) |
| 7 | Extra credit: sine wave into both the ADC and the scope; plot voltage against time; find the maximum usable frequency | Sampling, Nyquist, aliasing (§13, §14) |
You may also complete the shared Lab 7 Task 7 (temperature compensation, threads, and processes) in this lab, for up to +10 points awarded once across Labs 7 and 8. For partial credit, document clearly which parts you completed. See the Lab 8 manual for the task and submission policy and the Lecture 7 notes (§15–16) for the concepts. Lab 8 Task 7 above remains the separate waveform-analysis assignment.
2 Three Ways to Talk to a Chip
You have now met two serial protocols, and this week adds the third. Each makes a different choice about wires, clocks and who is talking.

- UART is asynchronous: one wire each way and no clock, so both ends must agree on the baud rate and frame format in advance (Lecture 06 §4).
- I²C is the MCP9808 and LIS3DH of Labs 6 and 7: two shared wires, a clock, addresses and an ACK/NAK bit after each byte.
- SPI (Serial Peripheral Interface) is the other synchronous serial protocol. Like I²C it sends a clock alongside the data; unlike I²C it uses separate wires for each direction and selects devices with a dedicated pin rather than an address. It is usually much faster than I²C, though how fast depends on the chips.
3 SPI: Four Wires, and the Pi Runs the Clock
3.1 Four wires

| Signal | Name | Direction | MCP3008 pin |
|---|---|---|---|
| SCLK | Serial clock | controller → device | CLK |
| MOSI | Controller Out, Peripheral In | controller → device | DIN |
| MISO | Controller In, Peripheral Out | device → controller | DOUT |
| CE0 | Chip enable / chip select | controller → device | CS/SHDN |
The names are not standard. Newer documents write COPI and CIPO, or SDO and SDI from the point of view of whichever chip you are looking at; the MCP3008 datasheet calls its pins DIN and DOUT. Read the arrow, not the name: data goes into the ADC on the controller's output.
The controller, the Pi, generates the clock. The peripheral never clocks anything on its own; it can only answer while the Pi clocks (§4.4).
3.2 Where SPI lives on the Pi header

| Signal | BCM | Physical pin |
|---|---|---|
| MOSI | 10 | 19 |
| MISO | 9 | 21 |
| SCLK | 11 | 23 |
| CE0 | 8 | 24 |
| CE1 | 7 | 26 |
# Enable SPI: Interface Options -> SPI -> <Yes>, then reboot
sudo raspi-config
# After rebooting, confirm the device nodes exist -- one per chip select
ls /dev/spidev*
# expect: /dev/spidev0.0 /dev/spidev0.1
/dev/spidev0.0 is bus 0 with CE0, and /dev/spidev0.1 the same bus with CE1; in Python, spi.open(0, 0) opens the first.
There is no SPI equivalent of i2cdetect. Because there are no addresses and no acknowledge bit, an SPI device cannot announce itself: a missing or mis-wired chip simply returns zeros or meaningless data instead of an error. This is a real disadvantage when debugging, and §17.2 gives the alternative approach.
3.3 Chip select: one wire per chip, not an address
SCLK, MOSI and MISO are shared by every SPI device; only the chip-select line is unique to each. The Pi has two hardware chip selects, CE0 and CE1. An ordinary GPIO pin can act as a third, but you have to set that up yourself, either in the SPI driver’s configuration or by switching the pin from your program; spi.open() will not do it for you. Chip select is active low: only the chip whose select line is low listens to MOSI and drives MISO. The others let go of MISO, leaving it at high impedance, so they do not fight the chip that is talking.

On the MCP3008 the select pin does more. Pulling CS/SHDN low starts a conversation; pulling it high ends the conversion and puts the chip into low-power standby, and it must go high between conversions (datasheet §3.7). So one reading is one uninterrupted stretch of CS low.
4 How a Transfer Works
4.1 Two shift registers joined in a ring
A good way to picture SPI is as two shift registers joined in a ring, each holding one byte. (The MCP3008 has command and conversion logic as well, so this shows how the bits move, not the whole chip.) MOSI joins the Pi's most significant end to the chip's least significant end; MISO joins the chip's most significant end back to the Pi's least significant end. Every SCLK tick, both registers shift one place, and the bit that falls off one end lands in the other chip.

4.2 Tick by tick: the two bytes trade places
After eight ticks every bit has gone round: the Pi holds the chip's byte and the chip holds the Pi's.

Data moves in both directions on every clock pulse. A chip may still treat the exchange as a command followed by a reply, but the wires do not know that: to receive a byte, the Pi must send one, even if it is only padding, because sending is what makes the clock run.
This is why reading the MCP3008 takes the form of sending three bytes and receiving three bytes in the same transaction. The first bytes you send carry the start bit and the channel selection; the bytes coming back during the later clocks carry the conversion result. Seeing the exchange as one simultaneous swap rather than a question followed by an answer is what makes the MCP3008's protocol make sense.
4.3 One byte on the wire, both directions at once
Figure 7 shows one byte moving each way while chip select is low. SPI itself defines nothing more than this: no addresses, no start bit, no acknowledgment. Each chip defines its own command format on top; the MCP3008, for example, wants a start bit and three bytes under one chip-select pulse. The clock need not be perfectly regular, but it must stay within the chip’s timing limits, and for the MCP3008 it must not pause too long in the middle of a conversion, or the sample capacitor starts to discharge (§9.3).

4.4 To read, you must write
The chip can only answer while the Pi clocks, and the Pi only clocks while it sends. So a read is a write: send three bytes, get three back. In Python, spidev's xfer2 takes a list of bytes to send and returns a list of the same length, the bytes that arrived on MISO during each one. xfer2 holds chip select low across all three bytes, which the MCP3008 needs, since raising it would end the conversion (§3.3).
![The call spi.xfer2([0x01, 0x80, 0x00]) sends three bytes and receives three: 0x01 (start bit) returns an unknown byte, 0x80 (channel 0, single-ended) returns 0x?2 holding the null bit and B9 B8, and the dummy byte 0x00 returns 0x6C holding B7 to B0. Each byte takes 8 ticks in both directions.](/_astro/spi-xfer-list.B8y2ts94_Z2qsyYK.webp)
spi.xfer2([0x01, 0x80, 0x00]) sends three bytes and receives three: 0x01 (the start bit) returns an unknown byte; 0x80 (channel 0, single-ended) returns 0x?2, holding the null bit and B9 B8; the dummy byte 0x00 returns 0x6C, holding B7 to B0. Each byte takes 8 ticks in both directions.5 Clock Modes
5.1 Four modes: idle level and reading edge
Two settings define exactly when bits are driven and sampled. Clock polarity, CPOL, is the clock's idle level: 0 for low, 1 for high. Clock phase, CPHA, says whether data is read on the first clock edge after chip select (0) or the second (1). The sender sets up each bit on the other edge, half a clock earlier, so the bit is steady when it is read. Together they give four modes, conventionally numbered 0 to 3.

5.2 The MCP3008 reads on the rising edge: mode 0
Both ends must agree. The MCP3008 latches DIN on the rising edge of CLK, and changes DOUT after the falling edge; its datasheet specifies the set-up and hold times around the rising edge, tSU = tHD = 50 ns. That is mode 0 (or mode 3, which reads on the same edge with the clock idling high); the datasheet supports modes 0,0 and 1,1 only. In code, spi.mode = 0b00.

A mode mismatch does not produce an error. In mode 1 the Pi would read MISO on the falling edge, exactly when the MCP3008 is changing it, and the result looks like your value shifted by one bit, or noise. If an SPI device returns data that looks like your value shifted by one bit, a mode mismatch is the classic cause. (The lab's ADC3008_SPI.py uses 0b00; an older course module, adc3008_mod.py, defaulted to 0b01 and has since been corrected.)
6 SPI Compared with I²C
The two buses make different choices about wiring, timing and device selection.
| Property | I²C (Lab 6, Lab 7) | SPI (Lab 8) |
|---|---|---|
| Signal wires, excluding power and ground | 2 shared | 3 shared + 1 chip select per device |
| Device selection | 7-bit address sent on the bus | A dedicated hardware pin per device |
| Clock on the Pi | 100 kHz by default | 1 MHz in Lab 8; many SPI chips run at tens of MHz |
| Direction | Half duplex: one way at a time | Full duplex: both directions at once |
| Electrical | Open drain with pull-ups; lines driven down only | Push-pull; driven up and down, no pull-ups needed |
| Acknowledgment | ACK/NAK after each byte (it confirms receipt, not that the data are right) | None; some chips add their own status or check bits |
| Scaling | Add devices with no extra pins, until addresses collide | Every extra device costs a GPIO pin |
| Discovery | i2cdetect finds devices that answer their address | No discovery mechanism at all |
The electrical row is why SPI can run faster. An I²C line rises only as fast as its pull-up can charge the bus capacitance (Lecture 06 §5.2); an SPI driver pushes the line up as hard as it pulls it down.

I²C spends speed to save pins; SPI spends pins to buy speed. A temperature sensor read twice a second has no use for megahertz, so I²C suits it. An ADC digitizing a waveform needs every bit of throughput it can get, so SPI suits it. Both choices are correct for their device, which is why the Raspberry Pi provides both.
An unplugged or mis-wired MCP3008 still “reads” a number: the Pi clocks in whatever MISO happens to be, and your program prints it without complaint. Test the chain with a known voltage before you trust an unknown one (§17.2).
7 What an ADC Does
A GPIO input sees 0 or 1: it compares the pin voltage with a threshold and throws everything else away. An analog-to-digital converter reports a number that follows the voltage. The MCP9808 had its ADC inside, hidden behind a temperature register; the MCP3008 is the ADC alone: eight analog inputs in, numbers out over SPI.

An ADC performs two distinct approximations, and keeping them separate is essential because they have different consequences.
- Sampling: discretizing time. The continuous signal is examined only at particular instants, and everything in between is unrecorded. This governs which frequencies you can represent (§13–14).
- Quantization: discretizing amplitude. The voltage at each instant is mapped to one of a finite number of levels. This governs how precisely you can resolve a value (§8).
8 Ten Bits: Quantization and the LSB
An N-bit converter has 2N levels spanning its reference voltage. The size of one step, the least significant bit (LSB), is
For the worked examples we use an ideal converter that simply rounds down, following datasheet Equations 4-1 and 4-2:
where ⌊ ⌋ means rounding down to a whole number. This holds for 0 ≤ Vin < VREF; at VREF and above, the output sticks at 1023, never 1024. A real converter also has small offset, gain and linearity errors, so on the bench the code can differ from this ideal by a count or two.
The MCP3008 is a 10-bit converter. With VREF = 3.30 V:
For 2.00 V, 1024 × 2.00/3.30 = 620.6, so the code is 620. Going back, 620 × 3.30 V/1024 = 1.998 V, 2 mV below the input, because code 620 covers every input from 1.998 to 2.001 V. This one reading runs through the rest of the notes: it is the SAR search of §9.2, the reply bytes of §11.2, and the SSH screen of §15.1.
So the codes are about 3.2 mV apart, and a single reading cannot tell you where the input lies within its step. Each code stands for a step one LSB wide. If you convert a code to its step’s bottom edge, code × VLSB, you read between 0 and 1 LSB low; if you use its center, (code + ½) × VLSB, you are within ±½ LSB, about ±1.6 mV. (Averaging many readings can do better than this, but only if some noise makes the readings hop between neighboring codes, and it never fixes a calibration error.)
Keep this scale in mind when you compare readings with the DMM. A reading that happens to agree to better than one LSB is luck, not sub-LSB accuracy. And quantization is only one term: the ADC’s own offset, gain and linearity errors, the uncertainty in VREF and the DMM’s own accuracy all count too (§12.3).

A 10-bit converter has 210 = 1024 distinct levels, numbered 0 through 1023. There is no count of 1024; it is the same off-by-one as an array of length 1024 whose last index is 1023.
It matters for your conversion formula. Dividing by 1024 and dividing by 1023 give slightly different volts-per-count, and the choice determines whether full scale maps to VREF or to one LSB below it. The two differ by at most 1 LSB. Dividing by 1024 matches the ADC’s real step size. Dividing by 1023 makes the top code land exactly on VREF, which is a convenient convention but not the ADC’s step size, so say which you chose. The difference is about 3 mV at the top of the range, exactly the size of the effect you are trying to measure in Task 3.
9 Inside the MCP3008
9.1 What it offers
- 10-bit resolution, successive approximation.
- Eight input channels, CH0 through CH7, multiplexed: one converter shared between eight inputs, selected per conversion.
- Single-ended or pseudo-differential input modes. Single-ended measures each channel against ground and is what Lab 8 uses.
- SPI interface, modes 0,0 and 1,1.
- Speed: up to 200 ksps with a 3.6 MHz clock at VDD = 5 V, and 75 ksps with 1.35 MHz at 2.7 V. The datasheet gives no figure for 3.3 V, so we play safe with a 1 MHz clock.

Follow a conversion through the blocks:
- Sample and hold freezes Vin on a capacitor (§9.3).
- The DAC produces a trial voltage, a fraction of VREF.
- The comparator answers one question: is Vin at or above the trial?
- The SAR, the successive-approximation register, keeps each answer as one bit and picks the next trial.
- The shift register sends the bits out on DOUT.
9.2 Successive approximation: a binary search
The MCP3008 is a successive-approximation converter, and the algorithm is worth knowing because it explains both the speed and the pin count.
Internally the ADC performs a binary search. It first tries half scale, code 512. If Vin is at or above it, the most significant bit is 1 and stays set; otherwise it is 0. It then halves the remaining interval and tries the next bit down, and so on. Ten comparisons yield ten bits, one per clock, and each bit leaves on DOUT as soon as it is decided, which is why the answer comes out most significant bit first.

For 2.00 V: 512 (1.650 V) is below, keep; 768 (2.475 V) is above, drop; 640 (2.063 V) drop; 576 keep; 608 keep; 624 (2.011 V) drop; 616 keep; 620 (1.998 V) keep; 622 and 621 drop. Kept bits: 1001101100 = 620.
Conversion time grows with resolution: each extra bit costs one more clock. That is the same trade between resolution and time as the MCP9808's resolution register (Lecture 06 §12), though that converter works differently and each extra bit there doubles the time.
9.3 Sample and hold: charge 20 pF in 1.5 clocks
The conversion begins by sampling. For 1.5 clock periods, starting on the fourth rising edge after the start bit, a switch connects the input to a 20 pF sample capacitor; then it opens, and the capacitor holds the voltage while the SAR works.

The capacitor must charge to within ½ LSB of the input in that time. Lab 8's source is a 10 kΩ potentiometer, whose output resistance is at most 2.5 kΩ (at mid-travel, 5 kΩ in parallel with 5 kΩ). With the 1 kΩ switch,
Settling to ½ LSB of 10 bits needs e−t/τ = 1/2048, so t = τ ln 2048 ≈ 7.6τ = 0.53 µs, well inside the 1.5 µs that 1.5 clocks last at 1 MHz. A source of much higher resistance, or a faster clock, would not settle, and the datasheet's Figure 4-2 shows the maximum clock falling as source resistance rises.
Too slow is bad as well. The held charge leaks away, so the datasheet (§6.2) requires all 10 bits to be clocked out within 1.2 ms of the end of sampling: an effective clock of at least 10 kHz.
10 Wiring the MCP3008

| MCP3008 pin | Connect to | Note |
|---|---|---|
| VDD (16) | 3.3 V | The chip's supply. |
| VREF (15) | 3.3 V | This sets the full-scale range. Tying it to the same 3.3 V rail gives a 0–3.3 V input range, which is what Task 3 assumes. |
| AGND (14) and DGND (9) | ground | Analog and digital grounds. Both must be connected. |
| CLK (13) | BCM 11 (physical 23) | SCLK |
| DOUT (12) | BCM 9 (physical 21) | MISO: data out of the chip |
| DIN (11) | BCM 10 (physical 19) | MOSI: data into the chip |
| CS/SHDN (10) | BCM 8 (physical 24) | CE0, chip select |
| CH0–CH7 (1–8) | your signal | Must stay between 0 V and VREF |
Wire it with the Pi powered off. The MCP3008 is a 16-pin DIP: pin 1 is beside the notch, and the numbers run down that side and back up the other, so pins 1 and 16 sit either side of the notch. VDD and VREF go to 3.3 V, never 5 V: the chip's DOUT swings to VDD, and the Pi's MISO pin is not 5 V tolerant.
Keep the input between ground and VREF. Above VREF the reading just sticks at 1023; beyond the supply rails you can damage the chip. Here VREF and VDD are the same 3.3 V rail, so stay within 0 to 3.3 V. And never apply a signal while the ADC is unpowered.
This matters in Task 7. A function generator will happily produce a sine wave that swings symmetrically about zero, and the negative half is outside the ADC's range. You need to offset the signal so it sits entirely within 0–3.3 V, using the generator's DC offset control or a bias network. For example, a 1.65 V offset with a 1.0 V peak amplitude spans 0.65–2.65 V, leaving margin at both ends. Check the signal on the oscilloscope before connecting it to the ADC, and set the generator's amplitude and offset with the scope, not from the front-panel numbers alone.
Fit a bypass capacitor between VDD and ground, as close to the chip's pins as you can; the datasheet (§6.4) recommends 1 µF. The reason is the same as for the AD633 in Lab 2: an ADC measures small voltage differences, so supply noise translates directly into noisy readings, and on a breadboard next to a switching Pi there is plenty of it.
11 The Three-Byte Conversation
11.1 What the datasheet asks for
A conversion needs a start bit, then four configuration bits (single-ended or differential, and the channel number D2 D1 D0), then one more clock to finish sampling, then a null bit, then the 10 result bits. That is not a whole number of bytes, and the Pi's SPI hardware sends whole bytes. The datasheet's answer (§6.1) is to send seven leading zeros before the start bit, which lines everything up so that the 10-bit answer ends exactly on clock 24.

11.2 Build the request, decode the reply
The request is the same three bytes for any channel; only the channel number changes.
- Byte 1: 0x01: seven zeros and the start bit.
- Byte 2: 1 D2 D1 D0 followed by four don't-care bits: single-ended (1), then the channel number.
(8 + ch) << 4builds it: 8 + ch puts a 1 above the three channel bits, and shifting left by 4 moves them to the top of the byte. For channel 0 it is 0x80. - Byte 3: 0x00, a dummy byte, sent only so that the Pi clocks out the last eight result bits.
The reply comes back in the same three slots. The first byte is all unknown bits. The low two bits of the second are B9 and B8; the rest, marked ?, is MISO before the chip has driven it, so mask them off with & 3. The third byte is B7 to B0. For the 2.00 V of §8:
![The three bytes of one MCP3008 reading, bit by bit. The Pi sends 0000 0001 (the start bit), then 1 D2 D1 D0 followed by don't-care bits, which is 1000 0000 for channel 0, then a dummy byte. The chip returns unknown bits, then five unknown bits, a null 0 and B9 B8 = 10, then B7 to B0 = 0110 1100. Notes explain that (8 + ch) << 4 builds the channel byte, and that ((r[1] & 3) << 8) + r[2] gives 512 + 108 = 620, which is 1.998 V.](/_astro/mcp3008-bytes.CxtlT_e-_1eMN59.webp)
(8 + ch) << 4 builds the channel byte, and ((r[1] & 3) << 8) + r[2] gives 512 + 108 = 620, which is 1.998 V.11.3 read_adc(), from the provided ADC3008_SPI.py
import spidev
spi = spidev.SpiDev()
spi.open(0, 0) # /dev/spidev0.0
spi.max_speed_hz = 1000000 # 1 MHz
spi.mode = 0b00 # mode 0
def read_adc(channel):
if channel < 0 or channel > 7:
raise IndexError('channel 0-7')
request = [0x01, (8 + channel) << 4, 0x00]
data = spi.xfer2(request) # 3 back
return ((data[1] & 3) << 8) + data[2]Example only. Do not copy this code as it is: read it, learn from it, then write your own.
Every line of read_adc() is one of the pieces above: the request of §11.2, the three-for-three exchange of §4.4, and the decode. The two settings before it matter as much:
max_speed_hz = 1000000. 1 MHz is below the 1.35 MHz the datasheet allows even at 2.7 V, and it gives the sample capacitor ample time (§9.3). Leave it out andspidevmay clock far faster than the chip can follow, and the readings go wrong without any error.mode = 0b00, as §5.2 explains.
Task 2 asks you to turn the count into a voltage, v_volt; §12 gives the relation. Lab 8's submission also asks for an explanation of how ADC3008_SPI.py works; §3 to §11 are that explanation.
12 Counts, Volts and Calibration
12.1 The transfer function
The ADC returns a raw count. Converting it back to volts gives an estimate of the input, not the exact input, because many input voltages share each count (Equation 2):
depending on the convention you adopt in §8. The first uses the ideal LSB, VREF/1024, so each count is one code step and count 512 is exactly half of VREF: at VREF = 3.30 V, 512 × 3.30 V/1024 = 1.650 V. The second makes the top code, 1023, map to VREF, fitting the endpoints instead. State your convention and use the measured VREF. Task 4 asks you to output both the raw count and the voltage, which is good practice generally: the raw value is what the hardware actually produced and the voltage is your interpretation of it.
12.2 What the plot should show
Task 4 asks for at least 20 points and a plot of voltage against count, with an analysis of linearity and accuracy. To test the converter, plot an independently measured voltage, the DMM reading, against the raw count. Do not plot the voltage your code calculated with Equation (3): that is just the count times a constant, a perfect straight line by construction, and it tests nothing. For the DMM plot:
- The slope should be VREF divided by full scale, about 3.2 mV per count. A different slope usually means VREF is not what you assumed (the Pi’s 3.3 V rail is not exactly 3.300 V, so measure it), or the converter has some gain error.
- The intercept should be close to zero; ideally half an LSB, about 1.6 mV, if you fit the DMM voltage against the count, since code 0 covers 0 to 1 LSB (§8). A larger offset points to a ground problem or an input offset.
- Plot the residuals. As in Lab 2, a straight-line plot hides everything; the residuals reveal whether departures are random scatter at the ±½ LSB level, or a systematic curve indicating real nonlinearity.
12.3 Comparing with the DMM (Task 3)
Task 3 asks you to verify your Python output against a DMM. Before starting, work out what agreement is achievable:
- Quantization: ±½ LSB ≈ ±1.6 mV if you convert to the center of each code step, or 0 to 1 LSB low if you use Equation (3) as it stands. Say which you use.
- The ADC’s own offset, gain and linearity errors, from the datasheet. Ten bits of resolution does not mean ten bits of accuracy.
- The DMM has its own accuracy specification: look it up rather than treating the meter as perfect.
- VREF is whatever the 3.3 V rail actually is, so measure it and use the measured value. A 3.28 V reference treated as 3.30 V makes every reading (3.30 − 3.28)/3.28 ≈ 0.61% too high. That is a scale error, about 10 mV at mid-range, and it grows with the reading.
- Noise on the supply and input adds scatter. Averaging reduces independent random noise, but not a fixed offset or slow drift.
Then judge the agreement against the whole budget, and report both the difference you measured and the uncertainty you compared it with. Whether a 4 mV difference is good or bad depends on that budget; quantization alone cannot tell you.
For the adjustable 0–3.3 V source, a potentiometer across the 3.3 V rail is the obvious choice (Figure 17), and it is worth taking readings near both ends, since that is where offset and full-scale errors show up most clearly.
Task 3 also asks for proper error handling. Check the channel number, and catch failures to open the SPI device or to transfer. Be aware of what software cannot catch: the decoded count is always between 0 and 1023, even with a floating input or a broken wire, so a range check proves nothing. The best your program can do is flag readings that look implausible, such as a count stuck at 0 or 1023, and say that something may be wrong; the known-voltage tests of §17.2 are how you find out what.
(a) The ADC returns a count of 768 with VREF = 3.28 V. What voltage is that, under each convention in Equation (3)? How much do the answers differ?
(b) Your DMM reads 1.652 V and the ADC reports 1.649 V. How does this difference compare with quantization under the lower-edge and midpoint conventions? What other uncertainties are needed to judge agreement?
(c) You measure the Pi's rail at 3.31 V but your code assumes 3.30 V. What percentage error does that introduce, and is it constant across the range?
(d) With VREF = 3.30 V, what count corresponds to 1.000 V in the ideal model, and what input interval does that code represent?
(e) Channel 5 is read with the same read_adc(). What is the second request byte, in hex?
13 Sampling a Waveform
Task 7 moves from static voltages to a sine wave, and introduces the second approximation of §7: time.
13.1 What sets your sampling rate
Three things limit the sampling rate:
- The ADC's own conversion time: up to 200 ksps at 5 V and 75 ksps at 2.7 V (§9.1).
- The SPI clock: each reading needs three bytes, 24 clocks: 24 µs at 1 MHz, so no more than about 41 700 readings per second even if nothing else took any time.
- Your Python loop, whose overhead you must measure on your Pi.
Every sample costs a Python function call, an SPI transaction through the kernel and a list append, all under a non-real-time operating system. This is the Lecture 03 analysis again, now setting the bandwidth of an instrument rather than the brightness of an LED.
Timestamp each of a few thousand conversions with time.perf_counter(). N readings span N − 1 intervals, so from the first and last timestamps
That is your average sampling rate; report it. Say where in the loop you take each timestamp (just before or just after the read_adc() call), since you cannot timestamp the exact instant the ADC samples. And do not confuse it with the SPI clock rate: each reading takes 24 clocks, and Python adds far more time between readings.
Also look at the spread of the intervals, not just the mean. Sampling jitter smears a waveform in time and is the reason a digitized sine wave can look ragged even when every individual voltage reading is accurate. Before you blame jitter for a ragged waveform, though, compare the spread of the intervals with the signal’s period; noise on the input or the reference, and quantization, can make a waveform ragged too.
14 Aliasing and the Frequency Limit
Task 7 asks you to determine the maximum frequency your setup can handle and to analyze the limitation. The governing result is one of the most important in all of measurement.
For a band-limited signal sampled at uniform intervals, ideal reconstruction requires a sampling rate greater than twice its highest frequency:
Half the sampling rate is the Nyquist frequency. It is a limit you must stay strictly below, not a frequency you can use. Above it, different input frequencies give the same samples, and without a filter or some other knowledge of the signal you cannot tell them apart. A Python loop samples only roughly uniformly, so treat its average rate as an optimistic guide.
14.1 What happens above the limit
Sample a signal whose frequency is above the Nyquist frequency and it does not vanish or turn into noise. It aliases: it reappears as a completely different, lower frequency that was never present in the input, and the false signal looks entirely legitimate in the data.
Suppose your loop achieves fsample = 1000 samples per second, so the Nyquist frequency is 500 Hz.
- A 100 Hz input is sampled ten times per cycle. Reconstructed faithfully.
- A 400 Hz input gives only 2.5 samples per cycle. That is below the Nyquist frequency, but close to it. The shape is poor, though the frequency is still recoverable.
- A 900 Hz input aliases to |900 − 1000| = 100 Hz. Your plot shows a clean 100 Hz sine wave that does not exist.
- A 1000 Hz input aliases to 0 Hz, a constant. The signal appears to have stopped entirely.
The third case is the dangerous one, because nothing about the data looks wrong. This is why the oscilloscope is in Task 7: the scope samples far faster and shows the truth, so comparing your reconstruction against it is how you catch an alias. Demonstrating one on purpose, by sweeping the generator up until your plot shows a frequency falling as the input rises, makes a memorable figure and proves you understand the effect.

14.2 Answering Task 7 properly
“Maximum frequency” has more than one defensible answer, so define yours:
- The absolute limit is the Nyquist frequency, fsample/2, above which aliasing occurs.
- The practical limit for a recognizable waveform shape is lower, perhaps fsample/10 or so, since two or three points per cycle recover the frequency but not the shape. Decide what you mean by “recognizable”.
- Sampling jitter degrades things further, and increasingly so as frequency rises, because a fixed timing error is a larger fraction of a shorter period.
In practice, raise the input frequency with the amplitude held fixed, and compare your recorded waveform with the scope at each step. Record the sample intervals, the frequency you see, and how you estimated the amplitude. Do not expect the amplitude to fade away smoothly as the frequency rises: sparse samples can miss the peaks, but an alias can come back at full size. Then choose a stated criterion for “usable”, such as the frequency or amplitude error you will accept, and compare the limit you find with fsample/2.
A final point worth a sentence: in a real instrument an anti-aliasing filter (a low-pass filter before the ADC, just like the RC network in Lab 1 Task 3) suppresses frequencies above the Nyquist frequency before sampling, so they cannot alias. The MCP3008 datasheet (§6.3) recommends one. Your setup has no such filter, which is why you can demonstrate the effect.
(a) Your loop achieves 2000 samples/s. What is the Nyquist frequency? How many samples per cycle for a 250 Hz input?
(b) With that rate, what apparent frequency does a 1900 Hz input produce?
(c) You see 50 Hz in your samples while the scope shows 1950 Hz. Give two uniform sampling rates that could produce this alias. Why does the alias alone not determine the sampling rate?
(d) A sine wave sampled at exactly twice its frequency can reconstruct to zero amplitude. Sketch why, and say what this implies about the strictness of the inequality in Equation (4).
15 Remote Access: SSH and VNC
Tasks 5 and 6 let you operate the Pi from your laptop while the circuit stays on the bench.
| Method | What you get | When to use it |
|---|---|---|
| SSH Secure Shell | A terminal on the Pi, in a window on your laptop | Running scripts, editing files, everything command-line. Light, fast, works over a poor connection. |
| VNC Virtual Network Computing | The Pi's entire graphical desktop, mirrored on your laptop | Anything needing graphics: viewing a Matplotlib window, using the desktop tools. Much heavier on the network. |
15.1 SSH: the Pi's terminal on your laptop

# On the Pi, once: Interface Options -> SSH (and -> VNC for §15.2)
sudo raspi-config
# On the Pi: find its address on the network
hostname -I
# From your laptop's terminal (macOS, Linux, or Windows PowerShell)
ssh <user>@<pi-ip>
# Copy a file back from the Pi to the machine you are sitting at
scp <user>@<pi-ip>:~/lab8/data.csv .
<user> is the account you log in to the Pi with; current Raspberry Pi OS images have no default pi account. The program you run over SSH still runs on the Pi: its GPIO and SPI pins stay on the bench, and only text crosses the network.
15.2 VNC: the Pi's whole desktop in a window

Enable VNC in raspi-config, then connect to the Pi’s address from a VNC viewer on your laptop. Current Raspberry Pi OS uses the WayVNC server, and the Raspberry Pi documentation suggests the TigerVNC viewer; an older image may use a different server, so check the Raspberry Pi remote-access guide for your version. Use VNC for windows, such as live plots and the temperature program of Task 6; use SSH for everything else.
A plain SSH login gives you a terminal, not a screen. With nowhere to draw, plt.show() either fails with an error or quietly opens no window at all.
Three ways round it, and knowing which to choose is the real lesson:
- Save instead of showing. Write the figure to a PNG and copy it back with
scp. The best option for automated data collection, and what a deployed instrument does. - Use VNC, which gives a real desktop for the window to open on. This is what Task 6 asks for when it says to run the temperature program remotely.
- X11 forwarding (
ssh -X), which sends the window itself across the network. It works only if the Pi allows it and your laptop runs an X server (on macOS, XQuartz);-Xdoes not install either.
- Your laptop must be able to reach the Pi over the network. The easiest way is to put both on the same network, but campus Wi-Fi often stops wireless devices from talking to each other, which blocks the connection however correct your settings are. If SSH times out, suspect this before suspecting your configuration.
- The Pi's address may change between sessions if assigned by DHCP. Note it each time, or use the hostname.
- The first time you connect, SSH shows the Pi’s key fingerprint and asks whether to trust it. Check that it really is your Pi (on the Pi,
ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pubprints the fingerprint). If SSH later warns that the key has changed, find out why before you accept it. - Task 5 asks you to demonstrate remote operation of your voltage measurement program, so plan a screenshot showing your laptop's terminal running the Pi's program, with the ADC reading changing as you adjust the potentiometer.
- Use the account and credentials assigned for the lab. Ask the instructor before changing credentials on a shared Pi.
16 The Final Project
With Lab 8 you have sensing, actuation, timing, serial communication, digitization and remote access: the full toolkit for an instrument. The final project is where you put them together in a design of your own.

In outline:
- Teams. Three or four students. Prof Yang sets the teams and picks each Team Leader.
- Proposal. Your team writes it in week 1, with the initial bill of materials. Order parts early.
- Build. A progress report with video clips each week, and a peer evaluation each week.
- Expo. In week 7, your team opens with a short video, presents its design and demos the working build live.
- Final report. A user manual for your build, with a data sheet. Due in week 8.
Open Final project in the course menu for the full brief: the theme, the requirements, the due times and the grading.
17 Common Mistakes and Bench Safety
17.1 Things that destroy hardware
- Input voltage outside 0–VREF. Especially a function generator swinging negative. Check on the scope first (§10).
- 5 V to the MCP3008 or its inputs while the Pi's SPI pins are connected.
- VDD and ground swapped on the chip. The MCP3008 is a 16-pin DIP; count pins carefully from the notch.
- Rewiring with power applied.
17.2 Debugging SPI without a detect command
Because SPI has no acknowledgment and no discovery, a wrong connection returns plausible-looking numbers rather than an error. Work through it in this order:
- Does
/dev/spidev0.0exist? If not, SPI is not enabled; go back toraspi-configand reboot. - Ground the input channel. You should read very close to 0. If not, the problem is wiring or configuration, not your conversion arithmetic.
- Tie the input to 3.3 V. You should read very close to full scale, 1023. These two tests bracket the whole transfer function in ten seconds.
- All zeros, always? Suspect MISO, chip select, or power.
- Wildly fluctuating readings? The input is probably floating. An unconnected ADC channel is a high-impedance node that picks up everything nearby. That is normal, not a fault.
- Reading exactly half, or double, what you expect? Suspect a bit-shift error in assembling the 10-bit result, or an SPI mode mismatch (§5.2).
The grounded-input and full-scale tests are the SPI equivalent of reading the MCP9808's manufacturer ID: a known input proving the chain before you trust an unknown one.
17.3 Things that waste your afternoon
- Confusing MOSI and MISO. They are not symmetric, and nothing warns you.
- Forgetting VREF, or leaving it floating: readings become meaningless and drift.
- Assuming exactly 3.300 V. Measure the rail (§12.2).
- Mixing the 1023 and 1024 conventions between two parts of the same program (§8).
- Leaving out
max_speed_hz, or setting the wrong SPI mode (§11.3). - A function generator set to a symmetric sine with no DC offset.
- Concluding the ADC is broken when you are actually seeing an alias (§14.1).
- Plotting inside the sampling loop, destroying the sample rate.
- Expecting
plt.show()to work over plain SSH (§15.2).
17.4 Before you leave
Copy scripts, CSV files, plots and remote-access screenshots to your own machine and check they open. Remove your directory from the shared Pi, and shut down cleanly. If you changed the Pi's password or network settings, tell the instructor or a TA.
18 Self-Check
- Name the four SPI signals and say which are shared between devices and which is not.
- What does full duplex mean, and why does it mean you must send bytes in order to receive them?
- What do CPOL and CPHA set, and which mode does the MCP3008 use? What does a mode mismatch look like?
- Give three differences between SPI and I²C, and state which protocol suits a slow temperature sensor and which suits a fast ADC, with reasons.
- Define quantization and sampling. Which sets amplitude resolution and which sets frequency range?
- Compute the LSB size for a 10-bit ADC with VREF = 3.3 V, and state the quantization error of a single reading.
- Why do the counts run 0 to 1023 rather than 1 to 1024, and where does it matter?
- Explain successive approximation in two or three sentences, and say why conversion time grows with resolution.
- Why does the MCP3008 exchange three bytes for a 10-bit answer, and where in the reply are the 10 bits?
- State the Nyquist criterion. If your loop achieves 800 samples/s, what is the highest faithfully representable frequency?
- At that rate, what apparent frequency does a 750 Hz input produce? Why is this more dangerous than the signal simply disappearing?
- What is an anti-aliasing filter, where does it go, and which earlier lab circuit is it?
- When would you use SSH and when VNC? Why does a Matplotlib window need more than plain SSH?
An ADC turns a voltage into a number, and both axes of that conversion are approximations you can quantify. Quantization sets the finest voltage difference you can see; the sampling rate (set here by your Python loop, not by the hardware) sets the highest frequency you can believe. Sample too slowly and the signal does not disappear, it lies to you. Knowing both limits, and measuring rather than assuming them, is what separates an instrument from a circuit that produces numbers.
19 Practical Engineering Connections
- ADCs are everywhere. Every digital multimeter, oscilloscope, data logger and sound card begins with the conversion you built this week.
- Resolution in practice. Audio uses 16–24 bits, scientific instruments 16–24, control systems often 10–12. Each extra bit halves the LSB and costs time, money and noise performance.
- SPI in the field. SD cards, display controllers, radio modules, flash memory and most high-rate sensors use SPI, because of the speed advantage in §6.
- Aliasing as a real hazard. Wagon wheels turning backwards in films, moiré patterns in photographs, and misdiagnosed vibration in machinery are all the effect of §14.1. The last of these has caused real engineering failures.
- Anti-aliasing filters. Mandatory ahead of any serious ADC, and the direct descendant of the RC low-pass you analyzed in Lab 1.
- Oversampling. Averaging many readings can resolve finer than one code step, provided some noise spreads the readings across neighboring codes. The uncertainty of the mean then falls as 1/√n, at the cost of time resolution. Averaging cannot undo an alias or a calibration error.
- Headless operation. Weather stations, telescope controllers, laboratory data loggers and industrial monitors all run without a screen, accessed over the network exactly as in Tasks 5 and 6.
- Toward the project. You now have sensing, actuation, timing, serial communication, digitization and remote access. That is the full toolkit for an instrument, and the group project (§16) is where you combine them into something of your own design.