Lost + Found HC-SR04 ultrasonic distance sensor library for Raspberry Pi Pico C SDK
  • C 69.5%
  • CMake 19.7%
  • Python 10.8%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
2026-08-05 13:02:39 -07:00
include Initial commit 2026-08-05 12:57:29 -07:00
src Initial commit 2026-08-05 12:57:29 -07:00
.gitignore Initial commit 2026-08-05 12:57:29 -07:00
CMakeLists.txt Initial commit 2026-08-05 12:57:29 -07:00
conanfile.py Initial commit 2026-08-05 12:57:29 -07:00
example.c Fix example.c double-triggering issue 2026-08-05 13:02:39 -07:00
pico_sdk_import.cmake Initial commit 2026-08-05 12:57:29 -07:00
README.md Initial commit 2026-08-05 12:57:29 -07:00

🔌 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 Echo pin output can be connected directly to the digital inputs (like GP15) 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);
    }
}