Tutorial 23 & 24: Analog Sensor Programming

Alright we have our MCP3004 or MCP3008 wired up to our Raspberry Pi. It's now time to start writing scripts that allow us to take readings from the sensors connected to the chips. In the following two tutorials I show you how to read an analog-digital convertor connected to your Pi via SPI.

This tutorial is a little older (published in 2015!). The main principles are still relevant, so I haven't needed to update this lesson.

  • Raspberry Pi
  • 5VDC Micro USB Power Supply
  • The circuit built in the previous tutorial
  • How to initialize a connection between a MCP3008 SPI device and a Raspberry Pi
  • How to pull data from the analog-digital-convertor
  • How to convert the analog bit value into a useful number
You can copy / paste the code below if you’re having issues with typos or want a shortcut. However I recommend that you follow along in the tutorial to understand what is going on!

import spidev
from time import sleep

# First open up SPI bus
spi = spidev.SpiDev()

# Initialize what sensor is where
lightChannel = 0
tempChannel = 1
sleepTime = 1

def getReading(channel):
    # First pull the raw data from the chip
    rawData = spi.xfer([1, (8 + channel) << 4, 0&#93;)
    # Process the raw data into something we understand.
    processedData = ((rawData&#91;1&#93;&3) << 8) + rawData&#91;2&#93;
    return processedData

def convertVoltage(bitValue, decimalPlaces=2):
    voltage = (bitValue * 3.3) / float(1023)
    voltage = round(voltage, decimalPlaces)
    return voltage

def convertTemp(bitValue, decimalPlaces=2):
    # Converts to degrees Celsius
    temperature = ((bitValue * 330)/float(1023) - 50)
    temperature = round(temperature, decimalPlaces)
    return temperature

while True:
    lightData = getReading(lightChannel)
    tempData = getReading(tempChannel)
    lightVoltage = convertVoltage(lightData)
    tempVoltage = convertVoltage(tempData)
    temperature = convertTemp(tempData)

    # Print ALL THE THINGS:
    print("Light bitValue = {} ; Voltage = {} V".format(lightData, lightVoltage))
    print("Temp bitValue = {} ; Voltage = {} V ; Temp = {} C".format(\
        tempData, tempVoltage, temperature))

The following tutorials require some downloads. You can find links to the sources below:

Tutorial 23

Tutorial 24