Ultrasonic sensor is a sensor that works on principle similar to radar or sonar. It generates high frequency sound and calculate the time interval between the sending of signal and the receiving of echo. Therefore, ultrasonic sensor can be used to measure distance. HC-SR04 ultrasonic sensor consists of a transmitter, a receiver and a control module.

DSC06790
Front view of HC-SR04
DSC06791
Back view of HC-SR04

The datasheet of HC-SR04 can be obtained here, HC-SR04.

The working principle of a ultrasonic sensor is as below:

1. Send at least 10us of HIGH signal to trigger pin.

2. Detect the pulse width of echo signal sent back.

3. Apply some calculation to get the distance.

I have sketch the working principle of ultrasonic sensor to give a better understanding.

DSC06798
Ultrasonic Sensor working principle sketch

The pulse width of echo is proportional to the distance travelled.

We know that the speed of sound travelling in air is 340 m/s.

When the transmitter send a signal out, the receiver receives back the signal sent.

Now that the distance travel by the signal is double of the distance of interest. So we divide it by two.

By using basic physics principle, velocity = distance/time.

Therefore, the distance travelled is the product of velocity and time.

ultra3

The set up of ultrasonic sensor on breadboard.

DSC06796

DSC06797

There are library made available for ultrasonic sensor. You can get it from here.

If you would like to know more on how to use ultrasonic sensor with library, you can visit here.

However, I had tried out the ultrasonic sensor based on the working principle I had mentioned above, and it works perfectly. 😀


#include <LiquidCrystal.h>

#define trigger 2
#define echo 3

LiquidCrystal lcd(5,6,7,8,9,10);

float time=0,distance=0;

void setup()
{
 lcd.begin(16,2);
 pinMode(trigger,OUTPUT);
 pinMode(echo,INPUT);
}

void loop()
{
 lcd.clear();
 digitalWrite(trigger,LOW);
 delayMicroseconds(2);
 digitalWrite(trigger,HIGH);
 delayMicroseconds(10);
 digitalWrite(trigger,LOW);
 delayMicroseconds(2);
 time=pulseIn(echo,HIGH);
 distance=time*340/20000;
 lcd.setCursor(0,0);
 lcd.print("Dist:");
 lcd.setCursor(6,0);
 lcd.print(distance);
 lcd.setCursor(10,0);
 lcd.print("cm");
 delay(100);
}

That’s it, hope that all the explanation can help you understand more about ultrasonic sensor. If you have any question, feel free to drop me a comment.

Advertisements