Connecting an [ultrasonic sensor](https://www.onzuu.com/category/ultrasonic-receivers-transmitters) (like the common [HC-SR04](https://www.ampheo.com/product/hc-sr04-26835950)) to a [Raspberry Pi](https://www.ampheo.com/c/raspberry-pi/raspberry-pi-boards) is a classic project for measuring distance. Here's a complete guide. ![hc-sr04-tut-8_1024x1024](https://hackmd.io/_uploads/HyqzHR4Axe.jpg) **Components Needed** * Raspberry Pi (any model with GPIO pins) * HC-SR04 Ultrasonic Sensor (the most common type) * [Breadboard](https://www.onzuu.com/category/solderless-breadboards) (optional but recommended) * [Jumper Wires](https://www.onzuu.com/category/jumper-wire) (Female-to-Female if connecting directly to the Pi) **How the HC-SR04 Sensor Works** 1. You send a short 10µs pulse to the Trigger pin. 2. The [sensor](https://www.ampheo.com/c/sensors) sends out an 8-cycle ultrasonic burst (40kHz). 3. The sensor sets the Echo pin HIGH. 4. The Echo pin stays high for the exact amount of time it takes for the sound wave to travel to the object and back. 5. You measure the duration the Echo pin is HIGH. You then calculate the distance using the speed of sound (~343 m/s or 34300 cm/s). **Formula:** Distance = (Time Echo was High * Speed of Sound) / 2 We divide by 2 because the time is for the round trip (to the object and back). **Wiring Diagram** The HC-SR04 operates at 5V, but the Raspberry Pi's GPIO pins are 3.3V tolerant and can be damaged by 5V. Therefore, we must handle the Echo pin carefully. Important: Never connect the sensor's 5V output directly to a Pi GPIO pin. Here are two safe wiring methods: **Method 1: Simple Voltage Divider (for Echo Pin) - Most Common** This method uses two resistors to lower the 5V Echo signal to a safe 3.3V. Connections: ![企业微信截图_20251021173109](https://hackmd.io/_uploads/HyMl7AV0ee.png) **Building the Voltage Divider:** * Connect the HC-SR04 Echo pin to a breadboard. * Connect a 1kΩ [resistor](https://www.onzuu.com/category/resistors) from the Echo line to the GPIO 24 line. * Connect a 2kΩ resistor from the GPIO 24 line to Ground. This will scale the 5V signal down to ~3.3V, making it safe for the Pi. ``` text HC-SR04 Echo | | 1kΩ Resistor | +-----> To RPi GPIO 24 | 2kΩ Resistor | GND ``` **Method 2: Direct Connection with Level Shifter (Recommended for Reliability)** For a more robust solution, use a logic level converter (bidirectional). ![企业微信截图_20251021173217](https://hackmd.io/_uploads/rkwNm0NRee.png) **Python Code Example** Here is a Python script using the RPi.GPIO library. This code uses the wiring from Method 1. 1. Enable SSH on your Pi and connect to it remotely, or open a terminal on the Pi itself. 2. Create a new file, for example: nano ultrasonic_sensor.py 3. Copy and paste the following code: ``` python #!/usr/bin/env python3 import RPi.GPIO as GPIO import time # Set the GPIO modes GPIO.setmode(GPIO.BCM) # Define GPIO pins GPIO_TRIGGER = 23 GPIO_ECHO = 24 # Set pin direction GPIO.setup(GPIO_TRIGGER, GPIO.OUT) GPIO.setup(GPIO_ECHO, GPIO.IN) def distance(): # Set Trigger to HIGH GPIO.output(GPIO_TRIGGER, True) # Wait 10µs and set Trigger back to LOW time.sleep(0.00001) # 10 microseconds GPIO.output(GPIO_TRIGGER, False) start_time = time.time() stop_time = time.time() # Save the start time (when the Echo pin becomes HIGH) # Wait for the echo pin to go high, but timeout after 0.1 seconds timeout = time.time() + 0.1 while GPIO.input(GPIO_ECHO) == 0: start_time = time.time() if start_time > timeout: print("Error: Sensor not responding (start time)") return -1 # Save the stop time (when the Echo pin becomes LOW again) # Wait for the echo pin to go low, but timeout after 0.1 seconds timeout = time.time() + 0.1 while GPIO.input(GPIO_ECHO) == 1: stop_time = time.time() if stop_time > timeout: print("Error: Sensor not responding (stop time)") return -1 # Calculate time difference time_elapsed = stop_time - start_time # Calculate distance using the speed of sound (34300 cm/s) # Divide by 2 because the sound traveled to the object and back distance = (time_elapsed * 34300) / 2 return distance if __name__ == '__main__': try: while True: dist = distance() if dist != -1: # Only print if measurement was successful print("Measured Distance = {:.1f} cm".format(dist)) time.sleep(1) # Reset by pressing CTRL + C except KeyboardInterrupt: print("Measurement stopped by User") GPIO.cleanup() ``` 4. Save the file (Ctrl+X, then Y, then Enter). 5. Run the script with superuser privileges: ``` bash sudo python3 ultrasonic_sensor.py ``` You should now see distance measurements in centimeters printed every second. Press Ctrl+C to stop the script. **Troubleshooting Common Issues** * **-1 or "Sensor not responding" error:** * Check your wiring! This is the most common cause. Ensure the Echo and Trigger pins are correct. * Ensure the voltage divider is correctly built for the Echo pin. * The sensor might be too far from an object. Try pointing it at a closer wall. * **Consistently incorrect readings:** * The speed of sound changes with temperature and humidity. For high precision, you would need to factor this in. * There might be acoustic interference from other surfaces. * **Script fails to run with "No module named 'RPi'":** * Ensure you are using a [Raspberry Pi](https://www.ampheoelec.de/c/raspberry-pi/raspberry-pi-boards) OS. * Install the library if it's missing: sudo apt update && sudo apt install python3-rpi.gpio **Summary** 1. Wire Safely: Always use a voltage divider or level shifter for the Echo pin. 2. Trigger Pin: Send a precise 10µs pulse. 3. Echo Pin: Measure the duration of the HIGH pulse accurately. 4. Calculate: Use the formula Distance = (pulse_duration * speed_of_sound) / 2. This setup is perfect for robotics, object detection, and simple automation projects!