Home Code Read an LDR On The Raspberry Pi Using An MCP3008

Read an LDR On The Raspberry Pi Using An MCP3008

by shedboy71

In this example we will use the MCP3008 to help us read the value of an LDR, as you will know the Raspberry Pi has no analogue input which can be a bit of a hassle considering there are a few sensors that requires this

The Microchip MCP3008 ADC is a 10-bit Analog to Digital (A/D) converter with on-board sample and hold circuitry.
Communication with the device is accomplished using a simple serial interface compatible with the SPI protocol. The MCP3008 operates over a broad voltage range (2.7V – 5.5V), and low-current design permits operation with typical standby currents of only 5 nA and typical active currents of 320 µA.


10bit ADC
8 channels
SPI Interface
Sampling Rate: 200kSPS
Supply Voltage 2.7V to 5.5V
Supply Current: 425µA
16 pin DIP
Conversion Time: 10µs


Schematics and Connections

You connect the MCP3008 to your Raspberry Pi like this



 VDD  3.3V
 VREF  3.3V
 CLK  GPIO9 (P1-21)
 DOUT  GPIO10 (P1-19)
 DIN  GPIO10 (P1-19)
 CS GPIO8 (P1-24)


Here is a sample layout on a breadboard with an LDR connected to channel 0




I used the gpiozero library, here is how to install this

[codesyntax lang=”bash”]

sudo apt-get update
sudo apt-get install python-pip python3-pip
sudo pip install gpiozero


Now save the following as mcp3008.py or similar

[codesyntax lang=”python”]

import time
from gpiozero import MCP3008

divider = MCP3008(0)

while True:


Run this from your terminal by typing in sudo python mcp3008.py

You should see a value outputted every second, now vary the light to the LDR by positioning closer to a light source, covering it up and so on


here is a code example that requires no library

[codesyntax lang=”python”]

import spidev
import time

#Define Variables
delay = 2
ldr_channel = 0

#Create SPI
spi = spidev.SpiDev()
spi.open(0, 0)
def readadc(adcnum):
    # read SPI data from the MCP3008, 8 channels in total
    if adcnum > 7 or adcnum < 0:
        return -1
    r = spi.xfer2([1, 8 + adcnum << 4, 0])
    data = ((r[1] & 3) << 8) + r[2]
    return data
while True:
    ldr_value = readadc(ldr_channel)
    print("LDR Value: %d" % ldr_value)



You can pick these up quite easily for around $2 a piece.


You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More