Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 37 ยท Sensors and Cameras

Distance and Motion Sensors

Measure distance with an HC-SR04 ultrasonic sensor and detect movement with a PIR sensor on the Raspberry Pi, with wiring, voltage divider and gpiozero code.

Two sensors let a Pi notice what is happening around it: an ultrasonic distance sensor that tells you how far away something is, and a PIR motion sensor that tells you that something warm just moved. Together they power robots that avoid walls, parking helpers, automatic lights and simple alarms. Both are inexpensive, and both have a small trap you need to know about: the voltage.

Ultrasonic distance: the HC-SR04

The HC-SR04 sends a short burst of ultrasound (40 kHz, too high for people to hear) and listens for the echo. The sensor measures the time between the burst and the echo. Sound travels at about 343 meters per second in air, and the pulse goes out and back, so:

distance = time * speed_of_sound / 2

The sensor has four pins: VCC (5 V), TRIG (trigger), ECHO and GND. You pulse TRIG for 10 microseconds and the sensor raises ECHO for as long as the sound took to return.

The HC-SR04 runs on 5 V and its ECHO output is 5 V. A GPIO pin accepts only 3.3 V. Connect ECHO through a voltage divider (for example 1 kilohm in series and 2 kilohm to ground, with the GPIO pin between them), or use a 3.3 V version of the sensor. Wiring ECHO straight to a pin can destroy it.

Wiring: VCC to 5 V (pin 2), GND to pin 6, TRIG to GPIO23 (pin 16), ECHO through the divider to GPIO24 (pin 18). The real code uses the DistanceSensor class (read-only):

Python
from gpiozero import DistanceSensor
from time import sleep

sensor = DistanceSensor(echo=24, trigger=23, max_distance=2)

while True:
    print(f"{sensor.distance * 100:.1f} cm")
    sleep(0.5)

distance is in meters. Events are available too: sensor.when_in_range and sensor.when_out_of_range run callbacks when something enters or leaves the threshold_distance.

The maths in code

The stand-in converts echo times to distances and shows how the temperature changes the speed of sound, which matters for precise work.

Python Stand-in: echo time to distance

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Noise and filtering

Ultrasonic readings jump: soft surfaces (clothes, curtains) absorb the sound and angled surfaces bounce it away. A median of several readings removes most outliers. This stand-in also decides when something is "too close".

Python Stand-in: median filter for distance

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The median stays near 101 cm even though two samples are garbage, while the mean is pulled far off.

PIR motion sensor

A passive infrared sensor detects changes in the infrared radiation a warm body gives off. It does not measure distance, it simply says "motion" or "no motion". It has three pins: VCC (5 V on most modules), OUT and GND. OUT is already 3.3 V on common boards, but check your datasheet before connecting. Two small potentiometers set the sensitivity and how long OUT stays high after motion; a jumper chooses a single or repeated trigger mode.

A PIR needs about 30 to 60 seconds to settle after power-up, during which readings are unreliable. Wire OUT to GPIO17 (pin 11). Real code (read-only):

Python
from gpiozero import MotionSensor
from signal import pause

pir = MotionSensor(17)
pir.when_motion = lambda: print("Motion detected!")
pir.when_no_motion = lambda: print("Quiet again")
pause()

You can also call pir.wait_for_motion() to block until something moves, or read pir.motion_detected.

A tiny motion logger

A motion logger records when events occurred. The stand-in feeds a list of simulated pin levels and records state changes with a timestamp, ignoring repeated "high" values, the same logic you would put in a callback.

Python Stand-in: motion event log

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Putting them together

An automatic night light: when the PIR reports motion and the room is dark, turn on a PWM LED for a minute. A parking aid: change the beep speed with the distance. Both are just combinations of the pieces you already know: inputs, events and outputs. For the full wiring of a project like this, see the course chapters on Projects.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the HC-SR04's ECHO pin need a voltage divider?

    A 5 V signal on a GPIO pin can damage the Pi.
  2. 2. In the distance formula, why do you divide the echo time by 2?

    The measured time covers the trip out and back, so the one-way distance is half.
  3. 3. What does a PIR sensor detect?

    PIR means passive infrared; it reports motion, not distance.
  4. 4. Why use a median of several distance readings?

    A median is not pulled off by one or two wild readings.

Summary

  • The HC-SR04 measures distance from echo time; divide by two and protect the GPIO with a voltage divider.
  • Filter ultrasonic readings with a median.
  • A PIR sensor reports motion only, needs a settle time, and works well with MotionSensor events.
  • Combine inputs and outputs to build alarms, lights and parking aids.

Next: Analog Sensors and the ADC