Tutorial

Lesson 3 โ€” Ultrasonic Sensor (HC-SR04)

Lesson 3 โ€” Ultrasonic Distance Sensor ๐Ÿ“

๐Ÿง  Concept

Use sound pulses to measure distance. We send a TRIG pulse and time the ECHO response.

๐Ÿ’ก Great for obstacle detection in robots.

๐Ÿ” What is an ultrasonic sensor?

The HC-SR04 emits ultrasonic waves (~40 kHz) and listens for the echo. Time ร— speed of sound = distance.

๐Ÿงญ Wiring guide

HC-SR04 Wiring Diagram

  • VCC โ†’ 5V (Arduino) / 5V (use level shifting for Pi) / 5V (ESP32 OK; Echo needs 3.3V protection)
  • GND โ†’ GND
  • TRIG โ†’ digital pin
  • ECHO โ†’ digital pin (Pi/ESP32: use a voltage divider to 3.3V)
โš ๏ธ Raspberry Pi & ESP32 are 3.3V devices. Use a resistor divider on ECHO.

๐Ÿ’ป Code (Arduino C/C++)

// HC-SR04 distance on Arduino
const int TRIG = 9;
const int ECHO = 10;

void setup() {
  Serial.begin(9600);
  pinMode(TRIG, OUTPUT);
  pinMode(ECHO, INPUT);
}

long microsecondsToCm(long us){ return us / 29 / 2; }

void loop() {
  digitalWrite(TRIG, LOW); delayMicroseconds(2);
  digitalWrite(TRIG, HIGH); delayMicroseconds(10);
  digitalWrite(TRIG, LOW);

  long duration = pulseIn(ECHO, HIGH, 30000UL); // timeout 30ms (~5m)
  if(duration == 0){ Serial.println("Out of range"); delay(200); return; }
  long cm = microsecondsToCm(duration);
  Serial.print("Distance: "); Serial.print(cm); Serial.println(" cm");
  delay(200);
}

๐Ÿ Code (Raspberry Pi โ€“ Python)

# HC-SR04 on Raspberry Pi (RPi.GPIO)
import RPi.GPIO as GPIO, time

TRIG, ECHO = 23, 24  # BCM pins
GPIO.setmode(GPIO.BCM)
GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)
GPIO.output(TRIG, False)
time.sleep(0.2)

def get_distance_cm():
    GPIO.output(TRIG, True); time.sleep(0.00001)
    GPIO.output(TRIG, False)

    t_start = time.time()
    while GPIO.input(ECHO) == 0:
        t_start = time.time()
    while GPIO.input(ECHO) == 1:
        t_end = time.time()

    elapsed = t_end - t_start
    return (elapsed * 34300) / 2  # speed of sound cm/s

try:
    while True:
        d = get_distance_cm()
        print(f"Distance: {d:.1f} cm")
        time.sleep(0.2)
except KeyboardInterrupt:
    GPIO.cleanup()

โšก Code (ESP32 โ€“ MicroPython)

# HC-SR04 on ESP32 (MicroPython)
from machine import Pin, time_pulse_us
import time

TRIG = Pin(5, Pin.OUT)
ECHO = Pin(18, Pin.IN)

def distance_cm():
    TRIG.off(); time.sleep_us(2)
    TRIG.on(); time.sleep_us(10)
    TRIG.off()
    us = time_pulse_us(ECHO, 1, 30000)  # wait for HIGH
    if us <= 0: 
        return None
    return (us * 0.0343) / 2

while True:
    d = distance_cm()
    if d is None:
        print("Out of range")
    else:
        print("Distance:", round(d,1), "cm")
    time.sleep(0.2)

๐Ÿงช Try this: LED trigger < 10 cm

// Add to Arduino setup:
pinMode(13, OUTPUT);

// Add in loop after computing 'cm':
digitalWrite(13, (cm < 10) ? HIGH : LOW);
๐Ÿ’ก On Pi/ESP32, control an LED pin when distance < 10 cm. Same idea!

๐Ÿ–จ๏ธ Worksheet โ€” Measure & Record Distances

  • [ ] Table of 10 readings at different ranges
  • [ ] Compute average and note any outliers
  • [ ] Explain why soft materials reflect poorly
  • [ ] Bonus: change sample rate to 5 Hz and 2 Hz
RoboRider Labs โ€ข Classroom Lesson 3