mcp3008_read.py
Raspberry Pi GPIO is purely digital: this script adds eight 10-bit analog inputs via an MCP3008 on SPI bus 0. Wire a potentiometer to channel 0 and the 0–1023 conversion becomes 0–3.3 V. On the model-b-rev2, enable SPI (spi_arm) in config.txt or raspi-config.
Hardware
A Raspberry Pi Model B revision 2 (BCM2835, 26-pin GPIO header, Ethernet/USB ports moved to the board edge). One MCP3008 DIP-16 chip, a 10k potentiometer, breadboard, dupont wires.
Wiring
MOSI/MISO/SCLK to GPIO10/9/11 (pins 19, 21, 23), CS0 to pin 24, VDD 3.3 V, wiper to CH0, 3.3 V/GND rail links.
How it works
spidev swaps 3 bytes; the MCP3008 returns a 10-bit sample scaled by 3.3/1023. Never feed more than 3.3 V into the inputs.
Running it
Copy the script to the board (scp or USB stick), then run it with python3 (or bash). On Raspbian, install gpiozero with sudo apt install python3-gpiozero. The full 26-pin pinout is in the official Raspberry Pi schematic.
Variants
Eight channels available; use a 16-sample moving average to steady readings. Check pinout on the official P1 diagram.
mcp3008_read.py
# mcp3008_read.py — lit un potentiel analogique via ADC SPI MCP3008.
# Deps: sudo apt install python3-spidev (activer spi_arm dans config.txt)
import spidev, time
spi = spidev.SpiDev()
spi.open(0, 0) # bus SPI0, celecteur CS0
spi.max_speed_hz = 1350000
def read_ch(ch):
val = spi.xfer2([1, (8 + ch) << 4, 0])
out = ((val[1] & 0x03) << 8) + val[2]
return out * 3.3 / 1023.0
try:
while True:
print(f"CAN0 = {read_ch(0):0.2f} V")
time.sleep(1)
except KeyboardInterrupt:
spi.close()