mcp3008_read.py

Raspberry Pi 3 Model B+ (2018) — 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-3b-plus, enable SPI (spi_arm) in config.txt or raspi-config.

Hardware

A Raspberry Pi 3 Model B+ (quad-core BCM2837B0 at 1.4 GHz, 5 GHz Wi-Fi, Bluetooth 4.2, shielded metal case SoC, 40-pin GPIO). 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 (or bash). Raspberry Pi OS ships gpiozero; otherwise sudo apt install python3-gpiozero. The 40-pin pinout is documented on the official Raspberry Pi site.

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