After completing these steps, you can change the position of the object and observe the result in the display.
import RPi.GPIO as GPIO
import time
# Set GPIO mode
GPIO.setmode(GPIO.BCM)
# Define GPIO pins
trig_pin = 18
echo_pin = 24
# Setup GPIO pins
GPIO.setup(trig_pin, GPIO.OUT)
GPIO.setup(echo_pin, GPIO.IN)
# Trigger pulse function
def send_trigger_pulse():
GPIO.output(trig_pin, True)
time.sleep(0.00001)
GPIO.output(trig_pin, False)
# Wait for echo function
def wait_for_echo(value, timeout):
count = timeout
while GPIO.input(echo_pin) != value and count > 0:
count -= 1
# Calculate distance function
def get_distance():
send_trigger_pulse()
wait_for_echo(True, 10000)
start_time = time.time()
wait_for_echo(False, 10000)
end_time = time.time()
pulse_duration = end_time - start_time
distance = pulse_duration * 17150 # Speed of sound is approximately 343 meters/second
distance = round(distance, 2)
return distance
# Main loop
try:
while True:
distance = get_distance()
print(f"Distance: {distance} cm")
time.sleep(1)
except KeyboardInterrupt:
GPIO.cleanup()