Below is the code I'm running on my raspberry pi zero to detect the range by Ping))) ultrasonic.
after some time (ex: 300 pings) the program uses most of the CPU (90%) and then it stops working, is there anything wrong with my code? or the circuit might need revision.
#!/usr/bin/python3
import time
import RPi.GPIO as GPIO
#Use board based pin numbering
GPIO.setmode(GPIO.BOARD)
def ReadDistance(pin,ping_duration):
# Set the pin to False (Low)
GPIO.setup(pin, GPIO.OUT)
GPIO.output(pin, False)
# Allow module to settle
time.sleep(0.02)
# Send ping
GPIO.output(pin, True)
# Signal duration
time.sleep(ping_duration)
# Stop pinging
GPIO.output(pin, False)
# Set pin to input
GPIO.setup(pin, GPIO.IN)
starttime = 0
endtime = 0
# wait for ping echo
while GPIO.input(pin)==0:
starttime = time.process_time()
while GPIO.input(pin)==1:
endtime = time.process_time()
# Calculate echo time
duration=endtime-starttime
# Distance is defined as time/2 (there and back) * speed of sound 34000 cm/s
distance=duration*34000/2
return distance
counter = 0;
while True:
print (ReadDistance(11,0.00001)," t:",counter)
counter = counter+1
time.sleep(.5)