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.
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
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
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
#!/usr/bin/python import time from gpiozero import MCP3008 divider = MCP3008(0) while True: print(divider.value) time.sleep(1.0)
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
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 & 3) << 8) + r return data while True: ldr_value = readadc(ldr_channel) print("LDR Value: %d" % ldr_value) time.sleep(delay)
You can pick these up quite easily for around $2 a piece.