Ultrasonic Sensor Raspberry Pi

 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

Raspbery Pi
Raspberry Pi Pinout Diagram


Pin Diagram Ultrasonic Sensor
Pinout Diagram Ultrasonic Sensor HC-SR04

Diveder
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

  1. TRIG pin sends ultrasonic pulse
  2. Pulse travels through air
  3. Hits object and reflects back
  4. ECHO pin receives reflected signal
  5. Time difference is measured
  6. 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

  1. Import GPIO and time libraries
  2. Define TRIG and ECHO pins
  3. Set TRIG as output and ECHO as input
  4. Send short pulse from TRIG
  5. Wait for ECHO response
  6. Measure pulse duration
  7. Calculate distance using formula
  8. Display result
  9. 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.

തുടക്കക്കാർക്കായുള്ള ഇലക്ട്രോണിക്സ് ലളിതമായി പഠിക്കാം.

Empowering students in Kerala with hands-on technical skills.