Permalink
Browse files

improve sensor logic

take multiple readings for sonic sensor and average them to counter bad
readings due to OS timings.  Also add a timeout for the readings.

reduce timeout for photocell
  • Loading branch information...
johnmwright committed Feb 2, 2015
1 parent 1d9422d commit 3918e7cbe2dbba2119dfd211f446afcf7237abe5
Showing with 33 additions and 6 deletions.
  1. +1 −1 Python/PhotocellController.py
  2. +32 −5 Python/SonicController.py
@@ -14,7 +14,7 @@ def __init__(self, pin):

def resistanceTime(self):
print(" Reading photocell")
timeout = 3000
timeout = 1000
reading = 0
GPIO.setup(self.pin, GPIO.OUT)
GPIO.output(self.pin, GPIO.LOW)
@@ -18,30 +18,57 @@ def __init__(self, triggerPin, echoPin):
print("Waiting For Sensor To Settle")
time.sleep(2)

def readDistance(self):
def _readDistanceOnce(self):

print("Distance Measurement In Progress")
print(" Distance Measurement In Progress")
READING_TIMEOUT = 2 #sec
maxTime = time.time() + READING_TIMEOUT

GPIO.output(self.triggerPin, True)
time.sleep(0.00001)
GPIO.output(self.triggerPin, False)


pulse_start = time.time()
while GPIO.input(self.echoPin)==0:
while GPIO.input(self.echoPin)==0 and pulse_start < maxTime:
pulse_start = time.time()


while GPIO.input(self.echoPin)==1:
pulse_end = time.time()
while GPIO.input(self.echoPin)==1 and pulse_end < maxTime:
pulse_end = time.time()

if pulse_end > maxTime:
print(" PULSE READ TIMED OUT")

pulse_duration = pulse_end - pulse_start
roundtrip_duration = pulse_duration * self.SPEED_OF_SOUND
one_way_distance = roundtrip_duration/2
print(" Distance: {0:0.2f} cm".format(one_way_distance))
return one_way_distance

def readDistance(self):

#
# Take multiple readings in order to counter the affects of
# bad data due to non-realtime OS. Take a bunch of readings,
# throw out the min and max, then average the rest.
#
numReadingsToTake = 8
print(" Taking {} Distance Measurements".format(numReadingsToTake))
measurements = []
for x in range(0, numReadingsToTake):
thisReading = self._readDistanceOnce()
measurements.append(thisReading)

maxReading = max(measurements)
minReading = min(measurements)
measurements.remove(maxReading)
measurements.remove(minReading)

average = sum(measurements)/len(measurements)

print(" Average Distance: {0:0.2f} cm".format(average))
return average

def teardown(self):
print("Tearing down Ultrasonic Range Finder")

0 comments on commit 3918e7c

Please sign in to comment.