Bird
0
0
Raspberry Piprogramming~5 mins

Reading analog sensors through ADC in Raspberry Pi

Choose your learning style9 modes available
Introduction

Analog sensors give signals as varying voltages. Raspberry Pi cannot read these voltages directly because it only understands digital signals. An ADC (Analog to Digital Converter) changes these voltages into numbers the Pi can read.

You want to measure temperature with an analog temperature sensor.
You need to read light levels from a photoresistor.
You want to detect the position of a joystick that outputs analog signals.
You are building a project that uses sensors giving varying voltage outputs.
Syntax
Raspberry Pi
import spidev

spi = spidev.SpiDev()
spi.open(0, 0)  # Open SPI bus 0, device 0

def read_adc(channel):
    if channel < 0 or channel > 7:
        return -1
    adc = spi.xfer2([1, (8 + channel) << 4, 0])
    data = ((adc[1] & 3) << 8) + adc[2]
    return data

This example uses the MCP3008 ADC chip connected via SPI.

The read_adc function reads the analog value from the specified channel (0-7).

Examples
Reads the analog value from channel 0 and prints it.
Raspberry Pi
value = read_adc(0)
print(f"Sensor value: {value}")
Reads and prints values from channels 0 to 3.
Raspberry Pi
for ch in range(4):
    print(f"Channel {ch}: {read_adc(ch)}")
Sample Program

This program reads the analog value from channel 0 of the MCP3008 ADC every second. It converts the raw value to voltage assuming a 3.3V reference and prints both values. Press Ctrl+C to stop.

Raspberry Pi
import spidev
import time

spi = spidev.SpiDev()
spi.open(0, 0)  # Open SPI bus 0, device 0

# Function to read from MCP3008 ADC
# channel must be 0-7

def read_adc(channel):
    if channel < 0 or channel > 7:
        return -1
    adc = spi.xfer2([1, (8 + channel) << 4, 0])
    data = ((adc[1] & 3) << 8) + adc[2]
    return data

try:
    while True:
        sensor_value = read_adc(0)  # Read channel 0
        voltage = sensor_value * 3.3 / 1023  # Convert to voltage
        print(f"Analog sensor reading: {sensor_value}, Voltage: {voltage:.2f} V")
        time.sleep(1)
except KeyboardInterrupt:
    spi.close()
    print("Program stopped")
OutputSuccess
Important Notes

Make sure the MCP3008 chip is wired correctly to the Raspberry Pi SPI pins.

SPI must be enabled on the Raspberry Pi using raspi-config.

The ADC returns values from 0 to 1023 for 10-bit resolution.

Summary

Raspberry Pi cannot read analog signals directly, so we use an ADC like MCP3008.

The ADC converts voltage to a digital number we can read via SPI.

Use a function like read_adc(channel) to get sensor values.