Nairobi
admin@elffie.com
HC-SR04 Ultrasonic Distance Sensor

Generic · HC-SR04

HC-SR04 Ultrasonic Distance Sensor

KSh 250In stock

Specification

Part number
HC-SR04
Manufacturer
Generic
Stock code
SEN-HCSR04
Category
Sensors
Supply voltage
5 V
Output type
Digital pulse
Mounting
Through-hole
Availability
22 in stock

Details

The standard four-pin ultrasonic ranger. You pulse TRIG, time how long ECHO stays high, and convert to distance. Cheap, reliable enough for obstacle avoidance and tank level, and the first sensor most robots get.

Worth knowing: it does not see soft or angled surfaces well — cloth absorbs the pulse and a surface tilted away reflects it elsewhere. ECHO idles at 5 V, so on a 3.3 V board (ESP32, Pico) put a divider on that pin.

Ask about this part

Answers come from this listing and the assistant can still be wrong — the manufacturer's datasheet is what governs. For anything you are going to wire up, check it there or ask us.

Using this part

Starting points, not finished firmware. Check them against the datasheet.

Measure distance in centimetres

cpp · 27 lines
// VCC -> 5V, GND -> GND, TRIG -> D9, ECHO -> D10
// On a 3.3V board, divide ECHO down first.

const uint8_t TRIG = 9, ECHO = 10;

void setup() {
  Serial.begin(9600);
  pinMode(TRIG, OUTPUT);
  pinMode(ECHO, INPUT);
}

void loop() {
  digitalWrite(TRIG, LOW);  delayMicroseconds(2);
  digitalWrite(TRIG, HIGH); delayMicroseconds(10);
  digitalWrite(TRIG, LOW);

  // Time out after ~30 ms so a missing echo does not block the loop.
  unsigned long us = pulseIn(ECHO, HIGH, 30000UL);
  if (us == 0) {
    Serial.println("no echo");
  } else {
    // Sound travels ~0.0343 cm/us; halve it for the round trip.
    Serial.print(us * 0.0343 / 2.0);
    Serial.println(" cm");
  }
  delay(100);
}