How to Build a Raspberry Pi Ultrasonic Distance Monitor with HC-SR04 and OpenClaw
The HC-SR04 ultrasonic sensor measures distance from 2 cm to 400 cm for under $3, making it the default starter sensor for Raspberry Pi projects. Most tutorials stop at printing a single reading to the terminal. This guide covers the full hardware wiring with a voltage divider, a Python measurement script with median filtering, and an OpenClaw agent that runs continuous proximity monitoring with threshold alerts, trend detection, and anomaly logging.
Why Most HC-SR04 Tutorials Stop Too Early
Raspberry Pi shipped 7.6 million units in FY 2025, a 25% revenue jump to $323.2 million, and for the first time semiconductor device volumes exceeded boards and modules. The Pi is moving from hobbyist breadboard to production sensor platform. But the tutorials have not caught up.
Search for "raspberry pi ultrasonic sensor" and you get dozens of guides that wire an HC-SR04, run a Python script, print a distance to the terminal, and stop. The sensor measures a distance. The script prints a number. The tutorial ends.
Real distance monitoring needs more than a single read. A garage parking assistant needs to track the vehicle continuously as it approaches the wall. A tank level monitor needs to log readings over time and flag abnormal drops. A security perimeter sensor needs threshold alerts when something enters range and context about whether the detection is new or ongoing. These are not hard problems individually, but they require a loop, a state tracker, and decision logic that adapts over time.
OpenClaw fills this gap by adding a reasoning layer on the same Raspberry Pi. The Pi is not running the language model itself. It acts as a gateway: reading the sensor, forwarding observations to a cloud LLM like Claude or GPT-4, and executing the response. The agent decides when a reading is routine (log it) versus interesting (alert on it), adjusts polling frequency based on conditions, and builds a history of readings that makes anomaly detection possible.
This guide covers the full path from bare hardware to intelligent monitoring: wiring the HC-SR04 with a proper voltage divider, writing a Python measurement script with median filtering, installing OpenClaw, and building an agent that watches distance continuously with threshold alerts and logging.
How to Wire the HC-SR04 to Raspberry Pi GPIO Pins
The HC-SR04 is a $2-3 ultrasonic distance sensor that sends a 40 kHz sound pulse and times the echo return. It measures distances from 2 cm to 400 cm with ±3 mm accuracy, draws 15 mA at idle and up to 25 mA during measurement, and operates on a 5V supply. The effective beam angle is about 15 degrees, so it measures the distance to whatever is directly in front of the transducer pair.
The sensor has four pins: VCC (5V power), TRIG (trigger input), ECHO (echo output), and GND (ground).
Wiring to Raspberry Pi GPIO:
- Connect VCC to Pin 2 (5V power) on the Pi
- Connect GND to Pin 6 (Ground)
- Connect TRIG to GPIO 23 (Pin 16). This pin sends the trigger pulse that starts a measurement
- Connect ECHO to GPIO 24 (Pin 18) through a voltage divider (see below). Do not connect ECHO directly to the Pi
The voltage divider is not optional. The ECHO pin outputs a 5V signal when the sensor detects a return pulse. The Raspberry Pi's GPIO pins are rated for 3.3V. Feeding 5V into a GPIO pin can permanently damage the Pi. Place a 1 kΩ resistor between the HC-SR04's ECHO pin and GPIO 24, then a 2 kΩ resistor between GPIO 24 and GND. This drops the echo signal to approximately 3.33V, calculated as 5V × 2000 / (1000 + 2000). If you do not have a 1 kΩ and 2 kΩ pair, a 330 Ω and 470 Ω combination also works (producing about 2.93V). Both are safe for the Pi's GPIO.
How the measurement cycle works:
The Pi sets GPIO 23 HIGH for 10 microseconds, which triggers the sensor. The HC-SR04 emits eight 40 kHz pulses and then raises the ECHO pin HIGH. The ECHO pin stays HIGH until the reflected pulse returns to the sensor. The Pi measures how long the ECHO pin remains HIGH. That duration, combined with the speed of sound, gives the distance.
The formula: distance in centimeters = pulse duration in seconds × 17150. This comes from the speed of sound at roughly 343 m/s (34,300 cm/s) at 20°C, divided by 2 because the sound travels to the target and back. Temperature affects accuracy: sound travels about 0.6 m/s faster per degree Celsius. At 30°C the speed is roughly 349 m/s. For indoor use between 15°C and 30°C, the uncorrected formula introduces less than 2% error.
Python Script for Distance Measurement
This script reads distance from the HC-SR04 using the RPi.GPIO library, which comes pre-installed on Raspberry Pi OS:
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)
def measure_distance():
GPIO.output(TRIG, True)
time.sleep(0.00001)
GPIO.output(TRIG, False)
timeout = time.time() + 0.04
start = time.time()
stop = time.time()
while GPIO.input(ECHO) == 0:
start = time.time()
if start > timeout:
return -1
while GPIO.input(ECHO) == 1:
stop = time.time()
if stop > timeout:
return -1
pulse_duration = stop - start
distance_cm = pulse_duration * 17150
return round(distance_cm, 2)
def measure_median(samples=5, delay=0.06):
readings = []
for _ in range(samples):
d = measure_distance()
if d > 0:
readings.append(d)
time.sleep(delay)
if not readings:
return -1
readings.sort()
return readings[len(readings) // 2]
try:
distance = measure_median()
print(f"{distance}")
finally:
GPIO.cleanup()
The measure_distance function triggers the sensor and times the echo pulse. A 40 ms timeout guard prevents infinite loops when the sensor fails to receive an echo (target out of range or sensor disconnected). The 40 ms ceiling covers the maximum round trip for a 400 cm target.
The measure_median function takes five readings with 60 ms spacing and returns the middle value. Ultrasonic sensors occasionally return garbage readings from stray reflections, air currents, or electrical noise. A single read might report 15.2 cm one moment and 312.7 cm the next. Taking the median of five samples filters these outliers without the complexity of a rolling average. Readings that return -1 (timeouts) are discarded before sorting.
Save this as distance.py in a location the OpenClaw agent can access (your home directory works). The script prints a single number to stdout, which is how OpenClaw agents consume hardware data: they call a system command and read the output.
Installing OpenClaw on the Raspberry Pi
OpenClaw runs on Raspberry Pi 4 or 5 with at least 2 GB of RAM (4 GB recommended). The Pi acts as a gateway, not an inference engine. Language model reasoning happens through API calls to providers like Anthropic (Claude) or OpenAI (GPT-4), so the Pi's own processing power is not the bottleneck.
Start with 64-bit Raspberry Pi OS Lite flashed via the official Raspberry Pi Imager. Connect via SSH and install Node.js (version 22 or later) through NodeSource. The OpenClaw installer sets up the agent daemon as a systemd user service that starts automatically on boot. Enable user lingering so the service runs even without an active SSH session.
Install the Adafruit Blinka library to give Python access to GPIO pins through a CircuitPython compatibility layer. For the HC-SR04 script above, the built-in RPi.GPIO library handles everything. But Blinka becomes valuable when you add sensors later (temperature, humidity, light) that have existing CircuitPython drivers with consistent APIs.
Configure a notification channel so the agent can send alerts. Telegram works well for headless Pi deployments: messages reach your phone instantly with no additional infrastructure beyond a bot token. The OpenClaw setup process includes guided configuration for messaging channels.
For storage, consider a USB SSD instead of the SD card if your agent will log readings frequently. An agent recording distance every 30 seconds generates thousands of small writes daily. SD cards degrade under sustained write loads. A 16 GB USB SSD costs $10-15 and lasts longer in write-heavy workloads.
For agents that need to persist and share sensor data beyond the Pi's local disk, Fast.io provides a free cloud workspace with 50 GB of storage, MCP server access at mcp.fast.io, and built-in AI search across uploaded files. No credit card required.
Store and query sensor logs from your Raspberry Pi
Fast.io gives your OpenClaw agent 50 GB of free cloud storage with MCP access and built-in AI search. Upload distance readings, share them with collaborators, and query historical data without setting up a database. No credit card required.
How to Build a Continuous Distance Monitoring Agent
With the sensor wired, the measurement script working, and OpenClaw installed, the next step is defining the agent behavior that turns one-shot reads into continuous monitoring.
The agent calls the distance.py script at a configurable interval (every 30 seconds for proximity monitoring, every 5 minutes for tank level tracking), evaluates each reading against its context, and decides what action to take.
Threshold alerts are the simplest monitoring mode. Define a distance threshold, say 50 cm, and the agent sends a Telegram notification whenever a reading drops below it. This covers garage parking assistants, security perimeter alerts, and inventory level warnings. The agent adds context that a raw threshold script cannot: it tracks whether the object just entered range (new event) or has been within range for the past ten readings (ongoing condition), and suppresses repeat notifications accordingly. No one wants 20 identical "object detected" messages in a row.
Trend detection uses a rolling window of recent readings to spot patterns. A water tank level that drops 2 cm per day suggests normal consumption. A drop of 10 cm in a single hour suggests a leak. A pellet hopper that empties 30% faster than the previous week suggests increased usage or a dispensing malfunction. The agent evaluates these trends through its cloud LLM reasoning, comparing current behavior against the recent baseline without requiring you to write custom statistical analysis code.
Anomaly logging catches events that do not match any predefined threshold but are still worth recording. A distance reading that jumps 50 cm and returns to normal in the next measurement could be a person walking through the beam, a bird, or sensor noise. The agent flags these deviations with timestamps and includes them in a periodic summary. Over weeks of operation, this log builds a behavioral baseline that makes future anomalies easier to classify.
Adaptive polling adjusts read frequency based on conditions. Quiet periods: one reading every 5 minutes to conserve power and storage. Active periods (object detected moving in and out of range): one reading every 10 seconds to capture the event in detail. The agent decides when to shift between modes based on its observations.
For single-sensor setups, local CSV files or a SQLite database on the Pi handle storage. But when you manage multiple Pis, need to share sensor logs with collaborators, or want to query historical data with natural language, a cloud workspace provides more flexibility. Fast.io workspaces accept uploads via the MCP server, and once Intelligence Mode indexes the files, you can ask questions like "what was the average distance reading last Tuesday afternoon" and get answers with citations from the raw logs.
Practical Applications and Sensor Calibration
The HC-SR04 paired with an OpenClaw agent covers a range of distance monitoring scenarios. Here are three that map directly to the threshold, trend, and anomaly detection modes described above.
Garage parking assistant: Mount the sensor on the wall facing the approaching vehicle. The agent monitors as the car pulls in, tracking distance readings as they decrease. A guidance zone between 150 cm and 30 cm triggers a "keep coming" status. Below 30 cm triggers a stop alert. The agent distinguishes between the car arriving (distance decreasing steadily) and someone walking past (distance drops briefly and returns), reducing false alerts compared to a simple proximity trigger.
Tank or bin level monitoring: Point the sensor downward into a water tank, grain bin, or pellet hopper. The sensor measures the distance from the top to the surface of the contents. As the level drops, the distance increases. The agent logs levels over time, detects abnormal consumption rates that suggest leaks or dispensing issues, and sends a refill alert when contents reach a configurable threshold.
Room occupancy detection: Place sensors at doorways to count entries and exits. Each person passing through produces a characteristic distance signature: a sharp drop as they enter the beam, a brief plateau at body distance (roughly 20-60 cm depending on doorway width), and a return to baseline as they pass. The agent counts these events and maintains a running occupancy estimate for the room.
Calibration tips for reliable readings:
- Mount the sensor at least 2 cm from any surface, since 2 cm is the minimum measurement distance
- Point the sensor perpendicular to the target. Angled surfaces reflect sound away from the transducer, producing incorrect or missing readings
- Avoid soft, sound-absorbing surfaces like fabric, foam, or heavy curtains. Hard, flat surfaces produce the cleanest echoes
- Test at your actual operating distance before committing to a deployment. Accuracy is best between 10 cm and 200 cm, and degrades as you approach the 400 cm maximum
- If you need readings beyond 400 cm, consider the JSN-SR04T (rated to 600 cm with a waterproof probe) or a time-of-flight laser sensor like the VL53L0X for millimeter precision at shorter ranges
For agents managing sensor data from multiple Raspberry Pi deployments, Fast.io workspaces serve as a central collection point. Each Pi's OpenClaw agent uploads logs to a shared workspace. Collaborators and other agents can query that data through Intelligence Mode, which auto-indexes uploaded files for semantic search without a separate vector database. Ownership transfer lets the agent that built and populated the workspace hand control to a human operator while retaining admin access for continued uploads.
Frequently Asked Questions
How do I connect an HC-SR04 ultrasonic sensor to a Raspberry Pi?
Connect VCC to Pin 2 (5V), GND to Pin 6, TRIG to GPIO 23 (Pin 16), and ECHO to GPIO 24 (Pin 18) through a voltage divider made from a 1 kΩ and 2 kΩ resistor. The voltage divider is required because the ECHO pin outputs 5V, which exceeds the Pi's 3.3V GPIO tolerance.
What is the range of the HC-SR04 with Raspberry Pi?
The HC-SR04 measures distances from 2 cm to 400 cm. Accuracy is best between 10 cm and 200 cm, with the datasheet rating ±3 mm across the full range. Beyond about 300 cm, readings become less reliable depending on the target surface and ambient conditions.
Do I need a voltage divider for HC-SR04 on Raspberry Pi?
Yes. The HC-SR04's ECHO pin outputs a 5V signal. Raspberry Pi GPIO pins are rated for 3.3V, and applying 5V directly can permanently damage the board. A simple voltage divider using a 1 kΩ resistor and 2 kΩ resistor drops the signal to a safe 3.33V. This is two inexpensive components and a few minutes of wiring, but skipping it risks destroying a GPIO pin or the entire Pi.
How accurate is the HC-SR04 ultrasonic sensor?
The datasheet rates accuracy at ±3 mm. In practice, accuracy depends on the target surface, temperature, and measurement distance. Hard, flat surfaces perpendicular to the sensor produce the most reliable readings. Soft or angled surfaces scatter the sound pulse and degrade accuracy. Taking the median of five readings filters out noise spikes and brings real-world performance close to the rated spec.
Can an OpenClaw agent read sensor data on Raspberry Pi?
OpenClaw agents interact with hardware through Python scripts executed as system commands. The agent calls a script that reads the sensor and prints the measurement to stdout. The agent then evaluates the reading, decides whether to log it, send an alert, or adjust polling frequency, and records the outcome. The Pi handles sensor I/O while the cloud LLM handles reasoning.
Related Resources
Store and query sensor logs from your Raspberry Pi
Fast.io gives your OpenClaw agent 50 GB of free cloud storage with MCP access and built-in AI search. Upload distance readings, share them with collaborators, and query historical data without setting up a database. No credit card required.