Ultrasonic Sensor Module – Everything You Should Know

Ultrasonic sensor module can detect existence of an object by sending ultrasound signals and monitoring its reflection. It’s one of the most common techniques to detect an obstacle in front of a robot. Another known usages is to measure the distance from an object. The alarm in you car that warns you when you get close to an obstacle during the parking process, is mainly implemented using these sensors.

Applications

Ultrasonic sensors can be used in variety of applications. Most common applications include:

  • Measuring distance
  • Detecting an obstacle
  • People detection for counting
  • Liquid level control
  • Vehicle detection in car wash, automotive assembly and parking garage 
  • Bottle Counting on Drink Filling Machines

Some of these applications require sensors with special features. In this article our main focus is on its application in robotics projects that is to detect an obstacle and measuring distance.

How the ultrasonic sensor module works?

How ultrasonic sensor module works
How ultrasonic sensor module works

The module consists primarily of two main components, an ultrasound transmitter and a receiver. The transmitter continuously sends ultrasound signals toward the direction it’s pointing to. It acts like a speaker that plays a constant note in short periods and is pointed to a specific direction. Whenever there is an object in front of the transmitter and in a range reachable by the ultrasound waves, it reflects the wave back into the space. Part of this reflection goes back toward the original source of the sound. The receiver component embedded in the module acts like a microphone and detects these reflections sends the signal to the output of the module. As the speed of the sound in the air is known (around 340m/s), it would be enough just to measure the time it takes for the ultrasound wave to reach the object and return. The formula is:

Distance = (Time * Sound Speed) / 2

When there is nothing in front of the ultrasound sensor module, there would be no reflection. This means that the value of time in the formula is infinite, that leads to having an infinite value for the distance.

How does it look like?

Whilst the basic operation and components of ultrasound sensor modules are more or less the same, they come in various form factors. You can easily distinguish the transmitter and receiver on some of them. But there are also modules incorporating both components in a single package. The most common and cheapest ultrasound sensor module is HC-SR04. That’s the one most people use in their Arduino Uno or Raspberry Pi projects.  Below is a picture of some of the most known type of them.

Where to buy an ultrasonic sensor module?

Ultrasonic sensor modules are available cheap on most local electronics shops. Here are some example in Amazon that also includes some arduino starter kits. If you’re a beginner and want to experiment more with Arduino Uno, it would be better to think about buying a starter kit. An starter kit is a collection of all common sensor modules that you may need in near future. They are compatible with almost all major platforms like Arduino, Raspberry Pi, ESP8266 and ESP32.

Ultrasonic sensor module pinout

From here on, we focus on the HC-SR04 module which is the most common and cheapest option available on the market. The pinout of this module is way too simple. The Vcc is the input voltage for the module. Normally they work with 5v but you should always refer to its documentation. Gnd must be connected to the ground. We can use the Trig pin to trigger module to send ultrasonic waves. It’s actually the input of the module. The Echo pin on the other hand is the output of the receiver.

VccThe input voltage for the module. Typically 5v
GndGround connection
TrigThe input to trigger module to send ultrasonic waves
EchoThe output received representing the reflection of waves

HC-SR04 Technical specification

Working VoltageDC 5V
Working Current 15 mA
Working Frequency40 Hz
Max Range4m
Min Range2cm
Measuring Angel15 degree
Trigger Input Signal10uS TTL Pulse
Echo Output SignalInput TTL lever signal and the range in
proportion
Dimension45x20x15mm

Connecting ultrasonic sensor to Arduino Uno

Based on what mentioned in the previous section, we can connect an HC-SR04 ultrasonic sensor module like the following diagram. In this simple scenario we have connected the trigger and echo pins to digital pin 6 and 7 of Arduino Uno. The Vcc and Gnd are also connected accordingly. 

Wiring Arduino Uno Ultrasonic Distance Module
Wiring Arduino Ultrasonic Distance Module
Ultrasonic Sensor Module PinArduino Uno Pin
VccArduino 5v
GNDArduino GND
TriggerDigital pin 7
EchoDigital pin 6

Reading data from the sensor module

Interfacing ultrasonic module is way to simple in compare with other sensor modules. The whole process is to set the trigger pin to HIGH for a short period and then read the response via Echo pin. When you set the Trigger to HIGH, module sends a burst of ultrasonic waves. On the other hand, when the reflected signal received, the Echo pin will go high. It remains high as long as it receives responses. So we just need to read the duration in which the Echo pin is high. You can see these steps in the following code. It’s annotated with proper comments to make it clear how it works.


long reflectionDuration;                //  The time it takes to get the echo of the waves
long distanceInCm;                      //  Calculated distance in centimeter
const int TRIGGER_PIN = 7;              //  The arduino pin connected to the trigger pin
const int ECHO_PIN = 6;                 //  The arduino pin connected to the echo pin

void setup() {
    pinMode(ECHO_PIN, INPUT);           //  We receive the results from the Echo, so it's input
    pinMode(TRIGGER_PIN, OUTPUT);       //  We trigger the module to start sending waves, so it's output
    Serial.begin(9600);                 //  Initialize serial pin to fetch responses from Arduino Uno
}

void loop() {
  digitalWrite(TRIGGER_PIN, HIGH);      //  Set the trigger pin to HIGH to start sending
  delayMicroseconds(10);                //  Wait for 10 microseconds while sending is in progress
  digitalWrite(TRIGGER_PIN, LOW);       //  Stop sending waves
 
  //    Duration from sending the signal until the sensor module receives the echo of the waves (in microseconds)
  //    check the pulseIn() function documentation for more info.
  reflectionDuration = pulseIn(ECHO_PIN, HIGH);
 
  //    The time takes for the signal to goes and gets reflected should be divided by 2 to
  //    get the time it takes for the ultrasonic wave to go from the module to the reflection point
  //    then divide it by 29.1 to calculate the distance in centimeter
  distanceInCm = (reflectionDuration/2) / 29.1;
  
  Serial.println(distanceInCm);
  delay(250);
}

Using NewPing library

Another simple way to read data from an ultrasonic sensor module is the NewPing library. It’s designed specifically to handle the trigger and echo pins properly and is compatible with different range of sensors. Besides that, it also have following extra features:

  • Compatible with different microcontrollers (e.g. Arduino Uno, Teensy, etc.)
  • Allows setting of maximum distance
  • Calculate the distance in different units (cm, inches)
  • Better performance in compare with plain pulseWidth calls
  • Supports multiple sensors at the same time
  • Measures distance multiple time and returns median to reduce noise data

In order to use this library, you should first install it in Arduino IDE. You can do this by going to Sketch > Include Library > Manage Libraries…

You can then type NewPing and click install (as shown in the picture below).

Arduino IDE Install NewPing Library
Arduino IDE Install NewPing Library

In order to use it you should define an instance of NewPing type giving it the Trigger and the Echo pin number. Then you can get the distance in centimeter or inches by a single call. The following sketch has the exact same result of the previous one but it uses NewPing library.


#include <NewPing.h>

const int TRIGGER_PIN = 7;              //  The arduino pin connected to the trigger pin
const int ECHO_PIN = 6;                 //  The arduino pin connected to the echo pin
NewPing sonar(TRIGGER_PIN, ECHO_PIN);   //  An instance of the NewPing class

long distanceInCm;                      //  Calculated distance in centimeter

void setup() {
  Serial.begin(9600);                   //  Initialize serial pin to fetch responses from Arduino Uno
}

void loop() {
  distanceInCm = sonar.ping_cm();           //  Ask NewPing to trigger, fetch echo and calculate distance in cm
  Serial.println(distanceInCm);
  delay(250);
}

You can also try to call the sonar.ping() function that returns the echo time in microseconds. Then you can use it to do your own calculations to find the distance. Also another useful method is the sonar.ping_median(iterations). This function does multiple pings (specified as iterations parameter) and returns the median of the result. It’s really helpful in removing noisy data and have a more normalized output.

Troubleshooting ultrasonic sensor module

Why the duration time sometimes jumps up so high or sometimes down to 0 for a very short period ?

The ultrasonic sensor result (like many other types of sensors) is not fully bulletproof. There is always a possibility that the ultrasonic wave doesn’t get reflected directly toward the receiver. In such cases the distance would be a very large number. Sometimes this happens when you’re trying to detect an small object or an object with a very irregular shape. Using sonar.ping_median() method of the NewPing library can be helpful to reduce this issue.

Why my ultrasonic sensor returns different value in different environments?

The main reason is that the sound speed is not the same everywhere. Sound travels faster in more dense environments. Also it’s temperature dependent. Hence you should consider this in your calculations. For more accurate results, you can incorporate a temperature, pressure and humidity sensors in your setup. Considering these parameter, you can calculate the sound speed more accurately as described here.

Why my ultrasonic sensor module keeps returning 0?

As described in comments here sometimes these cheap chinese boards stuck when they don’t receive echo. When you produce a loud sound in front of them (like clapping) they start working again. To fix this issue, you should implement a timer in your code. When the time is up, you can just set the pin mode for Echo pin to OUTPUT, set it to LOW and then set it back to INPUT.

References

Please follow and like us:

You may also like...

Leave a Reply