Skip to content

Instantly share code, notes, and snippets.

@m-hofmann
Created June 13, 2016 15:39
Show Gist options
  • Save m-hofmann/6c13a672a8e87fd5c47550513ed21979 to your computer and use it in GitHub Desktop.
Save m-hofmann/6c13a672a8e87fd5c47550513ed21979 to your computer and use it in GitHub Desktop.
Script for testing an IR sensor with the PCF8291 A/D converter on the Raspberry Pi
#!/usr/bin/env python3
import smbus as smbus
import RPi.GPIO as GPIO
import time
DEV_ADDR = 0x48
FR_LED_PIN = 15
def LED_on():
GPIO.output(15, 1) # LED on
def LED_off():
GPIO.output(15, 0)
def read_sensor(sensor_no):
aout = 0
bus.write_byte(DEV_ADDR, 0x40 | ((sensor_no) & 0x03))
bus.read_byte(DEV_ADDR)
return bus.read_byte(DEV_ADDR) # percentage of 3.3 V
GPIO.cleanup()
GPIO.setmode(GPIO.BOARD)
GPIO.setup(15, GPIO.OUT)
bus = smbus.SMBus(1)
channel = 0
ctr = 0
print("Polling on channel " + str(channel))
while True:
try:
print("=== reading " + str(ctr) + " ===")
LED_off()
baseline = read_sensor(channel)
LED_on()
value = read_sensor(channel)
LED_off()
over_baseline = value - baseline
collision_perc = over_baseline / (255 - baseline)
print("baseline: " + str(baseline) + " value: " + str(value))
print("collision likeliness: {0:.2f} %".format(collision_perc * 100))
dist = "["
# around 30% are from environmental scattering of the IR light
if collision_perc > 0.3:
if collision_perc > 0.4:
# > 50 % is already pretty close
if collision_perc > 0.5:
dist = "[=]"
else:
dist = "[==]"
else:
dist = "[===]"
print("rating: distance is ", dist)
time.sleep(0.5)
ctr += 1
except KeyboardInterrupt:
LED_off()
GPIO.cleanup()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment