Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 5471

Python • Re: HC-SR04 ultrasonic sensor

$
0
0
Okay, thank you for your help and for being nice. I tried running the snippet below and it doesn't work the best either, it takes sometimes so long to print the new value (like 5 seconds). I connected the echo pin using a voltage divider with the values R1 = 1000 ohms, R2 = 2000 ohms to my rpi 4B.

Code:

#main.pyimport timeimport RPi.GPIO as GPIOdef main():    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    while True:        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:            pulse_start_time = time.time()        while GPIO.input(ECHO_PIN) == 1:            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                print(distance)        time.sleep(1)main()

Statistics: Posted by mart1nek — Thu Dec 21, 2023 11:46 pm



Viewing all articles
Browse latest Browse all 5471

Trending Articles