HC-SR04 Ultrasonic Reference
An ultrasonic distance sensor that measures distance by timing the echo of a sound pulse.
Pin names
| Name | Description |
|---|---|
| VCC | Power (5V) |
| TRIG | Trigger — send a short HIGH pulse to start a measurement |
| ECHO | Echo — goes HIGH for the duration of the sound's round trip |
| GND | Ground |
Attributes
This component has no configurable attributes.
Usage
Connect VCC to 5V, GND to GND, TRIG to a GPIO output, and ECHO to a GPIO
input. Trigger a measurement with a 10 µs HIGH pulse, then read the echo pulse width with
pulseIn() and convert it to distance.
const int TRIG_PIN = 9;
const int ECHO_PIN = 10;
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long duration = pulseIn(ECHO_PIN, HIGH);
float distanceCm = duration * 0.0343 / 2;
Serial.print("Distance: ");
Serial.print(distanceCm);
Serial.println(" cm");
delay(200);
}
Examples
| Description | Attrs |
|---|---|
| Default HC-SR04 | {} |
See also
- DHT22 — another common digital sensor for beginner projects
- PIR Motion Sensor — presence detection instead of distance measurement