Skip to content

Instantly share code, notes, and snippets.

@exp0nge
Created February 19, 2017 03:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save exp0nge/e5580a128559c972351ad63b27086a29 to your computer and use it in GitHub Desktop.
Save exp0nge/e5580a128559c972351ad63b27086a29 to your computer and use it in GitHub Desktop.
hcsr04 with a fix for the stupid signal being frozen
# http://stackoverflow.com/questions/32300000/galileo-and-ultrasonic-error-when-distance-less-than-4cm
import mraa
import time
trig = mraa.Gpio(3)
echo = mraa.Gpio(4)
trig.dir(mraa.DIR_OUT)
echo.dir(mraa.DIR_IN)
def distance(measure='cm'):
trig.write(0)
time.sleep(0.1)
trig.write(1)
time.sleep(0.00001)
trig.write(0)
while echo.read() == 0:
nosig = time.time()
sig = None
while echo.read() == 1:
sig = time.time()
if sig is None:
return -1
# et = Elapsed Time
et = sig - nosig
if measure == 'cm':
distance = et * 17150
elif measure == 'in':
distance = et / 0.000148
else:
print('improper choice of measurement!!')
distance = None
return distance if distance < 80 else -1
while True:
print(distance('cm'))
time.sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment