The HC-SR04 Ultrasonic Distance Sensor is a popular and cost-effective solution for measuring distance without contact. It operates by emitting ultrasonic sound waves and then listening for an echo once these waves bounce off an object. This sensor is widely used in robotics for obstacle avoidance, in security systems, and for automatic distance measurement in various DIY projects.
Pin Number | Pin Name | Description |
---|---|---|
1 | VCC | Power supply (5V DC) |
2 | TRIG | Trigger input (TTL pulse) |
3 | ECHO | Echo output (TTL level signal) |
4 | GND | Ground |
Power Supply: Connect the VCC pin to a 5V power supply and the GND pin to the ground.
Triggering the Sensor: Send a 10µs TTL pulse to the TRIG pin to start the measurement.
Receiving the Echo: Monitor the ECHO pin; the duration of the high signal will give you the time interval between sending and receiving the echo.
Calculating Distance: Use the following formula to calculate the distance:
Distance (in cm) = (Time x Speed of Sound (34300 cm/s)) / 2
#include <NewPing.h>
#define TRIGGER_PIN 12 // Arduino pin tied to trigger pin on the sensor.
#define ECHO_PIN 11 // Arduino pin tied to echo pin on the sensor.
#define MAX_DISTANCE 400 // Maximum distance we want to ping for (in centimeters).
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
void setup() {
Serial.begin(9600); // Open serial monitor at 9600 baud to see ping results.
}
void loop() {
delay(50); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).
Serial.print("Ping: ");
Serial.print(uS / US_ROUNDTRIP_CM); // Convert time into distance and print result (0 = outside set distance range)
Serial.println("cm");
}
NewPing
for easier implementation and more reliable readings.Q: What is the maximum range of the HC-SR04 sensor? A: The maximum range is approximately 4 meters, but optimal performance is found within 2 meters.
Q: Can the HC-SR04 sensor detect soft materials? A: Soft and absorbent materials may not reflect sound waves well, leading to less reliable readings.
Q: How can I increase the accuracy of the sensor? A: Ensure stable mounting, avoid interference, and use averaging of multiple readings to increase accuracy.