Last active
January 8, 2017 18:08
-
-
Save frogwoo/7e27f127323f5d1f3d44998b6d6ca6ea to your computer and use it in GitHub Desktop.
Simple code to read values from an analogue line sensor (using an ADC as this is for the Pi) and say if a line is detected or not. View https://theraspberryblonde.wordpress.com/2017/01/08/qre1113-analogue-line-sensor-with-raspberry-pi/ to see more details about how to use the code.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import spidev | |
import time | |
# which ADC input the sensor is connected to | |
sensor = 0 | |
# the boundary between no line detected and a line detected | |
boundary = 30 | |
# open the spi connection for the ADC | |
spi = spidev.SpiDev() | |
spi.open(0, 0) | |
# read the ADC value for the given input | |
def getADC(adcnum): | |
r = spi.xfer2([1, 8 + adcnum << 4, 0]) | |
data = ((r[1] & 3) << 8) + r[2] | |
return data | |
# find the average value where there isn't a line | |
# NOTE: for calibration to work, the robot must | |
# not be over the line at the start of the program | |
def calibrate(): | |
val = 0 | |
for i in range(100): | |
val += getADC(sensor) | |
time.sleep(0.05) | |
val /= 100 | |
return val | |
noLineVal = calibrate() | |
while True: | |
# read the line sensor value | |
lineVal = getADC(sensor) | |
# if value higher than value for no line | |
if lineVal > noLineVal + boundary: | |
print "centre on line" | |
else: | |
print "not on line" | |
time.sleep(0.5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment