Lost + Found HC-SR04 ultrasonic distance sensor library for Raspberry Pi Pico C SDK
- C 69.5%
- CMake 19.7%
- Python 10.8%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
| include | ||
| src | ||
| .gitignore | ||
| CMakeLists.txt | ||
| conanfile.py | ||
| example.c | ||
| pico_sdk_import.cmake | ||
| README.md | ||
🔌 Lost + Found HC-SR04 Ultrasonic Distance Sensor Driver
This driver provides a simple, hardware-independent interface for the HC-SR04 ultrasonic distance sensor module on the Raspberry Pi Pico 2 (RP2350).
🎛️ Hardware Description & Specifications
The HC-SR04 uses ultrasonic waves (sound at 40 kHz) to determine the distance to an object. It works by sending an acoustic pulse (trigger) and measuring the time it takes for the echo to bounce back to the receiver.
📐 Sensor Characteristics & Tentative Specifications
- Operating Voltage: 5V (from VBUS on the Pico)
- Measurement Angle: < 15 degrees
- Detection Distance/Range: 2 cm to 400 cm
- Accuracy: Up to 3 mm deviation under ideal conditions
- 5V Tolerance: Because the Raspberry Pi Pico 2 GPIO pins are 5V tolerant when powered, the sensor's
Echopin output can be connected directly to the digital inputs (likeGP15) without level shifters.
🔌 Wiring Diagram (Pico 2)
| Sensor Pin | Pico 2 GPIO Pin | Pico 2 Physical Pin | Notes |
|---|---|---|---|
| VCC | VBUS | Pin 40 | Power input (5V from USB). |
| Trig | GP14 | Pin 19 | Trigger output from Pico (3.3V logic level). |
| Echo | GP15 | Pin 20 | Echo input to Pico (5V logic, safe on Pico 2 digital GPIO). |
| GND | GND | Pin 38 (or any GND) | Common ground reference. |
🚀 Usage Example
#include "pico/stdlib.h"
#include "lf_hcsr04.h"
#include <stdio.h>
#define TRIG_PIN 14
#define ECHO_PIN 15
int main() {
stdio_init_all();
lf_hcsr04_t sensor;
if (!lf_hcsr04_init(&sensor, TRIG_PIN, ECHO_PIN)) {
printf("Failed to initialize HC-SR04 driver\n");
return -1;
}
while (true) {
float distance_cm = lf_hcsr04_read_distance_cm(&sensor);
if (distance_cm >= 0.0f) {
printf("Distance: %.2f cm\n", distance_cm);
} else {
printf("Measurement error: %.1f\n", distance_cm);
}
sleep_ms(500);
}
}