Try Embedded

More analog inputs over SPI (MCP3008)

An MCP3008 adds eight 10-bit analog inputs over SPI: read a joystick and a knob through it, single-ended and as a differential pair.

Sensors · Intermediate

In a real product: Game controller (Consumer electronics): An external ADC reads the sticks and triggers.

Some boards have few analog inputs, or none. An MCP3008 gives eight, at 10 bits like the Uno's own ADC, over four SPI wires. It also measures one input against another (differential), handy for a bridge sensor.

What you'll learn

  • The MCP3008's three-byte SPI exchange: a start bit, the channel, and the result clocked back
  • That the result is relative to VREF: tie it to a steady reference
  • Single-ended and differential readings

How it works

adc.readADC(ch) pulls CS low and sends 0x01 (the start bit), then the mode bit and the channel number, then a dummy byte; the chip samples the input and shifts back a null bit and the 10-bit result. That is 1024 × VIN / VREF, here with VREF on 5V. readADCDifference(0) reads CH0 minus CH1: positive when the joystick's X is right of its Y, and 0 when it is not (it does not go negative).

Try this

  • Move the joystick and turn the knob while it runs.
  • Wire VREF to the 3.3V pin instead: the same voltages read about 1.5 times higher, and 3.3 V reads full scale.
  • Use the other constructor, adc.begin(SCK, MOSI, MISO, CS), to bit-bang it on any four pins.

sketch.ino

// An MCP3008 on the hardware SPI (CS on pin 10): a joystick on CH0 (X) and CH1 (Y) and a knob on CH2, every half
// second, with the X minus Y difference.
#include <Adafruit_MCP3008.h>

Adafruit_MCP3008 adc;

void setup() {
  Serial.begin(9600);
  adc.begin(10);
}

void loop() {
  Serial.print("X ");
  Serial.print(adc.readADC(0));
  Serial.print("  Y ");
  Serial.print(adc.readADC(1));
  Serial.print("  knob ");
  Serial.print(adc.readADC(2));
  Serial.print("  X-Y ");
  Serial.println(adc.readADCDifference(0));
  delay(500);
}

Lessons behind it