July 25, 2024, 02:18
import RPi.GPIO as GPIO import time # Define GPIO pins TRIG = 24 ECHO = 18 def setup(): # Set up the GPIO mode GPIO.setmode(GPIO.BCM) # Set up TRIG as an output and ECHO as an input GPIO.setup(TRIG, GPIO.OUT) GPIO.setup(ECHO, GPIO.IN) # Ensure TRIG is set low initially GPIO.output(TRIG, False) print("Waiting for sensor to settle") time.sleep(2) def measure_distance(): # Send a 10us pulse to TRIG GPIO.output(TRIG, True) time.sleep(0.00001) GPIO.output(TRIG, False) # Wait for the ECHO to go high (start of the echo pulse) while GPIO.input(ECHO) == 0: pulse_start = time.time() # Wait for the ECHO to go low (end of the echo pulse) while GPIO.input(ECHO) == 1: pulse_end = time.time() # Calculate the duration of the pulse pulse_duration = pulse_end - pulse_start # Calculate the distance (speed of sound is 34300 cm/s) distance = pulse_duration * 34300 / 2 return distance def cleanup(): GPIO.cleanup() if __name__ == "__main__": try: setup() while True: distance = measure_distance() print(f"Distance: {distance:.2f} cm") time.sleep(1) except KeyboardInterrupt: print("Measurement stopped by User") cleanup()