Using HC-SR04 (Ultrasonic sensor) with arduino


HC-SR04 is an ultrasonic sensor which works on the principle of ultrasonic waves. Basically it creates a pulse depending on the distance from the sensor. It has two eyes like structure one of which transmits the waves and the other acts as receiver. The sensor has 4 pins VCC, TRIG, ECHO, GND. When the sensor is triggered by sending a pulse to TRIG pin, it sends a pulse through ECHO pin which can be measured.

1.      Parts needed: Arduino, wires, Ultrasonic Sensor (HC-SR04).

2.      Connections:

VCC pin to Arduino 5V

TRIG pin to Arduino pin 11

ECHO pin to Arduino pin 12

GND pin to Arduino GND

3.      Code:


void setup()  
{  
Serial.begin(9600);
//Sensor TRIG pin to pin 11
pinMode(11, OUTPUT);
//Sensor ECHO pin to pin 12
pinMode(12, INPUT);  
}
void loop()  
{  
int duration, distance;
//to send trigger pin to pin 11 by activating it for 50 microseconds
digitalWrite(11, HIGH);
delayMicroseconds(50);
digitalWrite(11, LOW);
//pulseIn function measures the time for which the pulse is high
duration = pulseIn(12, HIGH);
//conversion of time to distance
distance = duration * 0.034 / 2;
//prints the distance on serial monitor
Serial.print(distance);
Serial.print(" cm");
delay(100);  
}