View Course Path

Interfacing of Arduino Uno with ultrasonic sensor HC-SR04

In this tutorial, we are going to learn how the HC-SR04 ultrasonic sensor works and also discuss the interfacing of an Arduino Uno with an ultrasonic sensor.

What are ultrasonic waves?

Ultrasonic waves are sound waves with frequencies above 20,000 Hz. These ultrasonic waves exist above the human-detectable frequency. However, animals like bats, frogs, and dolphins use these very high-frequency sound waves to find their food and also for communication. This process is known as echolocation. Additionally, they use these ultrasound waves as a tool to find the distance of objects in front of them.

Now that you are clear with the term ultrasonic let’s kickstart our discussion on Arduino Uno interfacing with the ultrasonic sensors.

What are the components required for interfacing an Arduino Uno with an ultrasonic sensor?

Before we begin building this project, let’s take a gander at the inventory we need to amass. Click on the links to check out these products on Amazon. Disclaimer: These purchases net us some money and help us maintain this website!

[geoip_detect2_hide_if country=”IN”] [/geoip_detect2_hide_if] [geoip_detect2_show_if country=”IN”] [/geoip_detect2_show_if]

Understanding the HC-SR04 ultrasonic sensor

The HC-SR04 ultrasonic sensors are used to find the distance of an object in front of them. They use high-frequency sound waves to find this distance. Kind of like the echolocation concept we read about above. Interestingly, ships also use this principle to find the depth of the sea.

Whenever we need our machine to ‘know’ about the obstacles in its path, we should use this ultrasonic sensor. We can gauge the distance by computing the data given by the sensor. A microcontroller does this computation. Here the microcontroller is the one embedded in the Arduino Uno. Interfacing the Arduino Uno with the ultrasonic sensor is a straightforward procedure.

What are the specifications of the HC-SR04 ultrasonic sensor?

  • DC supply voltage: 5V.
  • Supply current: 15 mA.
  • Output voltage: 0 – 5V (Output voltage is high only on the detection of an obstacle in the fixed range).
  • Modulation frequency: 40 HZ.
  • Beam Angle: Maximum 15 degrees.
  • Distance: 2 cm – 400cm.
  • Accuracy: 0.3 cm.
  • Output cycle: 50ms.
  • Communication: Pulse in/out.

The HC-SR04 ultrasonic sensor is very cheap and reasonably reliable. However, its accuracy is +/- 3 mm. It means that anything less than 1 cm measurement is, at best, a guess.

What are the physical dimensions of the HC-SR04?

  • Length: 45 mm
  • Height: 20 mm
  • Height of transmitter and receiver: 11 mm.
  • The diameter of the transmitter and Receiver: 16 mm.

What is the working principle of the ultrasonic sensor?

The working is pretty simple. The trig pin of the HC-SR04 emits and transmits a high-frequency pulse. This pulse bounces off the object and reflects. The HC-SR04 sensor’s echo pin senses (or receives) this reflection. Using the basic physics formula for calculating the distance (distance=speed x time), we can calculate the distance using arithmetic operators in the Arduino code.

working of an ultrasonic sensor

We can calculate the distance of an object in front of the ultrasonic sensor using the formula below:

D= 1/2 X T * C

Where,

D=Distance

T= Time taken.

C= Speed of the sound wave transmitted.

For example:

Consider there is an obstacle in front of the sensor. The speed of the ultrasonic waves emitted from the sensor is 350 m/s . and the time taken to receive the waves reflected by the obstacle is 2 ms. Then,

D= 1/2 X 350 * 2 X 10³

Distance = 0.350 m.

What are the pins present on the HC-SR04 ultrasonic sensor?

HC-SR04 ultrasonic sensor has four pins.

PIN

Pin name

Function

1 Vcc 5V input voltage should be given to this pin, this Vcc pin powers the sensor
2 Trigger pin It is an input pin, it has to be kept high for 10µs to initialize measurement by sending ultrasonic waves
3 Echo pin It is an output pin, it goes high for some time which will be equal to the time taken for the ultrasonic wave to return to the sensor.
4 Ground pin It is connected to the ground of the system.

What is the circuit design for an HC-SR04 Arduino distance sensor?

The Arduino Uno has a micro-controller that can read data from various inputs like sensors and also can compute it according to the program coded. It has 14 digital input/output pins and six analog pins.

The Arduino Uno power supply can be done with the help of a USB cable or an external power supply. The external power supplies mainly include AC to DC adapter or a battery. We can connect the adapter to the Arduino Uno by plugging it into the power jack of the Arduino board. Similarly, the battery leads will connect with the Vin pin and the GND pin of the POWER connector. The suggested voltage range will be 7 volts to 12 volts.

The circuit of the Arduino distance sensor consists of three parts. The microcontroller, the transmitter, and the receiver. All three of these major sectors perform some core operations.

What is the function of the microcontroller?

  • The microcontroller physically interfaces with the sensor’s trigger and echo pins.
  • It controls the timing and sending of pulses.
  • The microcontroller receives the processed signal from the receiver as an interrupt.
  • It controls the frequency and speed of the sound wave generated and also records the time taken to receive the reflected waves.

What is the function of the Transmitter?

  • The transmitter of the HC-SR04 emits a high-frequency sound wave, which is an ultrasonic wave.
  • The voltage is fed to the TX transducer from the anti-phase TX signals from the micro-controller. Using anti-phase signals, the transducer receives a differential voltage, which is effective +/- 5 V. The chip produces a higher current driver than the micro-controller.

What is the function of the Receiver?

  • It receives the ultrasonic wave reflected by the object in front of the sensor.
  • The receiver is a chain of three AC coupled op-amps.

How to connect the ultrasonic sensor with the Arduino Uno?

Circuit connections for Arduino interfacing with ultrasonic sensor are discussed below:

  • The Vcc pin of the Arduino distance sensor (HC-SR04) connects with the 5 V Vcc out pin of the Arduino Uno board.
  • The trigger pin of the Arduino distance sensor physically interfaces with any of the digital pins from D0 to D13. Do not forget to declare this signal as a trigger pin in your Arduino program.
  • The echo pin of the ultrasonic sensor connects with any of the digital pins from D0 to D13 in the Arduino Uno board.
  • The ground pin of the ultrasonic sensor goes into the Arduino’s ground pin female header.

Coding for the ultrasonic Arduino distance sensor

Arduino programming takes place within the Arduino environment. Open the Arduino IDE software on your computer. Coding in the Arduino programming syntax will control your circuit. Open a new sketch File by clicking New. The Arduino code should contain two functions as void setup() and void loop(). All pinMode declarations are made in void setup(). The functions inside void loop() will run infinitely.

How to write Arduino Uno ultrasonic sensor code?

Whenever applicable, it is always advised to check the sensor’s reading on the Arduino IDE’s serial monitor before proceeding with further modules of your Arduino project. The serial monitor helps a lot to follow up on the sensor’s activity. Moreover, it also enables you to rectify the problems instantly.

Let’s get down to the Arduino Uno ultrasonic sensor code for displaying the readings on the serial monitor.

One good thing is ultrasonic sensor Arduino interfacing doesn’t require any library files. It doesn’t require any special in-built functions. Some of the ordinary built-in functions used for displaying Arduino distance sensor readings on the serial monitor are:

  • begin(9600) – to set the baud-rate for the sensor reading.
  • pinMode(pin, mode) – to declare the pin and its functionality whether it should be an input pin or output pin
  • digitalWrite(pin, HIGH/LOW) – to give a digital signal to that particular pin as high or low.
  • delay(µs) – to delay the process for some microseconds.
  • Pulse in (echo-pin, mode) – Reads a pulse (either HIGH or LOW) on a pin. For example, if the value is HIGH, pulseIn() waits for the pin to go HIGH, starts timing, then waits for the pin to go LOW and stops timing. Returns the length of the pulse in microseconds or 0 if there was no reception of a complete pulse within the timeout.
  • print(data)- to print the sensors reading on the serial monitor.

How to write a code to display ultrasonic sensor readings on the serial monitor?

If you want to display the readings from the HC-SR04 Ultrasonic Sensor on serial monitor, you can use the following source code:

int trigPin = 3;

int echoPin = 4;

void setup()

{

Serial.begin(9600);

pinMode(trigPin, OUTPUT);

pinMode(echoPin, INPUT);

}

void loop()

{

long duration, distance;

digitalWrite(trigPin,HIGH);

delayMicroseconds(1000);

digitalWrite(trigPin, LOW);

duration=pulseIn(echoPin, HIGH);

distance =(duration/2)/29.1;

Serial.print(distance);

Serial.println("CM");

delay(10);

}

Here the trigger pin is made HIGH for 1000 µs to initialize measurement by sending ultrasonic waves. As you can see in the code, we connect the trigger pin and echo pin of the Arduino distance sensor with the digital pins D3 and D4 of the Arduino Uno board, respectively. You can use other digital pins also.

How to interface LCD and ultrasonic sensor (HC-SR04) with the Arduino Uno board?

An LCD has 16 pins with backlight and contrast adjustment functions. This LCD comes under the JHD162A series. We also have a detailed guide on everything you need to know about interfacing an LCD with the Arduino Uno.

LCD-Display-interface with arduino

  1. Connect the LCD pin 1 (GND) with the ground pin of the Arduino.
  2. Pin 2 (Vcc) connects with the 5V Vcc pin of Arduino.
  3. Connect the third pin of the LCD (Vee) with the middle pin of the 10 k potentiometer.
  4. You can connect the fourth pin (RS) with any of the digital pins on the Arduino. However, make sure that you include this connection in the code accurately. The Register select pin controls whether commands or data is being sent to the LCD. When the pin is given a 0 (LOW), it accepts commands as input. When it is given a 1 (HIGH), it takes data as input.
  5. Connect pin 5 (R/W) with the ground pin of the Arduino. Since we are writing to the LCD, we will select the Write mode by connecting it to a LOW value.
  6. LCD pin 6(EN) connects with any of the digital pins on Arduino. This is the enable pin, and it allows the next seven pins of the LCD (D0-D7) to send 8-bit data.
  7. LCD pin 7- pin 14(DB0-DB7) connects with any of the digital pins of the Arduino. However, remember to declare these as data pins in the code.
  8. Next, connect Pin 15(LED+) with the 5V Vcc pin of Arduino. The function of this pin is to control the backlight of the LCD screen.
  9. LCD pin 16(LED-) should be connected with the ground pin of the Arduino.

The final circuit after we are done interfacing the HC-SR04, and the LCD with the Arduino Uno should look something like this.

Circuit diagram to interface LCD and HC-SR04 with an Arduino Uno
Circuit diagram to interface LCD and HC-SR04 with an Arduino Uno

Write the code to interface the HC-SR04 ultrasonic sensor with an Arduino Uno and display data on an LCD

The example Arduino Uno ultrasonic code for displaying the sensor readings on liquid crystal display is included here,

#include <LiquidCrystal.h>

// initialize an object with the numbers of the interface pins

LiquidCrystal lcd(R/W,EN,D4,D5,D6,D7);

int trigPin = 3;

int echoPin = 4;

void setup()

{

// set up the LCD's number of columns and rows:

lcd.begin(16, 2);

lcd.clear();

Serial.begin(9600);

pinMode(trigPin, OUTPUT);

pinMode(echoPin, INPUT);

}

void loop()

{

long duration, distance;

digitalWrite(trigPin,HIGH);

delayMicroseconds(1000);

digitalWrite(trigPin, LOW);

duration=pulseIn(echoPin, HIGH);

distance =(duration/2)/29.1;

lcd.setCursor(0,0); // Sets the cursor at col 0 and row 0

lcd.print("Dis: "); // Prints Dis: on LCD

lcd.print(digitalRead(distance)); // Prints data on LCD

lcd.print("CM");

delay(1000);

}

Common errors with the interfacing of the Arduino and the HC-SR04 and their troubleshooting

The main problem arises when you swap the pin nodes while using. The voltage supply for the ultrasonic sensor must be 5V. So avoid the voltage fluctuations if you aren’t getting the proper output. Make sure that you connect the sensor pins according to your code.

Make sure to connect Read/Write, Enable pins to the Arduino’s transmitter, and receiver pins, which are D0 and D1. There is no strict rule about connecting the data pins of the LCD to a particular group of pins. You can connect them with any of the Arduino’s digital pins. However, you should declare the connections appropriately in the program.

It is necessary to connect a potentiometer with Vout to control the backlight. Without the potentiometer, the screen will appear shady. You can connect a resistor of 1 kΩ or 3.9 kΩ with the LED+ Anode pin of the LCD to control the contrast. Otherwise, you might face issues like a fuzzy display of data.

Liquid crystal display requires input voltage Vcc in the range between 4.7 V to 5.3 V. Fluctuations in the voltage given by 5V Vcc out pin of Arduino. It may cause problems in getting the output. Though the connections are correct. To avoid this issue, use a stable voltage supply for Arduino and check whether there is fluctuation in the 5 V Vcc output pin. In this case, use resistors with the corresponding ohm.

Many websites prefer to connect 10 kΩ with anode pin of the backlight in LCD, but it works well at 1 kΩ.

What can I use the HC-SR04 for? What are the different applications of the ultrasonic sensor?

Ultrasonic sensors can find depth or distance. Thus they will help you kind of give a type of ‘vision’ to your machine. It will help your machine find obstacles in front of them. Some simple and exciting projects using the Arduino and ultrasonic sensors are shown below.

  • Gadgets for blind people.
  • Maze solving bot.
  • Automatic water level indicator.
  • Automatic door alarm.
  • Obstacle solver.

If you have any queries with regards to interfacing the HC-SR04 with the Arduino, let us know in the comments section below, and we’ll be glad to assist you. For more Arduino projects, refer to the topic list on the side (or above if you are on your phone).

4 thoughts on “Interfacing of Arduino Uno with ultrasonic sensor HC-SR04

  1. i want to have a accurate output in the blynk lcd but it approximates the value if 2.5 cm it shows 2cm for example how do i fix it does it have some thing to do with this lcd.print(7, 1, distance);

  2. Hi there, thanks for the write-up.
    Duration=pulseIn(echoPin,High) just measures the duration between the raising edge and the falling edge of the return pulse, and this is just the pulse width. Doesn’t seem to be the traveling time of the pulse.

    Pls advise.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.