1. Introduction
The ultrasonic sensor (HC-SR04) is used to measure distance using sound waves. It sends ultrasonic pulses and measures the time taken for the echo to return. This is widely used in robotics, obstacle detection, and automation.
2. Components
- Raspberry Pi
- Ultrasonic Sensor (HC-SR04)
- Resistors (1kΩ and 2kΩ for voltage divider)
- Breadboard
- Jumper Wires
3. Circuit and connections
| Raspberry Pi Pinout Diagram |
| Pinout Diagram Ultrasonic Sensor HC-SR04 |

Voltage Divider For Raspberry Pi Protection
Connections:
- VCC → 5V (Pin 2)
- GND → GND (Pin 6)
- TRIG → GPIO23 (Pin 16)
- ECHO → GPIO24 (Pin 18) (via voltage divider)
⚠️ Note: Use voltage divider for ECHO (5V → 3.3V safe for Raspberry Pi)
4. Detailed Step By Step Circuit working
- TRIG pin sends ultrasonic pulse
- Pulse travels through air
- Hits object and reflects back
- ECHO pin receives reflected signal
- Time difference is measured
- Distance is calculated using speed of sound
5. Libraries to be included
import RPi.GPIO as GPIO
import time
6. Code
import RPi.GPIO as GPIO
import time
TRIG = 23
ECHO = 24
GPIO.setmode(GPIO.BCM)
GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)
while True:
GPIO.output(TRIG, False)
time.sleep(0.5)
GPIO.output(TRIG, True)
time.sleep(0.00001)
GPIO.output(TRIG, False)
while GPIO.input(ECHO) == 0:
pulse_start = time.time()
while GPIO.input(ECHO) == 1:
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 17150
distance = round(distance, 2)
print("Distance:", distance, "cm")
time.sleep(1)
7. Detailed Step By Step Code working
- Import GPIO and time libraries
- Define TRIG and ECHO pins
- Set TRIG as output and ECHO as input
- Send short pulse from TRIG
- Wait for ECHO response
- Measure pulse duration
- Calculate distance using formula
- Display result
- Repeat continuously
8. Tips
- Always use voltage divider for ECHO
- Keep sensor stable and straight
- Avoid soft surfaces (poor reflection)
- Use delay for accurate readings
9. Uses
- Distance measurement
- Obstacle avoidance robots
- Water level monitoring
- Parking assistance systems
10. Conclusion
The ultrasonic sensor is a powerful tool for distance measurement. This project helps in building smart sensing and automation systems using Raspberry Pi.