mcp3008_read.py

Raspberry Pi 5 (model-5) · File : mcp3008_read.py · Language : Python · Use case : Acquérir un signal analogique (potentiomètre, capteur) alors que le GPIO ne lit que du tout-ou-rien

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-5, enable SPI (spi_arm) in config.txt or raspi-config.

Hardware

A Raspberry Pi 5 (quad-core BCM2712 at 2.4 GHz, RP1 I/O chip, 40-pin GPIO, recommended 5 V/5 A USB-C power, two CSI camera ports). 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), then run it with python3. On Bookworm, gpiozero 2.x drives the pins through the RP1 chip; keep gpiozero and python3-rpi.gpio updated (sudo apt full-upgrade). A 5 V/5 A supply is advised.

Variants

Eight channels available; use a 16-sample moving average to steady readings. Check pinout on the official J8 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()

← Back to the board