1. Introduction
The Raspberry Pi does not have built-in analog input pins. To read analog sensors like LM35, LDR, or soil moisture sensors, we use an ADC (Analog to Digital Converter).
The MCP3008 is a popular 8-channel ADC that communicates using SPI protocol, allowing Raspberry Pi to read analog values easily.
2. Components
- Raspberry Pi 4 Model B
- MCP3008 ADC IC
- Breadboard
- Jumper wires
- Analog sensor (LM35 / LDR optional)
3. Circuit and Connections
MCP3008 to Raspberry Pi (SPI Connection)
| MCP3008 Pin | Function | Raspberry Pi Pin |
|---|---|---|
| 16 | VDD | 3.3V |
| 15 | VREF | 3.3V |
| 14 | AGND | GND |
| 13 | CLK | GPIO11 (SCLK) |
| 12 | DOUT | GPIO9 (MISO) |
| 11 | DIN | GPIO10 (MOSI) |
| 10 | CS/SHDN | GPIO8 (CE0) |
| 9 | DGND | GND |
Analog Input Pins
| Channel | Pin |
|---|---|
| CH0–CH7 | Pins 1–8 |
👉 Connect analog sensor output to any channel (e.g., CH0)
4. Detailed Step By Step Circuit Working
- Analog sensor produces variable voltage (0–3.3V).
- MCP3008 converts analog signal into 10-bit digital value (0–1023).
- Raspberry Pi communicates via SPI protocol.
- Data is sent serially from MCP3008 to Raspberry Pi.
- Pi processes and displays the digital value.
5. Libraries to be Included
Enable SPI:
sudo raspi-config
→ Interface Options → SPI → Enable
Install libraries:
pip3 install spidev
6. Code (Python)
import spidev
import time
spi = spidev.SpiDev()
spi.open(0, 0) # Bus 0, Device 0
spi.max_speed_hz = 1350000
def read_channel(channel):
adc = spi.xfer2([1, (8 + channel) << 4, 0])
data = ((adc[1] & 3) << 8) + adc[2]
return data
try:
while True:
value = read_channel(0) # Read from CH0
print("Analog Value:", value)
time.sleep(1)
except KeyboardInterrupt:
spi.close()
7. Detailed Step By Step Code Working
spi.open(0,0)→ Opens SPI busxfer2()→ Sends and receives data(8 + channel) << 4→ Selects ADC channel- Combines received bytes → gets 10-bit value
- Loop continuously reads analog input
8. Tips
- Always use 3.3V (NOT 5V)
- Double-check SPI pin connections
- Use proper grounding
- Keep wires short for stable readings
- Test using potentiometer before sensors
9. Uses
- Reading analog sensors (LM35, LDR, Gas sensors)
- IoT data acquisition systems
- Industrial monitoring
- Robotics sensor integration
- Environmental monitoring
10. Conclusion
The MCP3008 ADC is essential for enabling analog input on Raspberry Pi. It bridges the gap between analog sensors and digital processing, making it a must-have for advanced projects.