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.

Features

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

mcp3008-2

 

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

 

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

pi-and-mcp3008-and-ldr_bb

Code

 

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

[/codesyntax]

Now save the following as mcp3008.py or similar

[codesyntax lang=”python”]

#!/usr/bin/python
import time
from gpiozero import MCP3008

divider = MCP3008(0)

while True:
    print(divider.value)
time.sleep(1.0)

[/codesyntax]

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

UPDATE

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)
time.sleep(delay)

[/codesyntax]

Links

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

MCP3008-I/SL MCP3008 SOP 8-CH 10-BIT SUCCESSIVE APPROXIMATION ADC SERIAL ACCESS

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