1

I want to get distance continuously using while loop but a few minutes later my code suddenly stops working and doesn't get distance (there is None value in distance variable) I have changed first time.sleep(0.01) to time.sleep(1) and to other seconds but It is still same with others.

I am using RPi 3 b+, Raspbian, Python3, HC-SR04 and 1K, 2K resistors.

I connect ultrasonic sensor to RPi using this tutorial from MODMYPI: HC-SR04 Ultrasonic Range Sensor on the Raspberry Pi

and here is my code:

import RPi.GPIO as GPIO
import time

try:
    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)

    TRIG = 23
    ECHO = 24

    while True:
        GPIO.setup(TRIG,GPIO.OUT)
        GPIO.setup(ECHO,GPIO.IN)

        GPIO.output(TRIG,False)

        time.sleep(0.01)

        GPIO.output(TRIG,True)

        time.sleep(0.00001)

        GPIO.output(TRIG,False)

        while GPIO.input(ECHO) == 0:
            pulse_start = time.time()

        while GPIO.input(ECHO) == 1:
            pulse_end = time.time()

        pulse_duration = pulse_end - pulse_start
        distance = pulse_duration * 17000
        distance = round(distance, 2)

        print(distance)
except:
    GPIO.cleanup()
2

I would suggest 2 changes. Firstly it is possible that the program can get stuck in the while loops so add a timeout. Secondly initialise the pulse_start and pulse_end variables incase the while loops don't get entered. This could be improved to ignore results where the timeout has been used.

import RPi.GPIO as GPIO
import time

try:
    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)

    TRIG = 23
    ECHO = 24
    maxTime = 0.04

    while True:
        GPIO.setup(TRIG,GPIO.OUT)
        GPIO.setup(ECHO,GPIO.IN)

        GPIO.output(TRIG,False)

        time.sleep(0.01)

        GPIO.output(TRIG,True)

        time.sleep(0.00001)

        GPIO.output(TRIG,False)

        pulse_start = time.time()
        timeout = pulse_start + maxTime
        while GPIO.input(ECHO) == 0 and pulse_start < timeout:
            pulse_start = time.time()

        pulse_end = time.time()
        timeout = pulse_end + maxTime
        while GPIO.input(ECHO) == 1 and pulse_end < timeout:
            pulse_end = time.time()

        pulse_duration = pulse_end - pulse_start
        distance = pulse_duration * 17000
        distance = round(distance, 2)

        print(distance)
except:
    GPIO.cleanup()
  • Thank you so much I think it is works now thanks to your code!! Although I still don't understand your code perfectly but I will study it and understand perfectly. thank you so much again!! – allentando Mar 14 at 13:08

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.