Created
February 19, 2017 03:05
-
-
Save exp0nge/e5580a128559c972351ad63b27086a29 to your computer and use it in GitHub Desktop.
hcsr04 with a fix for the stupid signal being frozen
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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