mcp3008_read.py

Raspberry Pi Model B (Rev 1, 2012) — Board Sheet · 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-b-rev1, enable SPI (spi_arm) in config.txt or raspi-config.

Hardware

A Raspberry Pi Model B revision 1 (BCM2835, 26-pin GPIO header, original through-hole ports, no standard 40-pin P1 connector). 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). These boards often run an old Raspbian: gpiozero is still apt-installable. GPIO pins follow the 26-pin header in the official 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()

← Back to the board