1. Required Components
- 1 x Arduino Board (e.g., Arduino Uno)
- 1 x HC-SR04 Ultrasonic Sensor
- Jumper wires
- Breadboard (optional)
- USB cable to connect Arduino to PC
2. Wiring Instructions
Follow these steps to connect the HC-SR04 sensor to your Arduino:
- VCC: Connect to 5V on the Arduino.
- GND: Connect to GND on the Arduino.
- TRIG: Connect to digital pin 9.
- ECHO: Connect to digital pin 10.
3. How It Works
The HC-SR04 sensor emits ultrasonic waves through the TRIG pin and measures the time taken for the waves to reflect back to the ECHO pin. Using the speed of sound (343 m/s), the distance is calculated.
digitalWrite()
: Sends a signal to the TRIG pin to emit a pulse.pulseIn()
: Measures the duration of the returning signal on the ECHO pin.- Distance Formula: Distance in cm is calculated as
(duration * 0.034 / 2)
, where 0.034 is the speed of sound in cm/µs.
4. Arduino Code
Copy and paste this code into the Arduino IDE:
// HC-SR04 Ultrasonic Sensor Pins
const int trigPin = 9;
const int echoPin = 10;
// Variables for storing the distance and pulse duration
long duration;
int distance;
void setup() {
// Set up TRIG as output and ECHO as input
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Initialize Serial Monitor
Serial.begin(9600);
}
void loop() {
// Clear the TRIG pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Send a 10-microsecond pulse
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the ECHO response time
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in cm
distance = duration * 0.034 / 2;
// Output the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Wait before the next measurement
delay(500);
}
5. Upload and Test
- Connect your Arduino to your PC using the USB cable.
- Open the Arduino IDE and paste the code above into a new sketch.
- Select the correct board and port in the IDE.
- Upload the code to your Arduino.
- Open the Serial Monitor to view real-time distance measurements in centimeters.
6. Additional Tips
- Fine-Tune Sensitivity: Test in different environments to adjust for temperature or other factors affecting sound speed.
- Expand the Project: Integrate the sensor with an LCD display or control devices based on distance readings.
- Debugging: Use the Serial Monitor to verify the distance readings and troubleshoot wiring or code issues.
7. Conclusion
Congratulations! You’ve successfully created an ultrasonic distance measurement tool using the HC-SR04 and Arduino. This versatile sensor is a gateway to exciting projects in robotics, home automation, and obstacle detection systems.