I'm building a ground proximity warning system with an ultrasonic sensor, a raspberry pi, and python. I've got a loop thats checking the distance, and based on that distance I'd like a callout to be read.
Intended functionality: Shown in youtube video Boeing 737 cockpit landing (listen to the automatic callouts - sorry Airbus fans ;) ).
Intended functionality explained: As a height is reached, play a mp3 sound once, but only if the distance is getting closer, not farther away.
Python code for the ultrasonic sensor:
#! /usr/bin/python
import RPi.GPIO as GPIO
import time
def checkdist():
GPIO.output(16, GPIO.HIGH)
time.sleep(0.000015)
GPIO.output(16, GPIO.LOW)
while not GPIO.input(18):
pass
t1 = time.time()
while GPIO.input(18):
pass
t2 = time.time()
return (t2-t1)*340/2
GPIO.setmode(GPIO.BOARD)
GPIO.setup(16,GPIO.OUT,initial=GPIO.LOW)
GPIO.setup(18,GPIO.IN)
time.sleep(2)
os.system('mpg123 -q PWSOnline.mp3 &')
try:
while True:
print('Distance: %0.2f m' %checkdist())
time.sleep(0.1)
except KeyboardInterrupt:
GPIO.cleanup()
What I'd like to do:
The ultrasound sensor distance value tends to jump around especially at larger distances, so some way to get the average of the last 0.5 seconds?
Play the callout only if the distance is getting closer, not farther away - so I guess it would need to see the average change over 1 second (whether decreasing or increasing)?
Play the callout once.
The questions:
- What's the best way to go about triggering a function once while inside a loop (and not having the main loop wait for the function to finish - threading, right)?
- How do I deduce the average of the last second in
while
loop?