Skip to content

LDR MCP3004 ADC UPXtreme Device via SPI

Teteh Camillus Chinaedu edited this page Nov 8, 2021 · 2 revisions

Introduction

In this tutorial, I will describe how to connect an LDR to an MCP3004 device which in turn connects to a an UP Device. For this tutorial I will use an UP Xtreme device.

We will use a python3 script to get readings from the sensors.

Pre-requisites

  • UP Xtreme device
  • MCP3004
  • LDR sensor
  • Breadboard
  • Jumper wires
  • UP device setup correctly with UP kernel. upboard extras, groups, user added to groups, ACPI overrides installed and SPI enabled in user space. Kindly refer here for setup of UP Xtreme
  • Spidev installed on device

Wiring

  • You can find the MCP3004 datasheet to identify the channels and SPI serial interface
  • Refer to UP Xtreme pinout page to identify the SPI pins
  • Kindly refer to the wiring picture attached below

Wiring Picture

Installation

  • You will need to install python3-pip and spidev sudo apt install python3-pip pip3 install spidev

Python3 Script


#Import SpiDev wrapper to enable hardware SPI
import spidev
import time

#Establish SPI connection with Bus 0, Device 0
spi = spidev.SpiDev()
spi.open(0,0)

def get_adc(channel):
    #Check valid channel
    if((channel > 3) or (channel < 0)):
        return -1

    #Perform SPI transaction and store returned bits in 'r'
    r = spi.xfer([1, (8+channel)<<4, 0])
    #Filter data bits from returned bits
    adcout = ((r[1]&3) << 8) + r[2]
    #Return value from 0-1023
    return adcout


while True:
    print (get_adc(0))
    time.sleep(5)


Expected Result

When script is run, the device gets sensor readings from LDR connected to MCP3004 device, the value of readings are dependent on the light intensity of the environment. If LDR is protected from light for example by placing your palms to block out light you receive 0 as reading

Version

0.1

Author

  • Camillus Teteh

Acknowledgments

  • Hat tip to anyone whose code was used
Clone this wiki locally