#1) To determine if a train is present, I’ve cobbled together some code that samples the value of the GPIO pin about ~2,000 times over ten seconds. If the sensor reads high for more than 10% of the sampled 10 seconds, a train is considered to be present.
#2) I’m currently planning to embed a series of additional if statements that each sample a new 10 second window if a train was present in the previous if statement. However, it seems really inefficient to have 36 sequential if statements to find out if a train was passing by my house for 5 minutes. Is there a better approach??
Quick disclaimer: This is my first raspberry pi / coding project—I’m open to any suggestions to improve the program.
Code: Select all
#!/usr/bin/python import sys import urllib2 import RPi.GPIO as GPIO import time myAPI = 'YW9KT0LI9W72Z7JY' baseURL = 'https://api.thingspeak.com/update?api_key=%s' % myAPI #GPIO SETUP channel = 17 GPIO.setmode(GPIO.BCM) GPIO.setup(channel, GPIO.IN) def callback(channel): startTime = time.time() endTime = startTime + 10 # creates sample window soundPresentCount = 0.0 # number of instances in sample window where GPIO is HIGH soundAbsentCount = 0.0 # number of instances in sample window where GPIO is LOW while time.time() <= endTime: if GPIO.input(channel): soundPresentCount = soundPresentCount + 1.0 time.sleep(0.005) else: soundAbsentCount = soundAbsentCount + 1.0 time.sleep(0.005) print ("Counted Presents:"), soundPresentCount print ("Counted Absents:"), soundAbsentCount totalCount = soundPresentCount + soundAbsentCount print ("Total Count:"), totalCount presentPercent=(soundPresentCount/totalCount)*100.0 print (presentPercent) if presentPercent>=10.0: trainCount = 1 trainDuration = trainDuration + 10.0 print ("Train Detected") conn = urllib2.urlopen(baseURL + '&field1=%s&field2=%s' % (trainCount, trainDuration)) print conn.read() conn.close() soundAbsentCount = 0.0 soundPresentCount = 0.0 else: print ("No Train Detected") soundAbsentCount = 0.0 soundPresentCount = 0.0 GPIO.add_event_detect(channel, GPIO.BOTH, bouncetime=50) # let me know when the pin goes HIGH or LOW GPIO.add_event_callback(channel, callback) # assign function to GPIO PIN, Run function on change # infinite loop while True: time.sleep(0.5)