Codey OnlineArduino & ESP32 component library › HC-SR04
HC-SR04
Sensors

HC-SR04

The HC-SR04 is an ultrasonic distance sensor that measures range by sending a sound pulse and timing the echo return. It typically uses a 5V supply and a simple digital trigger/echo interface, making it easy to read from Arduino- and ESP32-based projects.

Width: 44.8 mm

Pinout — HC-SR04

Pin Signal Description
Vcc power bottom-edge power pin hole, leftmost of the 4-pin header
Trig digital bottom-edge trigger pin hole, second from left
Echo digital bottom-edge echo pin hole, third from left
Gnd ground bottom-edge ground pin hole, rightmost of the 4-pin header

Example wiring diagram — HC-SR04

From To Wire
board:5V x1:Vcc red
board:GND x1:Gnd black
board:D9 x1:Trig green
board:D10 x1:Echo blue

Example Arduino code — HC-SR04

This example was written and compile-checked for the arduino-uno. Codey Online adapts it to any other supported board for you.

// HC-SR04 ultrasonic distance sensor example
// Wiring:
// HC-SR04 Vcc -> 5V
// HC-SR04 Gnd -> GND
// HC-SR04 Trig -> D9
// HC-SR04 Echo -> D10

const int trigPin = 9;
const int echoPin = 10;

void setup() {
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  digitalWrite(trigPin, LOW);
  Serial.println("HC-SR04 ready");
}

void loop() {
  // Send a 10 microsecond pulse to start a measurement
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Read the echo pulse length (timeout after 30 ms)
  unsigned long duration = pulseIn(echoPin, HIGH, 30000UL);

  if (duration == 0) {
    Serial.println("Out of range or no echo");
  } else {
    // Convert time to distance in centimeters
    // Speed of sound approx. 343 m/s => 29.1 us per cm round trip
    float distanceCm = duration / 58.0;
    Serial.print("Distance: ");
    Serial.print(distanceCm, 1);
    Serial.println(" cm");
  }

  delay(500);
}

Related components

18650 Battery Shield with USB-C Charger and 5V Boost Converter

18650 Battery Shield with USB-C Charger and 5V Boost Converter

2.4 inch OLED Display I2C 3.3V

2.4 inch OLED Display I2C 3.3V

3.5 inch TFT LCD Shield

3.5 inch TFT LCD Shield

50kg Load Cell Weight Sensor

50kg Load Cell Weight Sensor

Build your Arduino or ESP32 project with AI

Describe what you want to build. Codey Online writes the code, draws the wiring diagram, compiles it and flashes your board straight from the browser.

Start for free