How to connect Aduino and Ultrasonic Sensor (HC-SR04)
published on 2020-02-17
The following table shows the connections you need to make:
Ultrasonic Sensor HC-SR04 | Arduino |
---|---|
VCC | 5V |
Trig | Pin 11 |
Echo | Pin 12 |
GND | GND |
Code:
(Upload the following code to Arduino IDE)
-
Create variables for Trig and echo pins, named trigPin and echoPin. the trig pin is connected to digital pin 11, echo pin is connected to digital pin 12.
int trigPin = 11; int echoPin = 12;
-
You also need to create two long variables: duration, cm. The variable duration holds the time between the transmission and reception of the signal.
long duration, cm,
-
In the setup(), initialize the serial port at a baud rate of 9600, and set the trigger pin as an output and the echo pin as an input.
//Serial Port begin Serial.begin (9600); //Define inputs and outputs pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT);
-
In the loop(), trigger the sensor by sending a HIGH pulse of 10 microseconds. But, before that, give a short LOW pulse to ensure you’ll get a clean HIGH pulse:
digitalWrite(trigPin, LOW); delayMicroseconds(5); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW);
-
Then, you can read the signal from the sensor – a HIGH pulse whose duration is the time in microseconds from the sending of the signal to the reception of its echo to an object.
duration = pulseIn(echoPin, HIGH);
-
Finally, you just need to convert the duration to a distance. We can calculate the distance by using the following formula:
distance = (traveltime/2) x speed of sound The speed of sound is: 343m/s = 0.0343 cm/uS = 1/29.1 cm/uS
-
We need to divide the traveltime by 2 because we have to take into account that the wave was sent, hit the object, and then returned back to the sensor.
cm = (duration/2) / 29.1;
The cm variable will save the distance in centimetres.