Using HC-SR04 Ultrasonic Sensor with Arduino
Using HC-SR04 Ultrasonic Sensor with Arduino
The HC-SR04 is an ultrasonic module that measures distance by emitting sound waves and calculating the time it takes for the echo to return. It can measure distances from 2 cm to 400 cm, making it useful for robotics, proximity detection, or obstacle avoidance projects.
Wiring HC-SR04 to Arduino UNO
| HC-SR04 | Arduino |
|---|---|
| Vcc | 5V |
| Gnd | Gnd |
| Trig | D13 |
| Echo | D12 |
Arduino Code: Reading Distance from HC-SR04
const int trigPin = 13;
const int echoPin = 12;
void setup() {
Serial.begin(9600);
}
void loop() {
long duration, cm;
// Send ultrasonic pulse
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(5);
digitalWrite(trigPin, LOW);
// Read echo signal
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
// Convert time to distance (cm)
cm = microsecondsToCentimeters(duration);
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);
}
long microsecondsToCentimeters(long microseconds) {
// Speed of sound = 340 m/s = 29 microseconds per cm
// Divide by 2 because the wave travels out and back
return microseconds / 29 / 2;
}
How to test: Upload the code, open the Serial Monitor (baud 9600), and you will see distance readings in cm every 100 milliseconds.
Using NewPing Library for Simpler Code
For cleaner code or multiple sensors, install the NewPing library via Sketch > Include Library > Manage Libraries and search for “NewPing”.
#include <NewPing.h>
const int trigPin = 13;
const int echoPin = 12;
const int maxDistance = 400; // cm
NewPing sonar(trigPin, echoPin, maxDistance);
void setup() {
Serial.begin(9600);
}
void loop() {
delay(50); // Wait between pings
int distance = sonar.ping_cm();
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
}
Point to adjust: Change maxDistance to match your project’s actual measurement range.
Practical Usage Notes
- Correct wiring — especially Vcc and Gnd, do not swap them
- Power supply — HC-SR04 draws about 15mA, ensure your USB or 5V adapter can supply enough current
- Target surface — objects with small angles or rough surfaces may cause the sound wave to reflect in the wrong direction, giving incorrect readings
- Maximum range — do not try to measure beyond 400 cm as it exceeds the sensor’s specification
Sensor Signal Sequence
Common Applications
- Obstacle-avoiding robots
- Proximity warning systems
- Water level measurement in tanks
Reference Video
อยากทำโปรเจคแบบนี้?
รับทำโปรเจค Arduino / IoT จบงานไว ส่งงานครบ พร้อมสอน
If you need Arduino project service or urgent IoT development, see full service details on the home page
จ้างทำโปรเจคเลย