Code: Select all
import time
import RPi.GPIO as GPIO
import datetime
GPIO.setmode(GPIO.BCM)
GPIO_TRIGGER = 11
GPIO_ECHO = 9
compensation = -11
print "Ultrasonic Measurement"
GPIO.setup(GPIO_TRIGGER,GPIO.OUT) # Trigger
GPIO.setup(GPIO_ECHO,GPIO.IN) # Echo
GPIO.output(GPIO_TRIGGER, False)
time.sleep(0.5)
distance_prev = 0
try:
while True:
# Send 10us pulse to trigger
GPIO.output(GPIO_TRIGGER, True)
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
start = time.time()
while GPIO.input(GPIO_ECHO)==0:
start = time.time()
while GPIO.input(GPIO_ECHO)==1:
stop = time.time()
# Calculate pulse length
elapsed = stop-start
# speed of sound = 34300 cm/s (34300 / 2 = 17150)
distance = elapsed * 17150
#print "Distance :",round(distance,2),"cm (",round(distance_prev-distance,2), "cm)"
print datetime.datetime.now(),"Distance = {}\t\tDiff = {}".format(round(distance,2), round(distance_prev-distance,2))
distance_prev = distance
distance = distance + compensation
time.sleep(10)
except KeyboardInterrupt:
print("Clean Exit By user")
finally:
# Reset GPIO settings
GPIO.cleanup()
I suspect it does not have time to read the data from the port of ECHO and hangs on WHILE
I had a problem earlier when he wrote a program to read RFID key protocol WIEGAND26, use the library pigpio
http://abyz.co.uk/rpi/pigpio/python.html#pigpio.pi
which work with GPIO ports goes through the daemon written in C
I tried to rewrite the program, but it also freezes help run the normal program with the library pigpio
Code: Select all
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pigpio
import time
import datetime
def waterlevel(wl_gpio_trigger, wl_gpio_echo):
pi = pigpio.pi()
wl_timer_start = time.time()
pi.set_mode(wl_gpio_trigger, pigpio.OUTPUT)
pi.set_mode(wl_gpio_echo, pigpio.INPUT)
pi.write(wl_gpio_trigger,False)
time.sleep(0.5)
pi.write(wl_gpio_trigger,True)
time.sleep(0.00001)
pi.write(wl_gpio_trigger,False)
while pi.read(wl_gpio_echo)==0:
wl_timer_start = time.time()
while pi.read(wl_gpio_echo)==1:
wl_timer_stop = time.time()
wl_time_elapsed = wl_timer_start - wl_timer_stop
pi.stop()
return wl_time_elapsed;
if __name__ == "__main__":
try:
while True:
print datetime.datetime.now(),"---"
print "\n",waterlevel(11,9)
time.sleep(3)
except KeyboardInterrupt:
print("Clean Exit By user")
finally:
print("Finally")
''' END '''