Hello, I am a total newbie to rpi and python and I would like to use HC-SR04 ultrasonic sensor in my project. I understand how the sensor works, but cannot make it work properly. I want to have function called ping() that will be called from other function what is called in main.py and ping() should return new meassured distance every run. If I run my function separatly in while loop, it works, but otherwise not. My code:
Code: Select all
import RPi.GPIO as GPIO
import time
last_distance = 0
def do_something():
distance = ping()
print(distance)
return_this = [(1,2),(2,1)]
return return_this
def ping():
global last_distance
GPIO.setmode(GPIO.BOARD)
TRIG_PIN = 7
ECHO_PIN = 11
GPIO.setup(TRIG_PIN, GPIO.OUT)
GPIO.setup(ECHO_PIN, GPIO.IN)
pulse_start_time = 0
pulse_end_time = 0
try:
GPIO.output(TRIG_PIN, GPIO.LOW)
time.sleep(2E-6)
GPIO.output(TRIG_PIN, GPIO.HIGH)
time.sleep(10E-6)
GPIO.output(TRIG_PIN, GPIO.LOW)
while GPIO.input(ECHO_PIN) == 0:
pass
pulse_start_time = time.time()
while GPIO.input(ECHO_PIN) == 1:
pass
pulse_end_time = time.time()
pulse_duration = pulse_end_time - pulse_start_time
distance = round(pulse_duration * 17150, 2)
if distance > 300 or distance <= 0:
distance = last_distance
else:
last_distance = distance
return distance
except Exception as e:
print(f"Error in ping function: {e}")