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

Beginners • Re: Rpi 5 and HC-SRO4

$
0
0
The Raspberry Pi 5 and HC-SR04 Works with this:

Code:

import gpiodimport time# Setupchip = gpiod.Chip('gpiochip0')  # This accesses the first GPIO chip on the Pitrig_line = chip.get_line(17)   # Replace with your trigger pin numberecho_line = chip.get_line(18)   # Replace with your echo pin number# Configure the linestrig_line.request(consumer="trig", type=gpiod.LINE_REQ_DIR_OUT)echo_line.request(consumer="echo", type=gpiod.LINE_REQ_DIR_IN)# Function to measure distance in cmdef get_distance():    # Trigger the sensor    trig_line.set_value(1)    time.sleep(0.00001)  # 10 µs pulse    trig_line.set_value(0)    # Wait for the echo response    start_time = time.time()    while echo_line.get_value() == 0:        start_time = time.time()    while echo_line.get_value() == 1:        stop_time = time.time()    # Calculate distance in cm    time_elapsed = stop_time - start_time    distance_cm = (time_elapsed * 34300) / 2  # Sound speed is 34300 cm/s    return distance_cm# Function to convert cm to feet and inchesdef get_distance_in_feet():    # Trigger the sensor and get distance in cm    distance_cm = get_distance()  # Assuming get_distance() returns cm    distance_ft = distance_cm / 30.48  # Convert to feet    # Split into whole feet and fractional feet    feet = int(distance_ft)  # Whole feet    fractional_feet = distance_ft - feet  # Fractional part    inches = fractional_feet * 12  # Convert fraction of a foot to inches    return feet, inches# Main loop to print the distance in feet and incheswhile True:    feet, inches = get_distance_in_feet()    print(f"Distance: {feet} feet and {inches:.2f} inches")    time.sleep(1)/code]        Steve

Statistics: Posted by sismith1 — Fri Sep 06, 2024 11:53 pm



Viewing all articles
Browse latest Browse all 3843

Trending Articles