Skip to content
Home > Components > Sensors > HC-SR04 Ultrasonic Sensor

HC-SR04 Ultrasonic Sensor

A highly accurate non-contact distance measurement module using 40kHz ultrasound.

Component Preview

HC-SR04 SensorUltrasonic Sensor

The HC-SR04 uses sonar to determine distance to an object like bats do. It offers excellent non-contact range detection with high accuracy and stable readings in an easy-to-use package.

SensorsUltrasonicDigital

Overview

The HC-SR04 operates by sending a 40kHz ultrasound signal and measuring the time it takes for the echo to return. It has a range of 2cm to 400cm and requires two digital pins (one for Trigger, one for Echo).

Pin Reference

PinTypeDescription
VCCpower5V Power Supply.
TrigdigitalTrigger input. Needs a 10µs HIGH pulse to start a measurement.
EchodigitalEcho output. Pulses HIGH for a duration proportional to the distance.
GNDpowerGround.

Configurable Attributes

AttributeTypeDefaultDescription
distancenumber100The simulated distance in centimeters. Adjustable via the context menu.

Working Principle

  1. You apply a 10 microsecond HIGH pulse to the Trig pin.
  2. The module automatically sends eight 40kHz acoustic bursts and forces the Echo pin HIGH.
  3. When the acoustic signal reflects back and is detected by the receiver, the Echo pin goes LOW.
  4. Your code measures how long the Echo pin remained HIGH and calculates the distance using the speed of sound.

Wiring Diagram

  1. Connect VCC to 5V.
  2. Connect GND to Ground.
  3. Connect Trig to a digital output pin (e.g., D3).
  4. Connect Echo to a digital input pin (e.g., D4).

Wiring Diagram

Example Arduino Code

This standard code block initializes the HC-SR04, triggers a pulse, measures the echo, and calculates the distance.

cpp
#define TRIG_PIN 3
#define ECHO_PIN 4

void setup() {
  Serial.begin(9600);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  Serial.println("HC-SR04 Sensor Ready");
}

void loop() {
  // Clear the trigger
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  
  // Send 10 microsecond pulse
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  
  // Read echo duration
  long duration = pulseIn(ECHO_PIN, HIGH);
  
  // Calculate distance in cm and inches
  // Speed of sound = 340 m/s or 29 microseconds per cm
  // We divide by 2 because the sound travels out and back
  float cm = (duration / 2.0) / 29.1;
  float inch = (duration / 2.0) / 74.0;
  
  Serial.print("Distance: ");
  Serial.print(cm, 1);
  Serial.print(" cm | ");
  Serial.print(inch, 1);
  Serial.println(" in");
  
  delay(500);
}

Simulation Notes

  • In OpenHW Studio, you can right-click the sensor during simulation to drag a slider and change the distance in real-time. The simulator instantly adjusts the pulseIn echo duration based on the simulated distance.

Released under the MIT License.