Ultrasonic Sensor and Arduino Tutorial

In this tutorial we are going to learn how Ultrasonic sensor works and how we can measure distance using Ultrasonic sensor.

What is an Ultrasonic sensor?

It emits an ultrasound at 40 000 Hz which travels through the air and if there is an object or obstacle on its path It will bounce back to the module. Considering the travel time and the speed of the sound you can calculate the distance.

Ultrasonic sensor Working | Alpha Electronz

The HC-SR04 Ultrasonic Sensor Module0 has 4 Pins GND, VCC, TRIG and ECHO.

Description of Each Pins of Ultrasonic Module –

GND – It should be connected to the ground of the rest of the cirucits

VCC – It should be connected to 5V

TRIG – It generates the Ultrasound when we give a high state of 10uS to this pin

ECHO –  It provides the time the sound wave have travelled in Microseconds

Ultrasonic sensor working

For example, if the object is 10 cm away from the sensor, and the speed of the sound is 340 m/s or 0.034 cm/µs the sound wave will need to travel about 294 u seconds. But what you will get from the Echo pin will be double that number because the sound wave needs to travel forward and bounce backward. So in order to get the distance in cm we need to multiply the received travel time value from the echo pin by 0.034 and divide it by 2.

Now  we have understood how the ultrasonic sensor works, so lets start the measuring distance using Ultrasonic Sensor and Arduino.

Components Required :

Ultrasonic Sensor – (Checkout)

Arduino Uno – (Checkout)

Jumpers & Breadboard – (Checkout)

Circuit Diagram

Arduino Ultrasonic Sensor Circuit Diagram | Alpha Electronz

Code

const int trigPin = 12;
const int echoPin = 13;
long duration;
int distanceCm;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);

Serial.begin(9600);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distanceCm= duration*0.034/2;

Serial.println("distanceCm");
}
0

Leave a Reply

Your e-mail address will not be published. Required fields are marked *