Menu

#181 wait_for_edge() not working when running program second time.

New
nobody
None
Medium
Defect
2020-06-19
2020-06-19
Ivo
No

I might have come accross an issue with the wait_for_edge function. I used the following project as basis, but changed it to use the wait_for_edge() function: https://tutorials-raspberrypi.com/raspberry-pi-ultrasonic-sensor-hc-sr04/

It seem to work, but only the first time. If I run the code the second time, it always fails. If I run it a third time, it works again. The funny part is, when I remove the GPIO.cleanup(), it always works! Am I doing somehting wrong or could this be an issue with RPi.GPIO? Below my code and the output from 2 runs in a row:

#! /usr/bin/python3

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(True)

TRIG = 23
ECHO = 24

GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)

GPIO.output(TRIG, False)
print(Waiting a few seconds for the sensor to settle)
time.sleep(2)

GPIO.output(TRIG, True)
time.sleep(0.00001)
GPIO.output(TRIG, False)

channel = GPIO.wait_for_edge(ECHO, GPIO.RISING, timeout=5000)
if channel is None:
print(Timeout occured, echo never started)
else:
pulse_start = time.time()

channel = GPIO.wait_for_edge(ECHO, GPIO.FALLING, timeout=5000)
if channel is None:
print(Timeout occured, echo never stopped)
else:
pulse_end = time.time()

pulse_duration = pulse_end  pulse_start
distance = pulse_duration * 17165
distance = round(distance, 1)
print (Distance first time: , distance, in cm)

GPIO.cleanup()
Output from running the code:
>>> %Run Measure_Distance_Using_Ultra_Sound_HC-SR04_version2.py
Waiting a few seconds for the sensor to settle
Distance first time: 12.1 in cm
>>> %Run Measure_Distance_Using_Ultra_Sound_HC-SR04_version2.py
Waiting a few seconds for the sensor to settle
Timeout occured, echo never started
Timeout occured, echo never stopped
Traceback (most recent call last):
File “/home/pi/Measure_Distance_Using_Ultra_Sound_HC-SR04_version2.py”, line 35, in
pulse_duration = pulse_end – pulse_start
NameError: name ‘pulse_end’ is not defined

Discussion


Log in to post a comment.