Table of Contents

LamaPLC: HC-SR04 Ultrasonic Sensor Module

HC SR04 Ultra-Sonic Ranger sensors
This solution has two components: a speaker that sends out sound pulses and a microphone that detects their reflections. The distance is computed from the time delay between emission and detection, assuming the speed of sound.

HC-SR04
The HC-SR04 ultrasonic sensor module is a widely used, affordable sensor popular among hobbyists for electronics projects with Arduino and Raspberry Pi, enabling non-contact distance measurement and obstacle detection. It uses sonar to measure distance by timing how long sound waves take to reflect back.

Key Specifications

If you'd like to support the development of the site with the price of a coffee — or a few — please do so here.

Here's a handy tip: you can quickly save this page as a PDF by clicking “export to PDF” in the menu on the right side of the screen.

2026/02/14 22:38

Arduino & HC-SR04

To operate the sensor, a microcontroller (like an Arduino) must provide a 10-microsecond (µS) high-level pulse to the Trig pin. The module then automatically sends out an 8-cycle burst of ultrasound at 40 kHz and raises the Echo pin to a high state. The duration of this high-level signal on the Echo pin is the time the sound waves took to travel to the object and back.

The distance can be calculated using the formula:
Distance in cm = (Duration of Echo pulse in µS / 58)

const int trigPin = 9;
const int echoPin = 10;
 
float duration, distance;
 
void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Serial.begin(9600);
}
 
void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
 
  duration = pulseIn(echoPin, HIGH);
  distance = (duration*.0343)/2;
  Serial.print("Distance: ");
  Serial.println(distance);
  delay(100);
}

This page has been accessed for: Today: 1, Until now: 17