The HC-SR04 is a simple module that is often used in distance measurement projects. It can detect objects up to 4 meters. The minimum detection range is 2 cm. The sensor has a relatively narrow beam angle of 15 degrees and an accuracy of 2 mm. One of the great things about the HC-SR04 is as it utilizes ultrasonic sound (sonar) instead of light to operate, its performance is not affected by sun ray.
The module has four pin connections (VCC, Trigger, Echo, and GND). It can be powered from a 5V DC supply. The working current of the HC-SR04 is 15 mA. The HC-SR04 is an ultrasonic transmitter and receiver sensor all in one. When the Trigger pin is given a HIGH pulse of at least 10 microseconds and there is an object within range, the Echo pin on the sensor will go from LOW to HIGH for a certain period. From here, the echo duration is used to calculate distance to the object.
In the example below, the HC-SR04 will activate one of the three LED lights based on the distance between the sensor and the object. If the calculated distance is over 100 cm, the green light illuminates. When the object gets closer (50-100 cm), the yellow light will turn on. Closer than that, the red light will come on. Three 330 ohm resistors limit the current flowing through the LEDs.
const int triggerPin=12;
const int echoPin=11;
const int greenledPin=10;
const int yellowledPin=9;
const int redledPin=8;
long duration;
int distance;
void setup() {
pinMode(triggerPin,OUTPUT);
pinMode(echoPin,INPUT);
pinMode(greenledPin,OUTPUT);
pinMode(yellowledPin,OUTPUT);
pinMode(redledPin,OUTPUT);
}
void loop() {
//Reset the Trigger pin to ensure a clean HIGH pulse.
digitalWrite(triggerPin,LOW);
delayMicroseconds(2);
//Start a ping by providing HIGH pulse on the Trigger pin for 10µs.
digitalWrite(triggerPin,HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin,LOW);
//Gets the echo duration.
duration=pulseIn(echoPin,HIGH);
//duration is converted into distance
//Speed of sound in air = 340 m/s = 0.034 cm/µs => 29.412 µs/cm
//The result is divided by 2 as the sound travels back and forth
distance=(duration/2)/29.412;
if(distance<=100&&distance>=50){
digitalWrite(redledPin,LOW);
digitalWrite(yellowledPin,HIGH);
digitalWrite(greenledPin,LOW);
}
if(distance<50&&distance>=0){
digitalWrite(redledPin,HIGH);
digitalWrite(yellowledPin,LOW);
digitalWrite(greenledPin,LOW);
}
if(distance>100||distance<0){
digitalWrite(redledPin,LOW);
digitalWrite(yellowledPin,LOW);
digitalWrite(greenledPin,HIGH);
}
delay(1000);
}