How To Connect

diagram
  1. Connect the VCC of Ultrasonic Sensor to 5V PWR pin of Raspberry Pi
  2. Connect the TRIG pin of Ultrasonic Sensor to GPIO 18 of Raspberry Pi
  3. Connect the GND of Ultrasonic Sensor to Ground of Raspberry Pi
  4. Connect the ECHO pin of Ultrasonic Sensor to 1k Resistor
  5. Connect the 1k Resistor pin, which is connected to GPIO 24, to Ground
  6. Connect the 2k Resistor pin, which is connected to 1k Resistor, to Ground

After completing these steps, you can change the position of the object and observe the result in the display.

Connections Logs

    Raspberry Pi
    1k Resistor
    2k Resistor
    Ultrasonic Sensor
    Object
    Hover over a component to see its description.

    CONNECTOR INFO
            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()