Arduino - Ultrasonic Sensor
Arduino - Using an Ultrasonic Distance Sensor (HC-SR04)
Section titled “Arduino - Using an Ultrasonic Distance Sensor (HC-SR04)”The HC-SR04 is an inexpensive and popular ultrasonic sensor used for non-contact distance measurement. It operates like a bat’s sonar, by emitting an ultrasonic pulse and measuring the time it takes for the echo to return. This allows for distance measurements from about 2cm to 400cm (1” to 13 feet).
Its readings are not affected by sunlight or dark surfaces, but soft, irregular, or angled surfaces (like cloth) can be difficult to detect accurately as they may absorb or deflect the sound waves.
Technical Specifications
Section titled “Technical Specifications”- Power Supply: +5V DC
- Working Current: ~15mA
- Effective Angle: <15°
- Ranging Distance: 2cm – 400cm
- Resolution: ~0.3 cm
Components Required
Section titled “Components Required”- 1 × Arduino Uno R3 (or similar)
- 1 × HC-SR04 Ultrasonic Sensor
- 1 × Breadboard
- Jumper Wires
Wiring Diagram
Section titled “Wiring Diagram”The sensor has four pins. Connect them as follows:
VCC→ Arduino5VTrig(Trigger Pin) → Arduino Digital Pin9Echo(Echo Pin) → Arduino Digital Pin10GND→ ArduinoGND
How It Works: The Physics
Section titled “How It Works: The Physics”- We send a short 10-microsecond pulse to the
Trigpin. - The sensor emits a burst of 8 ultrasonic sound waves at 40kHz.
- The sensor then listens for the echo of these waves to return on the
Echopin. - The
Echopin goes HIGH for the duration of the sound’s round trip. - We measure this duration and use the speed of sound to calculate the distance.
Formula: Distance = (Travel Time / 2) * Speed of Sound
We divide the time by 2 because it’s a round trip (to the object and back).
Arduino Code: A Clean and Explained Sketch
Section titled “Arduino Code: A Clean and Explained Sketch”// Define the pin numbers for clarityconst int TRIG_PIN = 9;const int ECHO_PIN = 10;
// Define a constant for the speed of sound in cm/microsecond// (343 m/s = 34300 cm/s = 0.0343 cm/µs)const float SPEED_OF_SOUND_CM_US = 0.0343;
void setup() { Serial.begin(9600); // Initialize serial communication
// Set pin modes pinMode(TRIG_PIN, OUTPUT); pinMode(ECHO_PIN, INPUT);}
void loop() { // --- 1. Generate the trigger pulse --- // Ensure the trigger pin is low for a clean pulse digitalWrite(TRIG_PIN, LOW); delayMicroseconds(2);
// Send a 10 microsecond high pulse digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN, LOW);
// --- 2. Measure the echo pulse duration --- // pulseIn() waits for the pin to go HIGH, starts timing, // and stops timing when the pin goes LOW. It returns the duration in microseconds. unsigned long duration_us = pulseIn(ECHO_PIN, HIGH);
// --- 3. Calculate the distance --- // Distance = (Duration / 2) * Speed of Sound float distance_cm = (duration_us / 2.0) * SPEED_OF_SOUND_CM_US;
// --- 4. Print the result --- if (distance_cm > 400 || distance_cm < 2) { Serial.println("Out of range"); } else { Serial.print("Distance: "); Serial.print(distance_cm); Serial.println(" cm"); }
delay(500); // Wait half a second before the next reading}Beyond the Basics: The NewPing Library
Section titled “Beyond the Basics: The NewPing Library”For more advanced projects, the basic pulseIn() function can be limiting because it’s blocking—it pauses your entire sketch while waiting for the echo. A better approach is to use the NewPing library.
Advantages of NewPing:
Section titled “Advantages of NewPing:”- Non-blocking code structure (using timers).
- Built-in filtering: Easily average multiple readings to get a more stable distance.
- Manages multiple sensors easily.
You can install it via the Arduino Library Manager. It’s a great next step for improving the reliability of your distance-sensing projects.
Troubleshooting Common Issues
Section titled “Troubleshooting Common Issues”- Readings are always 0 or a max value: Double-check your
VCC,GND,Trig, andEchopin wiring. A loose connection is the most common problem. - Readings are erratic: The sensor might be pointed at a soft, angled, or very small object that doesn’t produce a clean echo. Ensure a clear, flat surface for testing. Electrical noise on the power supply can also cause issues.
pulseIn()timeout: If no echo is detected,pulseIn()will time out (after 1 second by default), returning 0. This is why the code checks for out-of-range values.