This workpackage is about how to work with analogue input with the help of the Gertboard. We read the data of a light sensor with python.
Instructions Prepare Gertboard Python Code Test your Code Circuit Schematic Useful Resources
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
(PYTHON) Due to the fact, that the Raspberry Pi does not have analogue inputs we have to use an extension board to get information about a light sensor or other analogue inputs.
In this worksheet we use the Gertboard. There is some python and C test code already provided which can be used.
Instructions Prepare Gertboard
- connect the Gertboard to the Raspberry Pi, be careful that the Pin 1 on the raspberry (left upper corner) is connected to the Pin 1 on the Gertboard (marked with a square)
- enable SPI o sudo nano /etc/modprobe.d/raspi-blacklist.conf o insert a # before blacklist spi-bcm2708 o sudo reboot
- connect following with jumpers as shown in picture 1: o GP11 to SCLK o GP10 to MOSI o GP9 to MISO o GP8 to CSnA
- create circuit as seen in picture 2 o connect the blue wire to the analogue pin on Gertboard (Picture 1, upper left
corner, number 2) o connect the black wire to GND o connect the red wire to 3V
python code from time import sleep import subprocess # to prevent from spi failures reload spi drivers at the beginning unload_spi = subprocess.Popen('sudo rmmod spi_bcm2708', shell=True, stdout=subprocess.PIPE) start_spi = subprocess.Popen('sudo modprobe spi_bcm2708', shell=True, stdout=subprocess.PIPE) sleep(3) #import spidev and open SPI to work with ADC on Gertboard import spidev loops = 600 spi = spidev.SpiDev() #the ADC of the Gertboard is on SPI channel 0 spi.open(0,0)
#dependend on the Pin you use on Gertboard select 0 (for AD0) or 1 (for AD1) channel = 1 #if varable loops is 600, there are 600 values printed out before the program ends while loops > 0: #send start bit, sgl/diff, odd/sign, MSBF to SPI r = spi.xfer2([1,(2+channel)<<6,0]) #spi.xfer2 returens same number of 8-bit bytes as sent #we parse out the part of bits which includes the changing value of the sensor adc_value = ((r[1]&31) << 6) + (r[2] >> 2) #print analgue value print(adc_value) # delay after each print sleep(0.05) # decrease variable loops loops -= 1
Test your Code Run your code by navigating to directory where you saved your file and typing in following command: python filename.py