Mastering Arduino Part 13: SPI: A Different Bus

Mastering Arduino Part 13 cover: SPI: A Different Bus, with a controller, three peripherals, shared SCK, MOSI and MISO lines, and a chip-select line to each peripheral

Mastering Arduino Part 13: SPI: A Different Bus

Two people sit across a table, each with a row of eight coins in front of them, some heads up and some tails up. A metronome ticks. On every tick, each person pushes their whole row one place to the right, and the coin pushed off the right end goes to the other person, who slides it in at the left end of their own row. After eight ticks every coin has crossed the table. Each person now holds exactly the pattern the other started with, and neither one took a turn. The Serial Peripheral Interface (SPI) works this way: two 8-bit shift registers joined in a ring, with a clock signal as the metronome.

SPI is a synchronous serial bus in which one controller drives a shared clock and exchanges data with one or more peripherals over a separate wire for each direction [1]. Synchronous means the clock travels with the data, so no baud rate has to be agreed in advance, which was the requirement for the UART link in Part 11. A peripheral is the chip the controller talks to: a sensor, a converter, a display, a memory. Part 12 gave every peripheral on a two-wire bus an address. SPI takes a different approach and gives every peripheral its own select wire instead.

That choice costs wires and buys speed. The ATmega328P on an Uno can clock SPI at up to 8MHz [2], against the 100kHz and 400kHz speeds of the I2C bus in Part 12. Many analog-to-digital converters, shift registers, flash memory chips, displays, and radio modules offer SPI for that reason.

This part builds the idea in order: what the four signals do, how chip select shares one bus, what the four clock modes mean, how fast the Uno can clock the bus, and how SPI compares with UART and I2C. It then shows the hard way (a byte sent by hand and the SPI registers), the SPI.h library that hides them, and a trap in the AVR hardware that can silently switch an Uno out of controller mode. The practical project puts two devices on one bus: an MCP3008 converter reads a potentiometer, and a 74HC595 shift register shows the reading as a bar of eight LEDs. Both parts are introduced here. Everything is 5V Uno R3 hardware. You can build the project on a breadboard or run it in the Electronics Lab, which has working models of both chips, and an earlier, smaller Lab shows a single SPI transaction on a display. SD cards also use SPI, and they are covered in Part 26.

Bill of Materials

Component Description Buy on Amazon Buy on Temu Buy on SparkFun Buy on Seeed Studio Datasheet
Arduino Uno R3 The controller board. Any Uno R3 or compatible board works. Amazon Link Not yet available SparkFun Link Seeed Link Uno R3 datasheet
MCP3008 analog-to-digital converter 10-bit, 8-channel SPI converter. Buy the 16-pin DIP (through-hole) package so it fits a breadboard. Not yet available Not yet available Not yet available Not yet available MCP3008 datasheet
74HC595 shift register 8-bit shift register with output latches, such as the SN74HC595N. Buy the 16-pin DIP package. Not yet available Not yet available Not yet available Not yet available SN74HC595 datasheet
10kΩ potentiometer The knob whose position the MCP3008 measures. Amazon Link Temu Link SparkFun Link N/A N/A
5mm LEDs (×8) Red LEDs for the bar. Any 5mm color works, but the current figures in this part assume a red LED. Amazon Link Temu Link SparkFun Link Not yet available N/A
1kΩ resistors (×8) One per LED. A resistor kit that includes 1kΩ covers it. Amazon Link Temu Link SparkFun Link Seeed Link N/A
Breadboard & jumper wires Short wires keep an SPI bus easy to debug. Amazon Link Temu Link SparkFun Link Seeed Link N/A
USB A-to-B cable The square printer-style plug the Uno uses. It must carry data, not just power. Not yet available Not yet available Not yet available Not yet available N/A

The products linked above may contain affiliate links. The Makers Workbench earns from qualifying purchases when these links are used.

The MCP3008 and the 74HC595 are both 16-pin chips in the same package, so read the marking on each before placing it. Both run from 5V as wired here: the MCP3008 accepts 2.7V to 5.5V and the 74HC595 accepts 2V to 6V [3][4]. The two Labs in this part use simulated parts: a simulated SSD1306 OLED in the first, and simulated copies of the MCP3008 and 74HC595 in the second. The display is not part of the project and is not in this table.

How SPI Actually Works

Where SPI Comes From

Motorola had put an SPI on a microcontroller by 1985. A Motorola data sheet copyrighted that year for the MC68HC05C4 8-bit microcomputer describes a serial peripheral interface built into the chip, and it names four signals that this part covers: MOSI, MISO, SCK, and SS [5]. The feature list in that document reads like a summary of this article: full-duplex three-wire synchronous transfers, master or slave operation, programmable clock polarity and phase, and a maximum master bit rate of 1.05MHz [5]. An Uno's SPI clock can run about eight times faster than that. The 1985 sheet is the earliest document used for this article, so the article makes no claim about an earlier date.

SPI never settled into one rigid specification. Arduino's own guide puts it this way: the standard is loose, each device implements it a little differently, and the datasheet of each chip decides the settings [1]. That is why a large part of this article is about reading settings out of a datasheet.

Four Signals, Two Sets of Names

A basic SPI link uses four signals. Three are shared by every peripheral, and the fourth belongs to one peripheral only.

Role Name printed on most chips and in the ATmega datasheet Name in Arduino's documentation Direction Uno pin
Data from the controller MOSI (Master Out, Slave In) COPI (Controller Out, Peripheral In) Controller to peripheral D11
Data from the peripheral MISO (Master In, Slave Out) CIPO (Controller In, Peripheral Out) Peripheral to controller D12
Clock SCK SCK Controller to peripheral D13
Chip select SS (Slave Select) or CS CS Controller to one peripheral D10 by default, any pin works

The pins in the last column are the Uno R3's default SPI pins [6], and MOSI, MISO, and SCK also appear on the Uno's ICSP header [6]. Arduino's documentation uses controller and peripheral, with COPI and CIPO, and says it no longer supports the older master and slave terms [1]. The ATmega datasheet and the printing on most chips still use the old names [2]. Only the names differ. The wiring tables in this part use MOSI and MISO because those are the names a reader will find printed on the MCP3008 and on breakout boards, and the text says controller and peripheral.

Two Shift Registers in a Ring

The coin picture from the introduction is close to what the hardware does. Inside the controller there is an 8-bit shift register, and inside the peripheral there is another. MOSI connects the output end of the controller's register to the input end of the peripheral's. MISO connects the output end of the peripheral's register back to the input end of the controller's. SCK drives both registers. The coin picture stops working in one respect: a real peripheral takes part only while its chip select is low, which the next section adds. The ATmega datasheet describes the process in these terms: master and slave each prepare the byte to send in their own shift register, and the master generates the clock pulses that interchange the data [2].

Two 8-bit shift registers joined in a ring by MOSI and MISO, with SCK clocking both, shown before and after eight clock pulses

On each clock pulse, one bit leaves each register and one bit enters it. After eight pulses the two bytes have swapped places. Three consequences follow, and the rest of the part depends on them.

First, SPI is full duplex, meaning data moves in both directions at once. Every transfer sends a byte and receives a byte at the same time. Arduino's SPI.transfer() documentation describes it as a simultaneous send and receive [6].

Second, a controller that only wants to read still has to send something, because only the clock pulses move the peripheral's bits out. Programmers send a dummy byte, often 0x00, and use the byte that comes back.

Third, the byte that comes back was already sitting in the peripheral's register before the transfer began. Most peripherals cannot work out an answer to a command in the same eight clock pulses that deliver it. A reply to a command therefore appears in a later byte, which is why the MCP3008 later in this part needs three bytes to return one measurement. Some peripherals, such as the 74HC595, never use MISO at all.

Chip Select and Framing

Chip select is what makes the bus shareable. Each peripheral has its own chip select line, which the controller holds high while the peripheral should stay out of the conversation and pulls low to start talking to it. A line that is active when low is called active low. A peripheral whose chip select is high ignores SCK and MOSI, and it releases MISO, which means its output is electrically disconnected (tri-stated) so that it neither drives the line high nor pulls it low, and another peripheral can drive it. The ATmega's own datasheet describes this behavior for an AVR running as a peripheral: with SS high it stays idle with MISO tri-stated, and when SS goes high it resets its bit counter and drops any partly received byte [2]. That reset is why chip select also works as a frame marker. Bytes sent while chip select stays low belong to one transaction, and raising it ends the transaction cleanly.

One controller sharing MOSI, MISO, and SCK with three peripherals, each with its own chip-select line from a separate Uno pin

The ATmega datasheet is explicit that a controller in master mode has no automatic control of the SS line, and software must handle chip select before communication can start [2]. The sketches in this part therefore drive each chip select with digitalWrite(). Arduino's documentation gives the pattern for most SPI devices: begin a transaction, write chip select low, call SPI.transfer() as many times as the device needs, write chip select high, and end the transaction [1].

This arrangement has two costs. Every peripheral needs its own Arduino pin for chip select, so a bus of six peripherals uses nine pins. And SPI has no addresses and no acknowledge bit. The I2C scanner in Part 12 could find devices because a missing device failed to acknowledge. SPI.transfer() returns a byte whether or not anything is connected, because it reads the shift register after eight clocks [7]. An SPI bus with a missing device looks like a working bus that returns nonsense.

Clock Polarity, Clock Phase, and the Four Modes

The clock has two properties that a peripheral can require. Clock polarity (CPOL) is the level the clock rests at while the bus is idle: CPOL 0 means it idles low, and CPOL 1 means it idles high. Clock phase (CPHA) is which clock edge captures the data bit. With CPHA 0 the data bit is captured on the first edge of each clock pulse, called the leading edge, and with CPHA 1 it is captured on the second, the trailing edge. Data changes on the opposite edge from the one that captures it, which gives the data time to settle before it is read [2].

Two settings with two values each make four combinations, numbered as SPI modes 0 to 3.

Mode CPOL CPHA Clock idles Data is captured on Data changes on Arduino constant
0 0 0 Low Rising edge Falling edge SPI_MODE0
1 0 1 Low Falling edge Rising edge SPI_MODE1
2 1 0 High Falling edge Rising edge SPI_MODE2
3 1 1 High Rising edge Falling edge SPI_MODE3

The ATmega datasheet gives this table as its Table 19-2 [2], and Arduino's guide lists the four modes too, as output edge and capture edge [1]. The constants are defined in SPI.h as 0x00, 0x04, 0x08, and 0x0C [7].

Four timing diagrams, one per SPI mode, each showing SCK, MOSI, and the edge where data is captured

A worked example shows what a mode means in practice. Take the byte 0xA5, which is 10100101 in binary, sent most significant bit first in mode 0. Before the first clock pulse, while chip select is low, the controller has already put bit 7, a 1, on MOSI. Each rising edge of SCK then captures the bit on the wire, and each falling edge makes MOSI switch to the next bit.

Rising edge number 1 2 3 4 5 6 7 8
Bit captured from MOSI 1 0 1 0 0 1 0 1

In mode 3 the clock idles high, and the first falling edge is the one that puts bit 7 on the line. The eight captures still happen on rising edges, so the peripheral sees the same byte. The difference between modes 0 and 3 is only the idle level of the clock and when the first bit appears. A peripheral that captures on rising edges but receives mode 1 signals reads MOSI at the very moment the controller is changing it, so each bit it reads may be the old value or the new one. The result is a byte that is shifted, garbled, or both, and that is why every datasheet states its mode. The MCP3008 used later states "modes 0,0 and 1,1" [3], which means CPOL and CPHA both 0 (mode 0) or both 1 (mode 3). The 74HC595 captures serial data on the rising edge of its shift clock [4], which also suits modes 0 and 3.

Speed and Bit Order

The Uno's ATmega328P runs at 16MHz [8]. The SPI clock is that frequency divided by a value the hardware offers in seven steps, set by the bits SPR1 and SPR0 and the double-speed bit SPI2X in the SPI registers. The datasheet's rates are fosc/4, /16, /64, and /128 with SPI2X clear, and fosc/2, /8, /32, and /64 with SPI2X set [2].

Divider SPI2X SPR1 SPR0 SCK at 16MHz Library constant
2 1 0 0 8MHz SPI_CLOCK_DIV2
4 0 0 0 4MHz SPI_CLOCK_DIV4
8 1 0 1 2MHz SPI_CLOCK_DIV8
16 0 0 1 1MHz SPI_CLOCK_DIV16
32 1 1 0 500kHz SPI_CLOCK_DIV32
64 0 1 0 250kHz SPI_CLOCK_DIV64
128 0 1 1 125kHz SPI_CLOCK_DIV128

The register values come from Table 19-5 of the datasheet [2]. One caution about the constants: SPI_CLOCK_DIV4 is a setting code that selects the divide-by-4 setting, and its value is 0x00 [7]. It is not a speed in hertz.

Most of the time a sketch does not choose a divider. It tells SPISettings the highest clock the peripheral allows, and the library picks the fastest divider that does not exceed it [7]. The MCP3008 allows up to 3.6MHz at a 5V supply [3]. A request for 3,600,000 on a 16MHz Uno does not match any divider exactly. The fastest step at or below 3.6MHz is 16MHz / 8, which is 2MHz, because 16MHz / 4 would be 4MHz and exceed the limit. The project in this part asks for 1,000,000, which gives exactly 1MHz, a round figure that is comfortably inside the limit.

The slow end matters for the MCP3008 too. Its datasheet warns that clocking too slowly lets the internal sample capacitor lose charge during the conversion, and it gives about 10kHz as the effective minimum [3]. Every divider in the table is far above that.

Clock speed also sets how long a transfer takes. One byte is eight clock pulses, so it takes 8 divided by the clock frequency: 8 / 1,000,000Hz is 8 microseconds at 1MHz, and 1 microsecond at 8MHz. The three-byte MCP3008 frame used later therefore needs at least 24 microseconds at 1MHz. The library adds a little time between bytes, so these are minimums.

Bit order is the other setting. Most SPI chips expect the most significant bit first, which Arduino calls MSBFIRST [1]. A few expect the least significant bit first (LSBFIRST), and the datasheet says which.

SPI Compared with UART and I2C

The table below puts the three buses from Parts 11, 12, and 13 side by side.

Feature UART (Part 11) I2C (Part 12) SPI (this part)
Signal wires 2 per link (TX and RX) 2, shared by every device 3 shared, plus 1 chip select per device
Clock None, both ends agree on a baud rate Shared clock line Shared clock line
Choosing a device One partner per port 7-bit address in each transaction A chip-select wire per device
Data direction Two wires, so both ways at once One data wire, so one way at a time Two data wires, so both ways at once
Speed in this series Up to 115,200 baud on a hobby board 100kHz or 400kHz Up to 8MHz on an Uno
Checks that a device is there No Yes, each address gets an acknowledge No

SPI is the right choice when speed matters or when the peripheral only offers SPI, as many converters, displays, and memories do. It costs wires, it needs one select pin per device, and it leaves the controller responsible for everything: the clock, every transaction, and every chip select. I2C is usually the better fit for a bus of slow sensors that must share two pins, and UART fits one direct conversation between two devices. SPI's costs are wiring and bookkeeping, and the next sections cover the pin numbers on other boards and one wiring pattern that saves chip-select pins.

SPI Pins on Other Boards

The pin numbers above belong to the Uno R3. Arduino's documentation lists the default pins for each board [6], and the common ones differ.

Board CIPO (MISO) COPI (MOSI) SCK CS (SS)
Uno R3 12 11 13 10
Nano boards 12 11 13 not listed
Mega 2560 Rev3 50 51 52 53
Micro 14 16 15 not listed

On the Uno and the Mega these signals are also on the six-pin ICSP header [6]. If a library or a shield is written for an Uno and a project moves to a Mega, the SPI wires have to move to pins 50, 51, and 52. The pin that the hardware calls SS is also different: pin 53 on the Mega, which matters in the section on the SS trap.

Daisy Chains and 3.3V Devices

Two more points complete the picture before the code. The first is the daisy chain, a wiring pattern that saves chip-select pins. Instead of giving each peripheral its own select line, the controller connects the output of the first peripheral to the input of the second, and all the peripherals share one chip select. A byte sent into the chain moves from device to device, so after a long enough transfer the first byte sent ends up in the last peripheral. The 74HC595 is built for this: it has a serial output pin, QH', whose purpose is cascading [4]. Two chained 595 chips take two bytes, and then one latch pulse updates all sixteen outputs.

The second point is voltage. Many SPI breakout boards run from 3.3V, and an Uno drives its signals at 5V. Part 12 covers level shifting for a similar reason on the I2C bus. The same check applies here: read the module's documentation before connecting it to Uno signals. Both parts in this article's project run from 5V.

The mechanism is now complete on paper: a clock, two data wires, and a select wire per peripheral, with one byte swapped each way for every eight pulses. What remains is how the Uno produces those pulses, starting with the slow way a sketch can do it by hand.

SPI on the Arduino

The Hard Way: One Byte by Hand

The simplest SPI controller is a loop that moves the clock pin by hand. Here is a function that sends one byte in mode 0, most significant bit first, using ordinary digitalWrite() calls. It uses the Uno's SPI pins, and the hardware SPI peripheral is not enabled, so the pins behave like any other.

const byte DATA_PIN = 11;   // The Uno's MOSI pin
const byte CLOCK_PIN = 13;  // The Uno's SCK pin

// Send one byte by hand: most significant bit first, clock idles low (SPI mode 0).
void sendByteByHand(byte value) {
  for (int bit = 7; bit >= 0; bit--) {            // Count from bit 7 down to bit 0
    digitalWrite(DATA_PIN, (value >> bit) & 1);   // Put the next bit on the data line while the clock is low
    digitalWrite(CLOCK_PIN, HIGH);                // Rising edge: the receiver captures the bit
    digitalWrite(CLOCK_PIN, LOW);                 // Falling edge: the clock returns to idle
  }
}

void setup() {
  pinMode(DATA_PIN, OUTPUT);    // The data line is an output
  pinMode(CLOCK_PIN, OUTPUT);   // The clock line is an output
  digitalWrite(CLOCK_PIN, LOW); // Mode 0 idles low
}

void loop() {
  sendByteByHand(0xA5);         // Send the example byte from the mode 0 table
  delay(1000);                  // Wait one second, then send it again
}

This works, and it is slow. Each digitalWrite() call takes many CPU cycles, so the clock speed is far below what the SPI hardware reaches, and the processor does nothing else while it runs. It also reads nothing back. Exercise 3 uses this function to light LEDs through a 74HC595.

The ATmega's SPI Registers

The ATmega328P has a hardware SPI controller that does the bit shifting. Three registers control it. The SPI Control Register (SPCR) holds the settings. The SPI Status Register (SPSR) holds flags. The SPI Data Register (SPDR) holds the byte to send and, after a transfer, the byte received.

SPCR bit Name Meaning when set to 1
7 SPIE Enable the SPI interrupt
6 SPE Enable SPI
5 DORD Send least significant bit first (0 means most significant bit first)
4 MSTR Controller (master) mode
3 CPOL Clock idles high
2 CPHA Capture on the second clock edge
1 SPR1 Clock rate select, high bit
0 SPR0 Clock rate select, low bit

These are the bit names in the datasheet's SPCR description [2]. Setting SPE and MSTR turns the controller on. The datasheet's own master example is a single line, SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0), which gives fosc/16 [2]. A transfer is then two steps: write the byte to SPDR, which starts the clock generator and shifts eight bits, and wait until the SPIF flag in SPSR shows that the byte is finished [2]. The byte received is in SPDR.

void setup() {
  Serial.begin(115200);                    // Report the result over USB
  pinMode(10, OUTPUT);                     // SS as an output (the section on the SS trap explains why)
  pinMode(11, OUTPUT);                     // MOSI is an output
  pinMode(13, OUTPUT);                     // SCK is an output
  SPCR = _BV(SPE) | _BV(MSTR) | _BV(SPR0); // SPI on, controller mode, mode 0, fosc/16 = 1MHz
}

// The whole of SPI.transfer(), written out: start the clock, wait, read the reply.
byte transferByHand(byte value) {
  SPDR = value;                            // Writing SPDR starts the eight clock pulses
  while (!(SPSR & _BV(SPIF))) {            // SPIF becomes 1 when the byte is finished
  }
  return SPDR;                             // The byte that arrived on MISO during the transfer
}

void loop() {
  byte reply = transferByHand(0xA5);       // Nothing is connected, so the reply is whatever MISO reads
  Serial.println(reply, HEX);              // Print the reply in hexadecimal
  delay(1000);                             // Repeat once a second
}

The function in that sketch has the logic of the library's transfer(): write SPDR, wait for SPIF, return SPDR [7]. Nothing in it chooses a chip select, and nothing in it protects a bus shared with other code. That is the job the library takes on.

The SPI Library

SPI.h is part of every Arduino core, so it is already installed [1]. Four calls cover most uses.

SPI.begin() prepares the controller. It makes pin 10 (the SS pin) an output, sets the MSTR and SPE bits, and makes SCK and MOSI outputs [7].

SPISettings(maxClock, bitOrder, dataMode) packages the three settings a device datasheet gives: the highest clock the device allows in hertz, MSBFIRST or LSBFIRST, and one of SPI_MODE0 to SPI_MODE3 [6]. With no arguments, the default is 4MHz, MSBFIRST, and SPI_MODE0 [7].

SPI.beginTransaction(settings) applies the settings and takes the bus. SPI.endTransaction() releases it [6]. Settings belong to a transaction because different devices on one bus can need different settings, and the transaction call switches between them.

SPI.transfer(byte) sends one byte and returns the byte received. A second form, SPI.transfer(buffer, size), transfers a whole array and replaces the array contents with the bytes received [6].

Here is the pattern from the Arduino guide, written for a device on chip-select pin 10:

#include <SPI.h>                          // The SPI library is part of every Arduino core

const byte CS_PIN = 10;                   // Chip select for the device on the bus

void setup() {
  Serial.begin(115200);                   // Report the result over USB
  pinMode(CS_PIN, OUTPUT);                // Chip select is an output
  digitalWrite(CS_PIN, HIGH);             // High means "not selected", the idle state
  SPI.begin();                            // Start the SPI controller
}

void loop() {
  SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE0)); // At most 1MHz, mode 0
  digitalWrite(CS_PIN, LOW);              // Select the device: the frame starts
  byte reply = SPI.transfer(0x42);        // Send one command byte (0x42 is an arbitrary example)
  digitalWrite(CS_PIN, HIGH);             // Deselect the device: the frame ends
  SPI.endTransaction();                   // Release the bus
  Serial.println(reply, HEX);             // Print the byte that came back
  delay(1000);                            // Repeat once a second
}

The older calls setBitOrder(), setDataMode(), and setClockDivider() are deprecated, and Arduino says to use SPISettings with beginTransaction() instead [6]. Older tutorials still use them. They work on the Uno, but they set one option at a time and give no protection when two libraries share the bus.

What the Library Does Not Do

SPI.h keeps the code short, and a few limits come with it. The library header describes itself as an SPI master library [7], so an Uno running this library is always the controller, and the Uno acting as a peripheral needs the registers or a different library. SPI.transfer() waits in a loop until the transfer is done [7], so the sketch cannot do anything else during those microseconds. The library does not touch chip select at all. Every digitalWrite() on a CS pin is the sketch's job, and forgetting the one that raises a CS pin leaves a peripheral selected when another one is addressed.

The library also does not tell you whether a device answered, as the section on chip select explained. And if an interrupt service routine uses the SPI bus while the main sketch is in the middle of a transaction, the two will collide. For that reason the library has SPI.usingInterrupt(), which registers the interrupt so that beginTransaction() can hold it off until the transaction ends [7]. This series has not used SPI inside interrupts so far, and this part does not either. If a later library uses SPI from an interrupt, read its documentation before adding another SPI device.

The SS Pin Gotcha

So far, SPI is a clock, two data wires, and a select wire per peripheral. Each transfer swaps one byte in each direction, a peripheral listens only while its chip select is low, and its datasheet fixes the mode, the speed, and the bit order. The hand-written function and the SPI registers showed what the hardware does, and the library packages those steps behind SPISettings and a transaction. What the library cannot remove is a property of the AVR itself, because the chip watches its own SS pin even when the sketch never mentions it.

The SS pin is PB2 on the ATmega328P, which the Uno brings out as D10. The datasheet's rule for a controller depends on the direction of that pin. If SS is configured as an output, it is a general output pin that does not affect the SPI system. If SS is configured as an input, it must be held high to keep master operation. If something pulls an input SS low while the AVR is a controller, "the SPI system interprets this as another master selecting the SPI as a slave" [2].

The hardware then protects the bus from two controllers driving it. It clears the MSTR bit, so the AVR becomes a peripheral, MOSI and SCK become inputs, and the SPIF flag is set. The controller mode does not come back by itself: the sketch has to set MSTR again [2]. In practice a sketch that worked a moment ago stops clocking the bus, and nothing in the sketch's own code looks wrong.

Arduino's SPI.begin() removes the trap on an Uno by making the SS pin an output [7]. The comment in the library source says why: if the SS pin ever becomes a low input, SPI switches to slave mode automatically, so the pin's direction must be kept as output [7]. That has two consequences. D10 is safe to use as a general output pin once SPI.begin() has run, and it can serve as a chip select, as it does in this part's project. And the trap is still there for any sketch that sets SPCR itself, or that changes D10 into an input after starting SPI. Exercise 2 triggers it on purpose with a jumper wire, so the symptom is familiar when it appears by accident.

The Two Devices in This Part

MCP3008: an Analog-to-Digital Converter on SPI

The MCP3008 is a 10-bit analog-to-digital converter with eight input channels and an SPI interface [3]. The Uno's own analog inputs from Part 10 work through an internal converter. This chip adds a second one on the bus, which is handy for extra channels and a separate reference. It supports SPI modes 0,0 and 1,1, runs from 2.7V to 5.5V, and clocks at up to 3.6MHz at 5V [3]. It comes in a 16-pin DIP (the through-hole package) that fits a breadboard.

MCP3008 pin Name Connects to
1 to 8 CH0 to CH7 Analog inputs. The project uses CH0
9 DGND GND
10 CS/SHDN Chip select, active low
11 DIN MOSI (data from the Uno)
12 DOUT MISO (data to the Uno)
13 CLK SCK
14 AGND GND
15 VREF 5V, the reference
16 VDD 5V

The pin names and numbers are from the datasheet [3]. VREF sets the input range. The converter's output code is 1024 × VIN / VREF, and one step of the code is VREF / 1024 [3]. With VREF at 5V, a step is 5V / 1,024, about 4.88mV. A code of 512 therefore means 512 × 5V / 1,024 = 2.5V.

A conversation with the MCP3008 starts when chip select goes low. The first clock with DIN high is a start bit, followed by a bit that selects single-ended or differential input and three channel bits, D2, D1, and D0. After a short sample time the chip sends a null bit, then the ten result bits, most significant first [3]. Those are 17 clock pulses, and an Uno sends bytes of eight. The datasheet's solution is to start with leading zeros so that the result falls neatly into the second and third bytes [3].

The MCP3008 three-byte transaction: the byte sent on DIN, the byte received on DOUT, and where the start bit, channel bits, null bit, and ten result bits fall

The first byte sent is 0x01: seven zeros and then the start bit. The second byte is the single-ended bit (1), then D2, D1, and D0 for the channel, then four bits that the chip ignores. For channel 0 that is 0x80, and in general it is 0x80 | (channel << 4). The third byte is a dummy 0x00 that only produces clock pulses. The reply arrives in the second and third bytes: the low two bits of the second byte are result bits 9 and 8, and the whole third byte is result bits 7 to 0 [3]. The result is therefore ((second byte & 0x03) << 8) | third byte. The chip drives MISO only while chip select is low, and it releases the line afterward [3], which is what lets a second peripheral share MISO.

The MCP3008 wants a low-impedance signal source. A larger source impedance adds error to the reading [3]. A 10kΩ potentiometer presents up to 2.5kΩ at its wiper, at the midpoint where the two halves of the track act in parallel. That is good enough for a bar graph, and it is not how a precision measurement should be set up.

74HC595: a Shift Register that Listens to SPI

The 74HC595 is an 8-bit shift register with a storage register behind it [4]. Serial data enters on the SER pin, one bit per pulse of the shift clock SRCLK. A second clock, RCLK, copies the whole shift register into the storage register, and the storage register drives the eight outputs QA to QH. Both clocks act on a rising edge [4]. The new bit enters the first stage, which is QA, and every other stage takes the value of the stage before it [4]. After eight pulses the first bit sent has reached QH.

74HC595 pin Name Connects to
15 QA LED 1 (through a resistor)
1 to 7 QB to QH LEDs 2 to 8 (through resistors)
8 GND GND
9 QH' Not used here; serial output for a second chip
10 SRCLR 5V (active low, so high leaves it inactive)
11 SRCLK SCK
12 RCLK Latch, from an Uno pin (D9)
13 OE GND (active low, so low enables the outputs)
14 SER MOSI
16 VCC 5V

The pin names and numbers are from the datasheet [4]. SPI compatibility is partial. The 595 takes SPI's clock and data, so SPI.transfer() drives it. It has no chip-select pin and never answers on MISO. Its RCLK pin is a latch, not a chip select: it copies the shift register to the outputs and does not gate the data. The shift register moves on every SRCLK pulse, whether or not the controller meant those pulses for it. On a shared bus that matters. Every byte the Uno sends to the MCP3008 also shifts into the 595's shift register. The LEDs do not change when that happens, because the outputs only change on RCLK, and the project latches only after sending a full fresh byte to the 595. The sketch must therefore always send a whole byte before every latch pulse. Skipping that step would show garbage from the other device's frames.

LED current comes from the outputs. The datasheet rates the part for a 6mA output drive at 5V and says load currents should not exceed 35mA per output and 70mA for the whole part [4]. A red LED drops about 2V. That is a typical value, chosen here for tidy arithmetic, and the exact figure is on an LED's own datasheet. With a 1kΩ resistor at 5V, the current is (5V − 2V) / 1,000Ω = 3mA per LED, so eight LEDs draw 24mA. A 330Ω resistor would give about 9mA per LED, above the 6mA rating, so the project uses 1kΩ. The 3mA figure is an upper estimate, because the output pin drops a little below the supply when it carries current.

Settings at a Glance

Reading an SPI datasheet comes down to five questions: which mode, which bit order, how fast, how chip select works, and whether anything comes back on MISO. The table answers them for the three devices this part uses, with the datasheet each answer comes from.

Question MCP3008 [3] 74HC595 [4] SSD1306 (the Lab) [9]
Which mode? 0,0 or 1,1 (modes 0 and 3) Captures on the rising edge of SRCLK (modes 0 and 3) Captures on the rising edge of the clock (modes 0 and 3)
Bit order? Most significant bit first Set by wiring: the first bit sent ends up at QH D7 first
Fastest clock? 3.6MHz at 5V 25MHz at 4.5V Not checked in this part
Chip select? CS/SHDN, active low None. RCLK latches the outputs CS#, active low, plus D/C#
Reply on MISO? Yes, in the second and third bytes None used (QH' only for chaining) None, write only

The same Uno handles all three by passing a different SPISettings value to beginTransaction(). A datasheet that lists a mode, a bit order, and a speed limit is describing exactly the three arguments of SPISettings, which is why that call takes them.

Planning the Build

Item Value
Board Uno R3, powered from USB (5V)
Pins used D9 (latch), D10 (MCP3008 chip select), D11 (MOSI), D12 (MISO), D13 (SCK)
Analog input One 10kΩ potentiometer on MCP3008 CH0
LED resistors Eight 1kΩ
SPI settings MCP3008: 1MHz, MSBFIRST, SPI_MODE0. 74HC595: 4MHz, MSBFIRST, SPI_MODE0

The wiring is below. Both chips straddle the center gap of the breadboard, with the notch of each at the top. Pin 1 is then at the top left, the pins count down the left side, and the count continues up the right side.

From To Why
Uno D11 MCP3008 pin 11 (DIN) and 74HC595 pin 14 (SER) MOSI, shared by both chips
Uno D12 MCP3008 pin 12 (DOUT) MISO, driven only by the MCP3008
Uno D13 MCP3008 pin 13 (CLK) and 74HC595 pin 11 (SRCLK) SCK, shared by both chips
Uno D10 MCP3008 pin 10 (CS/SHDN) MCP3008 chip select
Uno D9 74HC595 pin 12 (RCLK) Latch for the LED outputs
Uno 5V MCP3008 pins 15 and 16; 74HC595 pins 10 and 16; one end of the potentiometer Power, reference, and the other control inputs held inactive
Uno GND MCP3008 pins 9 and 14; 74HC595 pins 8 and 13; the other end of the potentiometer; every LED cathode Common ground and enabled outputs
Potentiometer wiper MCP3008 pin 1 (CH0) The voltage to measure
74HC595 pins 15, 1, 2, 3, 4, 5, 6, 7 A 1kΩ resistor, then the anode of LED 1 to 8 QA to QH drive the LEDs

Project schematic: Uno SPI pins to the MCP3008 and the 74HC595, the potentiometer on CH0, and eight LEDs with 1kΩ resistors

Build in stages so that a fault has only one place to hide. First wire the 74HC595 and the eight LEDs, and run Exercise 3. Then add the MCP3008 and the potentiometer, and run Exercise 4. When both pass, run the project sketch.

Exercises

Exercise 1: Read the Settings Back

Goal: see which register values SPISettings produces for three different requests. This needs only the Uno.

#include <SPI.h>                                // Load the SPI library

// Apply one set of settings, then print the SPI Control Register and the double-speed bit.
void printSettings(const char *label, SPISettings settings) {
  SPI.beginTransaction(settings);               // This writes the settings into SPCR and SPSR
  Serial.print(label);                          // Say which request this line is about
  Serial.print(": SPCR = 0x");                  // SPCR holds the mode, bit order, and rate bits
  Serial.print(SPCR, HEX);                      // Print the register in hexadecimal
  Serial.print(", SPI2X = ");                   // SPI2X is the double-speed bit in SPSR
  Serial.println((SPSR & _BV(SPI2X)) ? 1 : 0);  // Print 1 if double speed is on, otherwise 0
  SPI.endTransaction();                         // Release the bus again
}

void setup() {
  Serial.begin(115200);                         // Report over USB
  SPI.begin();                                  // Start SPI so the settings take effect
  printSettings("1MHz, MSB first, mode 0", SPISettings(1000000, MSBFIRST, SPI_MODE0));
  printSettings("8MHz, MSB first, mode 0", SPISettings(8000000, MSBFIRST, SPI_MODE0));
  printSettings("3MHz, LSB first, mode 3", SPISettings(3000000, LSBFIRST, SPI_MODE3));
}

void loop() {
  // Nothing to repeat: the three lines print once.
}

Expected output, worked out from the SPISettings source and the SPCR bit table:

1MHz, MSB first, mode 0: SPCR = 0x51, SPI2X = 0
8MHz, MSB first, mode 0: SPCR = 0x50, SPI2X = 1
3MHz, LSB first, mode 3: SPCR = 0x7D, SPI2X = 1

The first line is SPE (0x40), MSTR (0x10), and SPR0 (0x01): fosc/16 is 1MHz. The second is SPE and MSTR with SPR bits clear and SPI2X set: fosc/2 is 8MHz. The third adds DORD (0x20) for least significant bit first, CPOL and CPHA (0x0C) for mode 3, and SPR0 with SPI2X set for fosc/8. The 3MHz request ran at 2MHz because no divider gives exactly 3MHz, and the library picks the fastest one that does not go over. If your numbers differ, check that the board is an Uno R3 or a classic Nano at 16MHz. Other boards have other clock speeds and, as the pin table showed, other SPI hardware.

Exercise 2: Trigger the SS Gotcha

Goal: watch the MSTR bit clear when the SS pin is pulled low. This needs the Uno and one jumper wire.

void setup() {
  Serial.begin(115200);                       // Report over USB
  pinMode(10, INPUT_PULLUP);                  // SS as an input, held HIGH by the internal pull-up resistor
  pinMode(11, OUTPUT);                        // MOSI is an output
  pinMode(13, OUTPUT);                        // SCK is an output
  SPCR = _BV(SPE) | _BV(MSTR);                // SPI on, controller mode. Written directly, not with SPI.begin()
}

void loop() {
  Serial.print("MSTR = ");                    // MSTR is bit 4 of SPCR
  Serial.println((SPCR & _BV(MSTR)) ? 1 : 0); // 1 means controller, 0 means the AVR has become a peripheral
  delay(500);                                 // Print twice a second
}

Expected output: MSTR = 1 on every line. Touch a jumper wire from D10 to GND, and the printed value changes to MSTR = 0. Remove the wire, and it stays at MSTR = 0, because the hardware does not return to controller mode by itself, and the datasheet says software has to set MSTR again [2]. Pressing the Uno's reset button restarts the sketch and sets MSTR in setup(). To prove the fix, change pinMode(10, INPUT_PULLUP) to pinMode(10, OUTPUT) and repeat the test: with D10 an output, grounding it no longer changes MSTR. Do not do the grounding step with a chip connected to D10.

If MSTR never changes: check that the jumper is in the D10 socket and not D11 or D9, and that its other end is in a GND socket.

Exercise 3: Send One Byte to the 74HC595, Two Ways

Goal: light the same LED pattern by hand and with the library. This needs the 74HC595 and the eight LEDs from the build (stage 1).

Upload the hand-written version first. It reuses the function from the hard-way section and adds the latch.

const byte DATA_PIN = 11;    // 74HC595 pin 14 (SER), the Uno's MOSI pin
const byte CLOCK_PIN = 13;   // 74HC595 pin 11 (SRCLK), the Uno's SCK pin
const byte LATCH_PIN = 9;    // 74HC595 pin 12 (RCLK)

// Send one byte by hand: most significant bit first, clock idles low (SPI mode 0).
void sendByteByHand(byte value) {
  for (int bit = 7; bit >= 0; bit--) {            // Count from bit 7 down to bit 0
    digitalWrite(DATA_PIN, (value >> bit) & 1);   // Put the next bit on the data line
    digitalWrite(CLOCK_PIN, HIGH);                // Rising edge: the 595 captures the bit
    digitalWrite(CLOCK_PIN, LOW);                 // Falling edge: back to idle
  }
}

void setup() {
  pinMode(DATA_PIN, OUTPUT);     // Data is an output
  pinMode(CLOCK_PIN, OUTPUT);    // Clock is an output
  pinMode(LATCH_PIN, OUTPUT);    // Latch is an output
  digitalWrite(CLOCK_PIN, LOW);  // Mode 0 idles low
  digitalWrite(LATCH_PIN, LOW);  // The latch idles low and is pulsed high to update the outputs
  sendByteByHand(0xA5);          // Shift 10100101 into the shift register
  digitalWrite(LATCH_PIN, HIGH); // Rising edge copies the shift register to the outputs
  digitalWrite(LATCH_PIN, LOW);  // Return the latch to idle
}

void loop() {
  // The pattern stays on the outputs until the next latch.
}

Expected result: LEDs 1, 3, 6, and 8 are lit. The first bit sent, a 1, travels all the way to QH, which is LED 8. The last bit sent, bit 0, stays in QA, which is LED 1. Reading 0xA5 as 10100101, bit 0 is 1 (LED 1), bit 2 is 1 (LED 3), bit 5 is 1 (LED 6), and bit 7 is 1 (LED 8).

Now the library version, which lights the same pattern with SPI.transfer():

#include <SPI.h>                 // Load the SPI library

const byte LATCH_PIN = 9;        // 74HC595 pin 12 (RCLK)

void setup() {
  pinMode(LATCH_PIN, OUTPUT);    // Latch is an output
  digitalWrite(LATCH_PIN, LOW);  // The latch idles low
  SPI.begin();                   // Start the SPI controller (MOSI is D11, SCK is D13)
  SPI.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE0)); // The 595 accepts up to 25MHz at 5V
  SPI.transfer(0xA5);            // The hardware shifts the same eight bits in far less time
  SPI.endTransaction();          // Release the bus
  digitalWrite(LATCH_PIN, HIGH); // Rising edge copies the shift register to the outputs
  digitalWrite(LATCH_PIN, LOW);  // Return the latch to idle
}

void loop() {
  // The pattern stays on the outputs until the next latch.
}

Expected result: the same four LEDs. If the LEDs show a different pattern, the data line is probably on the wrong 595 pin, or the order of the LED wires is reversed (QA is pin 15, and QB to QH are pins 1 to 7). If nothing lights, check pin 13 (OE) is on GND and pin 10 (SRCLR) is on 5V. If the pattern appears one step late, the latch is firing before the byte is complete.

Exercise 4: Read One MCP3008 Channel

Goal: read the potentiometer through the three-byte frame and print the raw code and the voltage. This needs the MCP3008 and the potentiometer from the build (stage 2).

#include <SPI.h>                          // Load the SPI library

const byte MCP_CS_PIN = 10;               // MCP3008 pin 10 (CS/SHDN), also the Uno's SS pin

// Read one single-ended channel (0 to 7) as a number from 0 to 1023.
int readMcp3008(byte channel) {
  byte frame[3];                          // Three bytes go out and three bytes come back
  frame[0] = 0x01;                        // Seven zeros, then the start bit
  frame[1] = 0x80 | (channel << 4);       // Single-ended bit, then D2 D1 D0, then four ignored bits
  frame[2] = 0x00;                        // A dummy byte that only produces clock pulses

  SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE0)); // 1MHz, well under the 3.6MHz limit
  digitalWrite(MCP_CS_PIN, LOW);          // Select the MCP3008: the frame starts
  SPI.transfer(frame, 3);                 // Send three bytes; the reply replaces them in frame[]
  digitalWrite(MCP_CS_PIN, HIGH);         // Deselect the MCP3008: the frame ends
  SPI.endTransaction();                   // Release the bus

  return ((frame[1] & 0x03) << 8) | frame[2]; // Result bits 9 and 8, then result bits 7 to 0
}

void setup() {
  Serial.begin(115200);                   // Report over USB
  pinMode(MCP_CS_PIN, OUTPUT);            // Chip select is an output
  digitalWrite(MCP_CS_PIN, HIGH);         // High means "not selected"
  SPI.begin();                            // Start the SPI controller
}

void loop() {
  int raw = readMcp3008(0);               // Read channel 0, where the potentiometer wiper is
  float volts = raw * 5.0 / 1024.0;       // One step is 5V / 1,024 when VREF is 5V
  Serial.print("raw = ");                 // Label the raw code
  Serial.print(raw);                      // The code from 0 to 1023
  Serial.print(", volts = ");             // Label the voltage
  Serial.println(volts, 2);               // The voltage to two decimal places
  delay(500);                             // Read twice a second
}

Expected output: with the knob at the GND end, raw = 0, volts = 0.00. At the 5V end, a raw value of about 1023 and volts = 4.99. At the middle, a raw value near 512 and volts near 2.50. The values are only as accurate as the 5V on the VREF pin, which is the Uno's USB supply and can sit a little above or below 5.00V, as Part 10 showed.

If the raw value is stuck at 0, 1023, or jumps randomly while the knob is still, no reply is reaching the Uno. Check DOUT on pin 12 goes to D12, CS on pin 10 goes to D10, VREF on pin 15 and VDD on pin 16 are both on 5V, and both ground pins (9 and 14) are on GND. If the reading changes with the knob but is off by a fixed amount, check the first byte is 0x01 and the second is 0x80 for channel 0.

SPI in the Electronics Lab

The exercises above use a bare Uno and real parts. The Makers Workbench Electronics Lab is a simulator that runs in the browser: an Uno R3, wired parts, the sketch, and a Serial monitor, with nothing to install and nothing to wire. This part has two Labs. The first shows one SPI transaction reaching a display. The second, in the Practical Project section, runs the whole knob-to-LED-bar project. In both, press Run, open the Serial monitor to read what the sketch prints, and watch the circuit respond.

Try SPI Frames in the Lab

This Lab uses the SPI library on its own, with none of the project's chips, to send two chip-select frames to a display. Use it to see how chip select, a transaction, and SPI.transfer() fit together before you build the project.

This first Lab uses an SSD1306 OLED display wired for SPI instead of the project's chips, because a display is the simplest SPI peripheral to watch. It is a write-only peripheral: it uses the same clock, data, and chip-select signals as the project's chips, and it never sends anything back. The SSD1306 datasheet says only write operations are allowed in serial mode [9], so its MISO wire does not exist and the Uno ignores the byte that every transfer returns. That shows the full-duplex point from earlier in this part from the other side: the hardware still receives a byte for every byte it sends, and the sketch throws it away. The project has its own Lab later in this part.

The display adds one signal the project does not have. D/C is a data/command line that tells the chip whether the next byte configures it (a command) or draws something (a pixel). The display captures data on the rising edge of the clock [9], which suits SPI mode 0, the mode used throughout this part.

The sketch sends two chip-select frames and reports each one over Serial. Frame 1 is eleven command bytes that switch the display on and set its address range. Frame 2 is 1,024 pixel bytes, one for each of 128 columns in 8 pages of 8 pixel rows [9]. Each frame follows the pattern from the SPI library section: begin a transaction, take chip select low, transfer the bytes, take chip select high. Read the code first. The comments mark which lines are SPI and which only set up the display.

#include <SPI.h>                   // Load the SPI library

const byte OLED_CS = 10;           // Chip select, active low
const byte OLED_DC = 9;            // Data/command select: LOW means command byte, HIGH means pixel byte
const byte OLED_RES = 8;           // Reset, active low

// Setup commands, each one defined in the SSD1306 datasheet.
const byte initCommands[] = {
  0x8D, 0x14,                      // Charge pump setting: enable the charge pump
  0x20, 0x00,                      // Memory addressing mode: horizontal
  0x21, 0x00, 0x7F,                // Column address range: 0 to 127
  0x22, 0x00, 0x07,                // Page address range: 0 to 7
  0xAF                             // Display on
};

void setup() {
  Serial.begin(115200);            // Report each frame over USB
  pinMode(OLED_CS, OUTPUT);        // Chip select is an output
  pinMode(OLED_DC, OUTPUT);        // Data/command select is an output
  pinMode(OLED_RES, OUTPUT);       // Reset is an output
  digitalWrite(OLED_CS, HIGH);     // Start deselected
  SPI.begin();                     // Start the SPI controller (MOSI is D11, SCK is D13)

  digitalWrite(OLED_RES, LOW);     // Hold the display in reset
  delay(10);                       // Wait 10 milliseconds
  digitalWrite(OLED_RES, HIGH);    // Release the reset
  delay(10);                       // Give the display time to start

  SPI.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE0)); // The display captures on the rising edge

  digitalWrite(OLED_DC, LOW);      // The next bytes are commands
  digitalWrite(OLED_CS, LOW);      // Frame 1 starts
  for (byte i = 0; i < sizeof(initCommands); i++) {
    SPI.transfer(initCommands[i]); // Send one command byte
  }
  digitalWrite(OLED_CS, HIGH);     // Frame 1 ends
  Serial.print("Frame 1: ");       // Report how many command bytes went out
  Serial.print(sizeof(initCommands));
  Serial.println(" command bytes");

  digitalWrite(OLED_DC, HIGH);     // The next bytes are pixel data
  digitalWrite(OLED_CS, LOW);      // Frame 2 starts
  for (byte page = 0; page < 8; page++) {          // The display has 8 pages of 8 pixel rows
    for (byte column = 0; column < 128; column++) { // Each page has 128 columns
      byte pixels = (column / 16 >= page) ? 0xFF : 0x00; // A staircase: one more step per page
      SPI.transfer(pixels);        // Send one column of 8 pixels
    }
  }
  digitalWrite(OLED_CS, HIGH);     // Frame 2 ends
  Serial.println("Frame 2: 1024 pixel bytes");

  SPI.endTransaction();            // Release the bus
}

void loop() {
  // The picture stays on the display. Nothing to repeat.
}

The Lab circuit is wired like this:

From To Why
OLED CLK Uno D13 SCK, the SPI clock
OLED DATA Uno D11 MOSI, data from the Uno
OLED CS Uno D10 Chip select, active low
OLED DC Uno D9 Selects command bytes (low) or pixel bytes (high)
OLED RST Uno D8 Reset, active low
OLED VIN Uno 5V Power
OLED GND Uno GND Common reference

To use the Lab:

  1. Press the green Run button. The first run compiles the sketch, so give it a few seconds.
  2. Open the Serial monitor above the circuit. It reads the same 115200 baud the sketch uses.
  3. Watch for Frame 1: 11 command bytes and Frame 2: 1024 pixel bytes.
  4. Look at the display. It shows a white stepped triangle: one more column group goes dark with each row, in steps of 16 columns. In the Lab the triangle is tallest at the left edge. A real module can show it mirrored, because the SSD1306 has a command that reverses its column order and modules are wired both ways.

Every byte of that picture went through one call, SPI.transfer(), inside one chip-select frame. The Lab shows the controller side of SPI only. It does not show the clock and data waveforms, because the simulator moves the bytes without toggling the pins, and it does not model the SS pin trap described earlier in this part.

Practical Project: Knob to LED Bar

What you will build

A potentiometer sets a voltage. The Uno reads it through the MCP3008, converts it into a level from 0 to 8, and sends a matching bar pattern to the 74HC595, which lights that many of eight LEDs. Both chips share MOSI and SCK, and each chip gets its own settings in its own transaction. The sketch prints the raw code and the level over USB so the numbers are visible.

Components needed

  • Arduino Uno R3 and a USB cable
  • MCP3008 (16-pin DIP)
  • 74HC595 (16-pin DIP)
  • One 10kΩ potentiometer
  • Eight LEDs and eight 1kΩ resistors
  • A breadboard and jumper wires

Wiring

Use the wiring table from Planning the Build. Both chips share D11 (MOSI) and D13 (SCK). Chip select for the MCP3008 is D10, the latch for the 74HC595 is D9, and only the MCP3008 is wired to D12 (MISO).

The sketch

#include <SPI.h>                          // Load the SPI library

const byte MCP_CS_PIN = 10;               // MCP3008 chip select (also the Uno's SS pin)
const byte LATCH_PIN = 9;                 // 74HC595 latch (RCLK)
const byte KNOB_CHANNEL = 0;              // The potentiometer is on MCP3008 channel 0

// Read one single-ended channel (0 to 7) as a number from 0 to 1023.
int readMcp3008(byte channel) {
  byte frame[3];                          // Three bytes go out and three come back
  frame[0] = 0x01;                        // Seven zeros, then the start bit
  frame[1] = 0x80 | (channel << 4);       // Single-ended bit, channel bits, four ignored bits
  frame[2] = 0x00;                        // Dummy byte that only produces clock pulses

  SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE0)); // MCP3008 settings: 1MHz, mode 0
  digitalWrite(MCP_CS_PIN, LOW);          // Select the MCP3008
  SPI.transfer(frame, 3);                 // Send the request, receive the reply in place
  digitalWrite(MCP_CS_PIN, HIGH);         // Deselect the MCP3008
  SPI.endTransaction();                   // Release the bus

  return ((frame[1] & 0x03) << 8) | frame[2]; // Combine result bits 9 and 8 with bits 7 to 0
}

// Show a pattern on the eight LEDs: bit 0 is LED 1 (QA) and bit 7 is LED 8 (QH).
void showPattern(byte pattern) {
  SPI.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE0)); // 74HC595 settings: 4MHz, mode 0
  SPI.transfer(pattern);                  // Shift a full byte in, replacing anything left from other traffic
  SPI.endTransaction();                   // Release the bus
  digitalWrite(LATCH_PIN, HIGH);          // Rising edge copies the shift register to the outputs
  digitalWrite(LATCH_PIN, LOW);           // Return the latch to idle
}

void setup() {
  Serial.begin(115200);                   // Report over USB
  pinMode(MCP_CS_PIN, OUTPUT);            // MCP3008 chip select is an output
  digitalWrite(MCP_CS_PIN, HIGH);         // Idle: not selected
  pinMode(LATCH_PIN, OUTPUT);             // The latch is an output
  digitalWrite(LATCH_PIN, LOW);           // The latch idles low
  SPI.begin();                            // Start the SPI controller
  showPattern(0);                         // Clear the LEDs so power-up leftovers never show
}

void loop() {
  int raw = readMcp3008(KNOB_CHANNEL);    // Read the knob: 0 to 1023
  byte level = (raw * 9L) / 1024;         // Scale to 0 to 8 lit LEDs, using long math to avoid overflow
  byte pattern = (1 << level) - 1;        // Make "level" ones starting at bit 0
  showPattern(pattern);                   // Send the pattern to the LEDs
  Serial.print("raw = ");                 // Label the raw code
  Serial.print(raw);                      // The MCP3008 reading
  Serial.print(", level = ");             // Label the level
  Serial.println(level);                  // The number of lit LEDs
  delay(100);                             // About ten updates a second
}

What is happening

Each pass of loop() makes two SPI transactions on the same wires. The first selects the MCP3008, sends the three-byte request, and returns the knob reading. The second sends one byte to the 74HC595 and pulses its latch. The two transactions use different settings, because beginTransaction() applies the settings the next device needs. The 74HC595 shifts on every clock pulse, including the pulses meant for the MCP3008, and that is harmless because the outputs change only on the latch, and the byte sent right before each latch replaces everything the shift register had collected.

The scaling line turns 0 to 1023 into 0 to 8. The expression (raw × 9) / 1,024 uses integer division, so it is 0 for the lowest readings and reaches 8 only at the top. The pattern line then builds that many ones: a level of 3 gives (1 << 3) − 1 = 7, which is 00000111 in binary, so LEDs 1 to 3 light.

The done test

The project is done when these three checks pass:

  1. With the knob at the GND end, no LED is lit, and Serial shows raw = 0, level = 0.
  2. With the knob at the 5V end, all eight LEDs are lit, and Serial shows raw near 1023 and level = 8.
  3. As the knob turns up from GND, the LEDs light one at a time, in order from LED 1.

The integer arithmetic fixes where each LED turns on. LED n lights at the smallest raw value that makes (raw × 9) / 1,024 reach n. The thresholds below are calculated, so a real knob can differ by a few counts, which is the noise Part 10 covered.

LED lit Raw value at which it turns on Input voltage at that point (raw × 5V / 1,024)
1 114 0.56V
2 228 1.11V
3 342 1.67V
4 456 2.23V
5 569 2.78V
6 683 3.34V
7 797 3.89V
8 911 4.45V

Build and test sequence

  1. Wire only the 74HC595 and the LEDs. Upload Exercise 3 and confirm LEDs 1, 3, 6, and 8 light.
  2. Add the MCP3008 and the potentiometer. Upload Exercise 4 and confirm the knob moves raw from 0 to about 1023.
  3. Upload the project sketch. Turn the knob from one end to the other and watch the bar grow.
  4. Compare the raw values at which the LEDs change with the table. If they differ by hundreds of counts, the wiring has a fault, and if they differ by a few, that is noise.

Try the Project in the Lab

The whole project also runs in the Electronics Lab, so you can check the sketch and the wiring before touching a breadboard, or run it without the parts. The Lab holds an Uno R3, a 10kΩ potentiometer, an MCP3008, a 74HC595, eight 1kΩ resistors, and eight LEDs, connected as in the wiring table in Planning the Build, and it runs the exact project sketch shown above.

The MCP3008 and the 74HC595 in the Lab are software models, not the real chips. Each one is a small program written from the part's datasheet. The MCP3008 model answers the three-byte frame from the diagram above and reads the voltage on its CH0 pin. The 74HC595 model shifts a bit in on every clock pulse, including the pulses meant for the MCP3008, and copies the shift register to its outputs only when RCLK rises, which is the behavior this part relied on. Two differences from a bench build matter. The Lab potentiometer gives an exact value with no noise, so the raw reading follows it in clean steps where a real knob jitters by a few counts. And the Lab's 5V is exactly 5V, so the voltages in Exercise 4 come out as calculated.

To use the Lab:

  1. Press the green Run button. The first run compiles the sketch, so give it a few seconds.
  2. Open the Serial monitor. It prints a raw = ..., level = ... line about ten times a second.
  3. Turn the potentiometer in the circuit. In the Lab its value runs from 0 to 1023, which stands for 0V to 5V.
  4. Watch the LEDs. LED 1 lights when the raw value reaches 114, two LEDs at 228, four at 456, and all eight at 911. Those are the thresholds in the done test table.

The author's own Lab runs agree with that table: with the potentiometer at 113, no LED lit and the level was 0; at 114 one LED lit; at 227 still one; at 228 two; at 456 four; at 911 and at 1023 all eight, in order from LED 1. If your run differs, check that you pressed Run after loading the circuit and that the Serial monitor shows the line changing as you turn the knob.

Reading the output critically

The numbers prove less than they seem to. A bar that follows the knob shows that the MCP3008 and the 74HC595 both work on the shared bus. It does not show the accuracy of the reading: the voltage in Exercise 4 assumes VREF is exactly 5V, and a USB-powered Uno supplies whatever the USB port provides. The LED count has a resolution of about 114 raw counts per step, so it hides noise that the raw column makes visible. If the raw value flickers by a few counts with the knob still, that is expected. If it flickers by dozens, look at the ground connection to the MCP3008 and the wires to the potentiometer.

Troubleshooting

Symptom Likely cause First check
All LEDs stay dark OE not low, or no latch pulse reaches RCLK 74HC595 pin 13 on GND; pin 12 wired to D9
LEDs show a random pattern at power-up The outputs have not been latched yet showPattern(0) in setup() runs and RCLK is wired
Pattern is mirrored LED order reversed QA is pin 15, not pin 1; QB to QH are pins 1 to 7
Raw stuck at 0 or 1023 No reply from the MCP3008 DOUT to D12, CS to D10, VDD and VREF on 5V
Raw follows the knob but values are too large or shifted Frame bytes out of order or the wrong mask First byte 0x01, second byte 0x80 for channel 0, third byte 0x00
Raw jumps while the knob is still Noise or a floating input Ground pins 9 and 14, potentiometer wiper to pin 1
Everything worked, then SPI stopped D10 became an input or a pulled-low SS The SS gotcha: confirm D10 stays an output
Another SPI peripheral added: readings corrupt Two chips driving MISO, or a CS left low Only the selected chip may drive MISO; every other CS high

Reading comes back as the wrong value in a consistent way

A reading that follows the knob but is too large or shifted points to the frame. The reply in the second byte carries only result bits 9 and 8 in its low two bits. The datasheet describes the bits above them as unknown, because the chip's output is still high-impedance for the first two clocks, and the null bit sits between them and the result [3]. A sketch that uses more than the low two bits of the second byte, for example by masking with 0x0F instead of 0x03, mixes those unknown bits into the result. Print frame[1] and frame[2] in hexadecimal and compare them with the diagram.

The bus stops working after a change that does not mention SPI

The SS trap is the usual cause. A change that turns D10 into an input, a shield that pulls D10 low, or a library that reconfigures the pin can clear MSTR, after which the Uno stops clocking the bus. Print SPCR & _BV(MSTR) in loop(): a 0 confirms it. The fix is to keep D10 an output.

Two devices disturb each other

On a shared bus, only one peripheral may have its chip select low at any moment. If a second peripheral that drives MISO is added, check that its chip select idles high and that the sketch raises the first chip select before lowering the second. Remember also that the 74HC595 has no chip select: it shifts on every clock pulse, so its latch must only be pulsed right after a fresh byte.

Measuring an SPI Bus

A multimeter can check the idle conditions of the bus and little else. With the sketch idle, a chip select line should sit near 5V (high, not selected), and in mode 0 the clock should rest near 0V. Transfers are too short for a meter to follow: at 1MHz one byte takes 8 microseconds, and the MCP3008 frame of three bytes lasts 24 microseconds. To see the bits themselves, use a logic analyzer or an oscilloscope on SCK, MOSI, MISO, and the chip selects. Everything in this part runs at 5V and from USB, so the measurements carry no mains risk, but do not connect a 5V signal to a 3.3V-only input.

Where This Fits in the Series

Mastering Arduino Part 11: UART: Serial Is a Bus showed an asynchronous link between two devices with no shared clock. Mastering Arduino Part 12: I2C, Addressing a Bus put many devices on two shared wires and told them apart with addresses. This part adds a third approach, a shared clock with a chip select per device, which gives speed at the price of extra wires. Part 14 moves from talking to chips to driving real loads, with PWM and switching.

References

  1. Arduino, “Arduino & Serial Peripheral Interface (SPI),” Arduino Docs, docs.arduino.cc. https://docs.arduino.cc/learn/communication/spi/ Accessed November 22, 2026.
  2. Microchip Technology, “ATmega48A/PA/88A/PA/168A/PA/328/P Data Sheet,” document DS40002061A, 2018, chapter 19, SPI - Serial Peripheral Interface, microchip.com. https://ww1.microchip.com/downloads/en/DeviceDoc/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061A.pdf Accessed November 22, 2026.
  3. Microchip Technology, “MCP3004/3008 2.7V 4-Channel/8-Channel 10-Bit A/D Converters with SPI Serial Interface,” datasheet DS21295D, 2008, microchip.com. https://ww1.microchip.com/downloads/en/DeviceDoc/21295d.pdf Accessed November 22, 2026.
  4. Texas Instruments, “SN54HC595, SN74HC595 8-Bit Shift Registers With 3-State Output Registers,” datasheet SCLS041J, revised October 2021, ti.com. https://www.ti.com/lit/ds/symlink/sn74hc595.pdf Accessed November 22, 2026.
  5. Motorola, “MC68HC05C4, MC68HSC05C4, MC68HC05C8, MC68HC805C4 Technical Data, Advance Information,” document ADI991R2, 1985, section 6, Serial Peripheral Interface (SPI), hosted by bitsavers.org. https://bitsavers.mirrorservice.org/components/motorola/6805/_dataSheets/MC68HC05C4_C8_Technical_Data_1985.pdf Accessed November 22, 2026.
  6. Arduino, “SPI,” Arduino Language Reference, with the SPISettings, beginTransaction, and transfer pages, revised January 24, 2026, docs.arduino.cc. https://docs.arduino.cc/language-reference/en/functions/communication/SPI/ Accessed November 22, 2026.
  7. Arduino, “SPI library source (SPI.h and SPI.cpp),” ArduinoCore-avr, GitHub. https://github.com/arduino/ArduinoCore-avr/tree/master/libraries/SPI/src Accessed November 22, 2026.
  8. Arduino, “Arduino UNO R3,” datasheet A000066, docs.arduino.cc. https://docs.arduino.cc/resources/datasheets/A000066-datasheet.pdf Accessed November 22, 2026.
  9. Solomon Systech, “SSD1306 128 x 64 Dot Matrix OLED/PLED Segment/Common Driver with Controller,” datasheet Rev 1.1, April 2008, copy hosted at cdn-shop.adafruit.com. https://cdn-shop.adafruit.com/datasheets/SSD1306.pdf Accessed November 22, 2026.

Wrap-Up and What's Next

SPI exchanges one byte in each direction on every eight clock pulses, and chip select decides which peripheral takes part. The mode, the clock speed, and the bit order are set by the device's datasheet, SPISettings carries them, and a transaction applies them. The SPI library hides the registers, and the AVR's SS pin remains a trap whenever a sketch changes it from an output. The knob-to-bar project shows two chips with different settings sharing one set of wires.

Part 14 turns from reading and talking to chips toward driving real loads, which takes PWM and switching hardware, so it comes next.

Hack The World and Make Awesome.

Add new comment

Restricted HTML

  • You can align images (data-align="center"), but also videos, blockquotes, and so on.
  • You can caption images (data-caption="Text"), but also videos, blockquotes, and so on.