CNAP

HC-SR04 Ultrasonic Reference

An ultrasonic distance sensor that measures distance by timing the echo of a sound pulse.

Pin names

NameDescription
VCCPower (5V)
TRIGTrigger — send a short HIGH pulse to start a measurement
ECHOEcho — goes HIGH for the duration of the sound's round trip
GNDGround

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

DescriptionAttrs
Default HC-SR04{}

See also

  • DHT22 — another common digital sensor for beginner projects
  • PIR Motion Sensor — presence detection instead of distance measurement