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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#! /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_endpulse_start
NameError: namepulse_endis not defined

Discussion


Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.