Skip to main content

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);  
}

Comments

Post a Comment

Popular posts from this blog

Connect LCD Display to Arduino

Connecting LCD to Arduino to display various things is fun if you know how to. It is very simple just follow the simple steps. Gather the things necessary to do so like: Arduino (mega 2560 for example), LCD display(16x2), Jumper Wires, Potentiometers (1k/10k). Make the connections as shown in the circuit diagram. I this example we are using Arduino mega 2560. You can use any of the arduino just the connections and the coding will change. LCD 1(VSS) to Arduino GND LCD 2(VCC) to 5V LCD 3(VEE) to Arduino GND via potentiometer (10K) LCD 4(RS) to Arduino pin 12 LCD 5(R/W) to Arduino GND LCD 6(E) to Arduino pin 11 LCD 11(DB4) to Arduino pin 5 LCD 12(DB5) to Arduino pin 4 LCD 13(DB6) to Arduino pin 3 LCD 14(DB7) to Arduino pin 2 LCD 15(LED+) to 5V via potentiometer (10K) LCD 16(LED-) to GND         The pin 3 potentiometer will control the contrast of the display. The pin 15 and 16 are for the backlight and the potentiome...