Ultrasonic Sensor Arduino: HC-SR04 Wiring and Code

An ultrasonic sensor Arduino project can measure approximate distance without touching the target. The HC-SR04 sends a short sound burst and reports the echo travel time. The important details are correct voltage levels, a bounded measurement timeout and a target that reflects sound back toward the sensor.
This example is for a conventional 5 V Arduino Uno-compatible board and an HC-SR04-style trigger/echo module. It is an instructional starting point, not a tested collision-avoidance system or a guarantee of precision.

Parts and compatibility checks
Use an HC-SR04 ultrasonic distance module, an Uno-compatible controller, four jumper wires and a stable USB supply for the controller. Confirm the four module labels before connecting anything. Do not assume that a different ultrasonic board uses the same pin order or communication mode.
Typical HC-SR04 modules use 5 V and return a 5 V Echo signal. This guide is not direct-wiring guidance for a 3.3 V ESP32 or Raspberry Pi. Those platforms need appropriate input-level protection and platform-specific code. Check the exact board documentation before changing the controller.
HC-SR04 wiring for Arduino Uno
| Sensor pin | Uno connection | Purpose |
|---|---|---|
| VCC | 5 V | Module supply |
| GND | GND | Shared reference |
| TRIG | D9 | Trigger output |
| ECHO | D10 | Echo input |
Disconnect USB power while wiring. Check for a reversed supply, loose ground connection and adjacent breadboard rows accidentally touching. Keep the two transducer faces unobstructed and point the module at a broad, flat object for the first test.
Ultrasonic sensor Arduino example code
const byte TRIG = 9;
const byte ECHO = 10;
void setup() {
Serial.begin(9600);
pinMode(TRIG, OUTPUT);
digitalWrite(TRIG, LOW);
pinMode(ECHO, INPUT);
}
void loop() {
digitalWrite(TRIG, LOW);
delayMicroseconds(2);
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
unsigned long us = pulseIn(ECHO, HIGH, 25000UL);
if (us == 0) {
Serial.println("No valid echo");
} else {
float cm = us * 0.0343f / 2.0f;
Serial.print(cm, 1);
Serial.println(" cm");
}
delay(100);
}Open Serial Monitor at 9600 baud. The conversion assumes a sound speed of approximately 343 m/s near room temperature. Division by two accounts for the outward and return journey. Temperature and target geometry affect the result; a decimal place in the display is not proof of equivalent measurement accuracy.Newest in the store
Why the timeout matters
The explicit 25,000 microsecond timeout prevents this measurement call from waiting indefinitely for a valid echo. A zero return value means the measurement failed within that window; it does not mean an object is touching the sensor. In an actuator project, handle missing or implausible readings as a separate state, rather than feeding zero into a motor-control decision.
Test the sensor in stages
First hold a broad board perpendicular to the sensor at a moderate distance. Move it gradually and compare the displayed trend with a ruler. Repeat at several positions instead of judging performance from one reading. The nominal HC-SR04 range is about 2–400 cm, but objects near the blind zone, soft materials and oblique surfaces can produce missing or unstable readings.
Once the basic setup works, add filtering only if needed. A small median of valid samples can reject isolated spikes, but it should not hide a long run of invalid echoes. If several modules share the project, trigger them sequentially with enough quiet time to reduce acoustic cross-talk.
Troubleshooting common symptoms
- No valid echo: check common ground, swapped Trigger/Echo wires and target alignment.
- Unchanging short reading: check enclosure reflections, a nearby obstruction and wiring mistakes.
- Jumping readings: test a larger flat target, improve mounting and check supply stability.
- Works on Uno but not a 3.3 V board: stop and review interface levels rather than repeating unsafe direct connections.
Next steps and reference
Compare the ultrasonic sensor price and selection guide before choosing accessories. A waterproof probe uses a different mechanical arrangement and may have a much larger blind zone; see the JSN-SR04T selection guide. The HC-SR04 reference datasheet explains the trigger pulse and echo principle. Verify your own module revision before depending on a published specification.
