0

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)
  • What error does it stop with? Have you checked the system logs? Have you tried adding any application logging? Does this run via an ssh connection or system daemon? More information is needed... – Jacobm001 Aug 15 '17 at 22:24
  • i ran it through SSH, no error, just it stops printing out the distance after some time, joan solution worked and by adding a time out to the while it got fixed – Mahdi Aug 18 '17 at 20:37
2

The bug is in the following lines.

# wait for ping echo
while GPIO.input(pin)==0:
  starttime = time.process_time()
while GPIO.input(pin)==1:
  endtime = time.process_time()

You should timeout both whiles.

Otherwise occasionally the echo will have come and gone by the time the first while is executed which means it will spin on pin is 0 for eternity.

  • This doesn't solve the issue. The infinite while loop may be averted, but you will still get back an incorrect sensor reading, which could go on for multiple readings. – Ctpelnar1988 Apr 5 '18 at 4:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.