← About PHYS 351

PHYS 351 · Advanced Instrumentation

Lecture 08 · ADC, SPI & remote access

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.

The one idea to carry out of this lecture

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.

Lab 8 setup

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 taskWhat you doConcept & section
1Network, lab directory, OS update, enable SPI, download ADC3008_SPI.pyBringing SPI up (§3.2)
2Wire the MCP3008; read a channel as a voltage; demonstrateWiring; the three-byte conversation; counts to volts (§10, §11, §12.1)
3Build a 0–3.3 V source; compare your readings against a DMM; error handlingQuantization; calibration and accuracy (§8, §12.3)
4Record counts, calculated volts and DMM volts for 20+ points; fit DMM volts against counts and examine residualsThe transfer function (§12)
5–6SSH from your laptop; VNC desktop; run your programs remotelyRemote access (§15)
7Extra credit: sine wave into both the ADC and the scope; plot voltage against time; find the maximum usable frequencySampling, 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.

Three panels compare serial protocols. UART: the Pi's TX goes to the device's RX and back on a second wire, with no clock, so both ends must agree on the baud rate. I2C: the Pi and two chips at addresses 0x18 and 0x19 share two pulled-up wires, SDA and SCL, and each byte has an ACK or NAK bit. SPI: the Pi and one chip are joined by four wires, SCLK, MOSI and chip select from the Pi and MISO back; drivers are push-pull, the chip is picked by its own select wire, and there is no acknowledgment.
Figure 1. Three serial protocols. UART: the Pi's TX goes to the device's RX and back on a second wire, with no clock, so both ends must agree on the baud rate. I²C: the Pi and two chips at addresses 0x18 and 0x19 share two pulled-up wires, SDA and SCL, and each byte has an ACK or NAK bit. SPI: the Pi and one chip are joined by four wires (SCLK, MOSI and chip select from the Pi, MISO back); the drivers are push-pull, the chip is picked by its own select wire, and SPI has no built-in acknowledgment.
  • 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

The Raspberry Pi as SPI controller and the MCP3008 as peripheral. SCLK from BCM 11 to CLK carries one bit per tick; MOSI from BCM 10 to DIN carries the request; MISO from DOUT back to BCM 9 carries the answer; chip select from BCM 8 (CE0) to the chip's CS/SHDN pin, active low, tells the chip to listen.
Figure 2. The Pi as SPI controller and the MCP3008 as peripheral. SCLK from BCM 11 to CLK carries one bit per tick; MOSI from BCM 10 to DIN carries the request; MISO from DOUT back to BCM 9 carries the answer; chip select from BCM 8 (CE0) to the chip's CS/SHDN pin, active low, tells the chip to listen.
SignalNameDirectionMCP3008 pin
SCLKSerial clockcontroller → deviceCLK
MOSIController Out, Peripheral Incontroller → deviceDIN
MISOController In, Peripheral Outdevice → controllerDOUT
CE0Chip enable / chip selectcontroller → deviceCS/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

Raspberry Pi 40-pin header map distinguishing physical pin positions from BCM GPIO numbers and marking 3.3 V, 5 V, ground, I²C, UART, and SPI connections. Power pins are not GPIO inputs.
Figure 3. The Raspberry Pi 40-pin header, showing physical pin positions and BCM GPIO numbers, and marking 3.3 V, 5 V, ground, I²C, UART and SPI pins.
SignalBCMPhysical pin
MOSI1019
MISO921
SCLK1123
CE0824
CE1726
# 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.

One Pi with three SPI chips. SCLK, MOSI and MISO are shared by all three. Each chip has its own select line: CE0, CE1 and an ordinary GPIO. CE0 is low, so the MCP3008 is talking; the other two chips have their select high and have released MISO to high impedance.
Figure 4. One Pi with three SPI chips. SCLK, MOSI and MISO are shared. Each chip has its own select line: CE0, CE1 and an ordinary GPIO. CE0 is low, so the MCP3008 is talking; the other two chips have their select high and have released MISO to high impedance.

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.

Two 8-bit shift registers joined in a ring. The Pi's register holds 1100 1010 and the MCP3008's holds 0110 1100. MOSI carries the Pi's most significant bit out into the chip's least significant end; MISO carries the chip's most significant bit out into the Pi's least significant end. Each clock tick moves every bit one place.
Figure 5. Two 8-bit shift registers joined in a ring. The Pi's register holds 1100 1010 and the MCP3008's holds 0110 1100. MOSI carries the Pi's most significant bit into the chip's least significant end; MISO carries the chip's most significant bit into the Pi's least significant end. Each clock tick moves every bit one place.

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.

The two shift registers after each of eight clock ticks, with the Pi's original bits shaded slate and the chip's shaded rose. At each tick one slate bit leaves the Pi and enters the chip while one rose bit enters the Pi. After tick 8 the Pi holds 0110 1100 and the chip holds 1100 1010: the bytes have traded places.
Figure 6. The two shift registers after each of eight clock ticks, the Pi's original bits shaded slate and the chip's shaded rose. At each tick one slate bit leaves the Pi and enters the chip while one rose bit enters the Pi. After tick 8 the Pi holds 0110 1100 and the chip holds 1100 1010: the bytes have traded places.
SPI is full duplex, and that matters here

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

Timing of one SPI byte in mode 0. Chip select goes low, SCLK makes eight pulses, and on the same eight ticks MOSI carries the Pi's byte 0xCA (1100 1010) while MISO carries the chip's byte 0x6C (0110 1100). Both sides read at each rising edge and change their data on the falling edge.
Figure 7. One SPI byte in mode 0. Chip select goes low and SCLK makes eight pulses; on the same eight ticks MOSI carries the Pi's byte 0xCA (1100 1010) while MISO carries the chip's byte 0x6C (0110 1100). Both sides read at each rising edge and change their data on the falling edge.

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.
Figure 8. The call 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.

The four SPI clock modes drawn against one row of data bits D7 to D0. Mode 0 (CPOL 0, CPHA 0) idles low and reads on the rising edge; mode 1 (CPOL 0, CPHA 1) idles low and reads on the falling edge; mode 2 (CPOL 1, CPHA 0) idles high and reads on the falling edge; mode 3 (CPOL 1, CPHA 1) idles high and reads on the rising edge. In every mode the reading edge falls in the middle of each data bit.
Figure 9. The four SPI clock modes against one row of data bits D7 to D0. Mode 0 (CPOL 0, CPHA 0) idles low and reads on the rising edge; mode 1 (0, 1) idles low and reads on the falling edge; mode 2 (1, 0) idles high and reads on the falling edge; mode 3 (1, 1) idles high and reads on the rising edge. In every mode the reading edge falls in the middle of each data bit.

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.

MCP3008 datasheet Figure 1-1, serial interface timing: chip select falls at least t_SUCS before the first rising clock edge; DIN must be valid t_SU before and t_HD after each rising edge; DOUT leaves high impedance with a null bit, then MSB out, each changing t_DO after a falling clock edge, and returns to high impedance t_DIS after chip select rises, which must stay high for t_CSH.
Figure 10. The MCP3008 serial interface timing. Chip select falls at least tSUCS before the first rising clock edge; DIN must be valid tSU before and tHD after each rising edge; DOUT leaves high impedance with a null bit and then the MSB, each changing tDO after a falling edge, and returns to high impedance tDIS after chip select rises. Source: Microchip MCP3004/3008 datasheet (DS21295D), Figure 1-1.

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.

PropertyI²C (Lab 6, Lab 7)SPI (Lab 8)
Signal wires, excluding power and ground2 shared3 shared + 1 chip select per device
Device selection7-bit address sent on the busA dedicated hardware pin per device
Clock on the Pi100 kHz by default1 MHz in Lab 8; many SPI chips run at tens of MHz
DirectionHalf duplex: one way at a timeFull duplex: both directions at once
ElectricalOpen drain with pull-ups; lines driven down onlyPush-pull; driven up and down, no pull-ups needed
AcknowledgmentACK/NAK after each byte (it confirms receipt, not that the data are right)None; some chips add their own status or check bits
ScalingAdd devices with no extra pins, until addresses collideEvery extra device costs a GPIO pin
Discoveryi2cdetect finds devices that answer their addressNo 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.

Illustration of a 1 MHz square wave on two kinds of line. Top, SPI push-pull: the driver pulls the line up and down, so both edges are sharp. Bottom, I2C open drain: the line falls fast but rises along an RC curve with time constant 1.5 kilohms times an illustrative 100 pF, 150 ns, barely reaching 3.3 V before the next fall.
Figure 11. An illustration of a 1 MHz square wave on two kinds of line. Top, SPI push-pull: the driver pulls the line up and down, so both edges are sharp. Bottom, I²C open drain: the line falls fast but rises along an RC curve with time constant 1.5 kΩ × 100 pF = 150 ns, reaching about 3.18 V after the 0.5 µs high interval. The slow rise leaves less time above the receiver's high threshold. The 100 pF is illustrative.
The trade in one sentence

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.

No ACK means no warning

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.

The same slowly varying voltage between about 0.3 and 3.1 V read two ways over 10 seconds. A GPIO input reports only 0 or 1, switching at an illustrative threshold of 1.65 V. The MCP3008 reports a count from 0 to 1023 that follows the voltage in steps of 3.2 mV.
Figure 12. The same slowly varying voltage, between about 0.3 and 3.1 V, read two ways over 10 s. A GPIO input reports only 0 or 1, switching at an illustrative threshold of 1.65 V. The MCP3008 reports a count from 0 to 1023 that follows the voltage in steps of 3.2 mV.

An ADC performs two distinct approximations, and keeping them separate is essential because they have different consequences.

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

VLSB = VREF2N(1)

For the worked examples we use an ideal converter that simply rounds down, following datasheet Equations 4-1 and 4-2:

code = ⌊1024 VinVREF⌋(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.

Worked example: 2.00 V on CH0

The MCP3008 is a 10-bit converter. With VREF = 3.30 V:

VLSB = 3.30 V210 = 3.30 V1024 = 3.22 mV

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

Ten-bit ADC transfer function with a 3.3 V reference. Full scale, output code against input voltage from 0 to 3.3 V looks like a straight line from 0 to 1023. Zoomed to 1.985 to 2.013 V, it is a staircase of steps 1 LSB = 3.22 mV wide; 2.000 V gives code 620.
Figure 13. The ideal round-down 10-bit model with a 3.3 V reference. At full scale, code against input voltage from 0 to 3.3 V looks like a straight line from 0 to 1023. Zoomed to 1.985–2.013 V it is a staircase of steps 1 LSB = 3.22 mV wide, and 2.000 V gives code 620.
1024 levels, but the counts run 0 to 1023

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.
MCP3008 datasheet functional block diagram: inputs CH0 to CH7 pass through an input channel multiplexer to a sample and hold; a comparator compares the held voltage with a DAC driven from VREF under a 10-bit successive-approximation register; control logic driven by CS/SHDN, DIN and CLK moves the result into a shift register that drives DOUT.
Figure 14. The MCP3008 functional block diagram. Inputs CH0–CH7 pass through a channel multiplexer to a sample-and-hold; a comparator compares the held voltage with a DAC driven from VREF, under a 10-bit successive-approximation register; control logic driven by CS/SHDN, DIN and CLK moves the result into a shift register that drives DOUT. Source: MCP3008 datasheet.

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.

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.

Successive approximation of 2.00 V with a 3.3 V reference. Over ten clocks the DAC tries codes 512, 768, 640, 576, 608, 624, 616, 620, 622 and 621; each trial at or below 2.00 V keeps its bit and each above drops it. The kept bits B9 to B0 read 1001101100, which is 620. A zoomed panel shows the last six trials within a few millivolts of 2.00 V.
Figure 15. Successive approximation of 2.00 V with a 3.3 V reference. Over ten clocks the DAC tries codes 512, 768, 640, 576, 608, 624, 616, 620, 622 and 621; each trial at or below 2.00 V keeps its bit and each above drops it. The kept bits B9 to B0 read 10 0110 1100, which is 620. A zoomed panel shows the last six trials within a few millivolts of 2.00 V.

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.

MCP3008 datasheet Figure 4-1, analog input model: a signal source with source impedance drives the channel pad, which has 7 pF pin capacitance, clamp diodes to VDD and VSS, and about 1 nA leakage; a sampling switch with 1 kilohm resistance connects it to the 20 pF sample capacitor.
Figure 16. The analog input model. A signal source with source impedance drives the channel pad, which has 7 pF pin capacitance, clamp diodes to VDD and VSS, and about 1 nA leakage; a sampling switch with 1 kΩ resistance connects it to the 20 pF sample capacitor. Source: MCP3008 datasheet, Figure 4-1.

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,

τ = 3.5 kΩ × 20 pF = 70 ns

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

Wiring the MCP3008 to the Pi header, pins 17 to 26. VDD (pin 16) and VREF (pin 15) go to the 3.3 V rail from header pin 17; AGND (14) and DGND (9) go to the ground rail from header pin 25. CLK (13) goes to SCLK pin 23, DOUT (12) to MISO pin 21, DIN (11) to MOSI pin 19, and chip select (10) to CE0 pin 24. A 10 kilohm potentiometer across the rails feeds its wiper to CH0 (pin 1).
Figure 17. Wiring the MCP3008 to the Pi header, pins 17 to 26. VDD (pin 16) and VREF (pin 15) go to the 3.3 V rail from header pin 17; AGND (14) and DGND (9) go to the ground rail from header pin 25. CLK (13) goes to SCLK on pin 23, DOUT (12) to MISO on pin 21, DIN (11) to MOSI on pin 19, and CS/SHDN (10) to CE0 on pin 24. A 10 kΩ potentiometer across the rails feeds its wiper to CH0 (pin 1).
MCP3008 pinConnect toNote
VDD (16)3.3 VThe chip's supply.
VREF (15)3.3 VThis 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)groundAnalog 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 signalMust 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.

Never exceed the input range

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.

MCP3008 datasheet Figure 6-1, SPI communication in 8-bit segments, mode 0,0: over 24 clocks the MCU transmits 0000 0001 (start bit), then SGL/DIFF D2 D1 D0 and four don't-care bits, then eight don't-care bits. It receives eight unknown bits, then five unknown bits, the null bit 0, B9 and B8, then B7 to B0. Data leaves the converter on falling edges and the MCU latches it on rising edges.
Figure 18. SPI communication in 8-bit segments, mode 0,0. Over 24 clocks the controller sends 0000 0001 (the start bit), then SGL/DIFF, D2, D1, D0 and four don't-care bits, then eight don't-care bits. It receives eight unknown bits, then five unknown bits, the null bit, B9 and B8, then B7 to B0. Data leaves the converter on falling edges and the controller latches it on rising edges. Source: MCP3008 datasheet, Figure 6-1.

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) << 4 builds 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:

((r1 & 3) << 8) + r2 = (0b10 << 8) + 0x6C = 512 + 108 = 620
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.
Figure 19. The three bytes of one MCP3008 reading, bit by bit. The Pi sends 0000 0001 (the start bit), then 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. (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

ADC3008_SPI.py (excerpt)
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 and spidev may 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):

V = count1024 × VREF     or     V = count1023 × VREF(3)

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)

Set expectations before you measure

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.

Practice 12

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

  1. The ADC's own conversion time: up to 200 ksps at 5 V and 75 ksps at 2.7 V (§9.1).
  2. 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.
  3. 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.

Measure your sample rate; do not assume it

Timestamp each of a few thousand conversions with time.perf_counter(). N readings span N − 1 intervals, so from the first and last timestamps

fs ≈ N − 1tN − t1

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.

The Nyquist–Shannon sampling theorem

For a band-limited signal sampled at uniform intervals, ideal reconstruction requires a sampling rate greater than twice its highest frequency:

fsample > 2fsignal     equivalently     fmax = fsample2(4)

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.

Worked example: a fictitious signal

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.

Sampling at 1000 samples per second: a 100 Hz sine wave is resolved, while samples of a 900 Hz sine wave appear to follow a 100 Hz wave. Sample points alone cannot distinguish these frequencies.
Figure 20. Sampling at 1000 samples per second. Top: a 100 Hz input, ten samples per cycle. Bottom: a 900 Hz input, whose samples trace a 100 Hz wave that is not in the signal. From the samples alone the two are indistinguishable; comparing with the scope, or changing the sample rate, tells them apart.

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.

Practice 14

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

MethodWhat you getWhen to use it
SSH
Secure Shell
A terminal on the Pi, in a window on your laptopRunning 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 laptopAnything 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

SSH: a laptop terminal logged in to the Raspberry Pi over the same network on port 22, encrypted. Keystrokes go to the Pi and text output comes back; the terminal shows the ADC program printing counts 620 and 621 with voltages 1.998 and 2.001 V. The program runs on the Pi, whose pins stay on the bench.
Figure 21. SSH: a laptop terminal logged in to the Pi over the same network, on port 22, encrypted. Keystrokes go to the Pi and text output comes back; the terminal shows the ADC program printing counts 620 and 621, 1.998 and 2.001 V. The program runs on the Pi, whose pins stay on the bench.
# 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

VNC: a laptop shows the whole Raspberry Pi desktop in a viewer window, including a live plot. Screen pixels travel from the Pi to the laptop and mouse and keyboard events go back, over the same network on port 5900.
Figure 22. VNC: the laptop shows the whole Pi desktop in a viewer window, including a live plot. Screen pixels travel from the Pi to the laptop, and mouse and keyboard events go back, over the same network on port 5900.

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.

Why a plot needs more than SSH

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:

  1. 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.
  2. 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.
  3. 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); -X does not install either.
Practical notes
  • 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.pub prints 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.

Final-project timeline over eight weeks. Week 1: proposal and initial BOM, order parts. Weeks 2 to 5: build, wire and code, and film every week. Week 6: test with customers and finish. Week 7: the Expo, with the team video, a technical presentation and a live demo. Week 8: the final report. A weekly report is due at the start of weeks 3 to 7, and a peer evaluation at the start of weeks 2 to 7.
Figure 23. The final-project timeline over eight weeks. Week 1: proposal and initial BOM, order parts. Weeks 2 to 5: build, wire and code, and film every week. Week 6: test with customers and finish. Week 7: the Expo, with the team video, a technical presentation and a live demo. Week 8: the final report. A weekly report is due at the start of weeks 3 to 7, and a peer evaluation at the start of weeks 2 to 7.

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:

  1. Does /dev/spidev0.0 exist? If not, SPI is not enabled; go back to raspi-config and reboot.
  2. Ground the input channel. You should read very close to 0. If not, the problem is wiring or configuration, not your conversion arithmetic.
  3. 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.
  4. All zeros, always? Suspect MISO, chip select, or power.
  5. 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.
  6. 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

  1. Name the four SPI signals and say which are shared between devices and which is not.
  2. What does full duplex mean, and why does it mean you must send bytes in order to receive them?
  3. What do CPOL and CPHA set, and which mode does the MCP3008 use? What does a mode mismatch look like?
  4. 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.
  5. Define quantization and sampling. Which sets amplitude resolution and which sets frequency range?
  6. Compute the LSB size for a 10-bit ADC with VREF = 3.3 V, and state the quantization error of a single reading.
  7. Why do the counts run 0 to 1023 rather than 1 to 1024, and where does it matter?
  8. Explain successive approximation in two or three sentences, and say why conversion time grows with resolution.
  9. Why does the MCP3008 exchange three bytes for a 10-bit answer, and where in the reply are the 10 bits?
  10. State the Nyquist criterion. If your loop achieves 800 samples/s, what is the highest faithfully representable frequency?
  11. At that rate, what apparent frequency does a 750 Hz input produce? Why is this more dangerous than the signal simply disappearing?
  12. What is an anti-aliasing filter, where does it go, and which earlier lab circuit is it?
  13. When would you use SSH and when VNC? Why does a Matplotlib window need more than plain SSH?
Lab takeaway

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

  1. ADCs are everywhere. Every digital multimeter, oscilloscope, data logger and sound card begins with the conversion you built this week.
  2. 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.
  3. 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.
  4. 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.
  5. Anti-aliasing filters. Mandatory ahead of any serious ADC, and the direct descendant of the RC low-pass you analyzed in Lab 1.
  6. 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.
  7. 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.
  8. 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.

← All course materials