How to Read Data From Ultrasonic Sensor
The HC-SR04 is an inexpensive, piece of cake to use ultrasonic distance sensor, with a range of 2 to 400 cm. It is normally used in obstacle fugitive robots and automation projects. In this tutorial, you volition learn how the sensor works and how to use information technology with Arduino.
I take included 5 examples with a wiring diagram and code and then you lot can offset experimenting with your sensor. We will starting time look at an example that does not employ an Arduino library. Next, I will show y'all how y'all can use theNewPing library to create a more than meaty lawmaking.
Inexpensive ultrasonic altitude/proximity sensors are great merely in some projects, you might need a waterproof sensor like the JSN-SR04T or an IR sensor that isn't influenced by temperature changes. In that case, the articles below might be useful:
- Waterproof JSN-SR04T Ultrasonic Distance Sensor with Arduino Tutorial
- How to use a Precipitous GP2Y0A21YK0F IR Distance Sensor with Arduino
- How to use a Sharp GP2Y0A710K0F IR Distance Sensor with Arduino
- MaxBotix MB7389 weather-resistant altitude sensor tutorial
- MaxBotix MB1240 ultrasonic distance sensor Arduino tutorial
Supplies
Hardware components
| HC-SR04 sensor | × 1 | Amazon |
| Arduino Uno Rev3 | × 1 | Amazon |
Breadboard | × ane | Amazon | |
Jumper wires | ~ 10 | Amazon | |
USB cable type A/B | × 1 | Amazon | |
| twenty×iv character I2C LCD (optional) | × ane | Amazon |
DHT11 sensor (optional) | × 1 | Amazon |
Software
Makerguides.com is a participant in the Amazon Services LLC Assembly Programme, an chapter ad programme designed to provide a means for sites to earn advertising fees by advertising and linking to products on Amazon.com.
How does an ultrasonic altitude sensor work?
Ultrasonic sensors work by emitting sound waves with a frequency that is as well high for a man to hear. These sound waves travel through the air with the speed of sound, roughly 343 thousand/s. If there is an object in forepart of the sensor, the sound waves get reflected back and the receiver of the ultrasonic sensor detects them. By measuring how much time passed betwixt sending and receiving the sound waves, the distance between the sensor and the object can be calculated.
At 20°C, the speed of sound is roughly 343 grand/south or 0.034 cm/µs. Let'south say that the time between sending and receiving the sound waves is 2000 microseconds. If you multiply the speed of audio past the time the sound waves traveled, you become the distance that the sound waves traveled.
Distance = Speed ten Time
Merely that is non the result we are looking for. The distance between the sensor and the object is actually only half this altitude because the sound waves traveled from the sensor to the object and back from the object to the sensor. Then you need to divide the result by two.
Distance (cm) = Speed of audio (cm/µs) × Fourth dimension (µs) / two
And so for the instance this becomes:
Distance (cm) = 0.0343 (cm/µs) × 2000 (µs) / 2 = 34.three cm
Temperature dependence of the speed of sound
The speed of sound actually depends strongly on temperature and to a far lesser degree on the humidity of the air. Wikipedia states that the speed of sound increases with roughly 0.6 m/s per degree Celsius. For nigh cases at 20°C yous can just apply 343 yard/s but if you lot want to get more accurate readings, yous can calculate the speed of sound with the following formula:
Five (m/s) = 331.3 + (0.606 × T)
5 = Speed of sound (m/s)
T = Air Temperature (°C)
This formula doesn't include the humidity since its effect on the speed of sound is merely very minor.
Below yous can notice a tutorial on how to use a DHT11 temperature and humidity sensor to calibrate the speed of sound and go a more authentic altitude reading with the HC-SR04.
How the HC-SR04 works
At the front of the HC-SR04 sensor, yous tin can observe two silver cylinders (ultrasonic transducers), one is the transmitter of the sound waves and the other is the receiver. To let the sensor generate a sonic burst, you need to set the Trig pin high for at least ten µs. The sensor and so creates an 8 bike burst of ultrasound at 40 kHz.
This sonic burst travels at the speed of sound and bounces back and gets received by the receiver of the sensor. The Echo pivot then outputs the time that the audio waves traveled in microseconds.
You tin can utilise thepulseIn()
function in the Arduino code to read the length of the pulse from the Echo pin. After that, yous can use the formula mentioned above to calculate the distance between the sensor and the object.
HC-SR04 Specifications
Operating voltage | 5 V |
Operating electric current | 15 mA |
Frequency | 40 kHz |
Measuring range | 2 – 400 cm |
Resolution | 3 mm |
Measuring angle | 15 degrees |
Trigger input betoken | 10 µs loftier pulse |
Cost | Check price |
For more information you can check out the datasheet beneath:
Wiring – Connecting HC-SR04 to Arduino UNO
The wiring diagram below shows yous how to connect the HC-SR04 sensor to the Arduino.

The code examples below use digital pivot ii and 3 for the trigger and echo pin respectively, simply of course you tin modify this to whatsoever digital pin you want.
HC-SR04 Connections
HC-SR04 | Arduino |
---|---|
VCC | 5 V |
Trig | Pin ii |
Echo | Pin 3 |
GND | GND |
Example code for HC-SR04 with Arduino
Now that you have wired up the sensor it is time to connect the Arduino to the estimator and upload some code. You tin can upload the following example lawmaking to your Arduino using the Arduino IDE. Next, I will explain to you how the lawmaking works.
/* Case lawmaking for HC-SR04 ultrasonic distance sensor with Arduino. No library required. More info: https://www.makerguides.com */ // Ascertain Trig and Echo pin: #define trigPin 2 #define echoPin iii // Define variables: long duration; int distance; void setup() { // Define inputs and outputs: pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); //Begin Series communication at a baudrate of 9600: Serial.begin(9600); } void loop() { // Clear the trigPin by setting it Low: digitalWrite(trigPin, LOW); delayMicroseconds(v); // Trigger the sensor by setting the trigPin high for 10 microseconds: digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, Low); // Read the echoPin, pulseIn() returns the duration (length of the pulse) in microseconds: duration = pulseIn(echoPin, HIGH); // Summate the altitude: altitude = duration * 0.034 / two; // Print the distance on the Serial Monitor (Ctrl+Shift+M): Serial.print("Distance = "); Serial.print(altitude); Serial.println(" cm"); delay(50); }
How the lawmaking works
First, the trigger pin and the echo pin are defined. I phone call themtrigPin
andEchoPin
. The trigger pin is continued to digital pin 2 and the echo pin to digital pin three on the Arduino.
The statement#define
is used to requite a name to a abiding value. The compiler will replace any references to this abiding with the defined value when the program is compiled. So everywhere you mentiontrigPin
, the compiler will supplant it with the value ii when the program is compiled.
// Define Trig and Repeat pin: #define trigPin 2 #define echoPin iii
Next I defined two variables:elapsing
anddistance
. Elapsing stores the time between sending and receiving the sound waves. The distance variable is used to shop the calculated distance.
// Ascertain variables: long duration; int altitude;
In thesetup()
, you lot start by setting the trigPin every bit an output and the echoPin equally an input. Next you initialize serial communication at a baud charge per unit of 9600. Later on yous volition brandish the measured distance in the serial monitor, which can exist accessed with Ctrl+Shift+M or Tools > Serial Monitor. Make sure the baud rate is also set to 9600 in the serial monitor.
void setup() { // Ascertain inputs and outputs: pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); //Begin Serial communication at a baudrate of 9600: Serial.begin(9600); }
In theloop()
, you trigger the sensor by setting the trigPin High for 10 µs. Note that to get a make clean signal yous start by clearing the trigPin by setting it Low for 5 microseconds.
void loop() { // Clear the trigPin by setting it Low: digitalWrite(trigPin, LOW); delayMicroseconds(five); // Trigger the sensor by setting the trigPin high for 10 microseconds: digitalWrite(trigPin, High); delayMicroseconds(10); digitalWrite(trigPin, LOW);
Adjacent, yous need to read the length of the pulse sent by the echoPin. I use the functionpulseIn()
for this. This part waits for the pin to become from LOW to High, starts timing, then waits for the pin to go LOW and stops timing.
After that, you lot can calculate the distance past using the formula mentioned in the introduction of this tutorial.
// Read the echoPin, pulseIn() returns the duration (length of the pulse) in microseconds: duration = pulseIn(echoPin, High); // Calculate the distance: distance = elapsing * 0.034 / 2;
Finally, the calculated altitude is printed in the series monitor.
// Print the distance on the Series Monitor (Ctrl+Shift+M): Serial.print("Altitude = "); Serial.impress(distance); Series.println(" cm"); filibuster(fifty); }
Case lawmaking HC-SR04 with Arduino and NewPing library
TheNewPing library written past Tim Eckel tin can be used with many ultrasonic altitude sensors. The latest version of this library can exist downloaded here on bitbucket.org. You might find that the code beneath, which uses the NewPing library, is a lot shorter than the code we used earlier. Besides that, the NewPing library does include some other nice features. Information technology allows you to set a max altitude to read, it won't lag for a full second when no echo is received and it has a built-in median filter.
You can install the library by going toSketch > Include Library > Add together .Cypher Library in the Arduino IDE.
The library does include some examples that you can use, just you will have to modify them to match your hardware setup. I have included a modified example code below that tin be used with the aforementioned wiring setup as earlier.
/* HC-SR04 ultrasonic altitude sensor with NewPing library example code. More info: www.www.makerguides.com */ // Include the library: #include <NewPing.h> // Define pins and max distance: #define trigPin 2 #define echoPin three #ascertain MAX_DISTANCE 350 // Maximum altitude nosotros want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm. NewPing sonar(trigPin, echoPin, MAX_DISTANCE); // NewPing setup of pins and maximum altitude. bladder elapsing, distance; void setup() { Serial.begin(9600); // Open serial monitor at 9600 baud to see ping results. } void loop() { delay(50); // Wait 50ms between pings (about xx pings/sec). 29ms should be the shortest delay between pings. duration = sonar.ping(); altitude = (duration / two) * 0.0343; Series.impress("Distance = "); Serial.print(distance); // Distance will be 0 when out of set max range. Serial.println(" cm"); }
You lot tin as well usedistance = sonar.ping_cm()
ordistance = sonar.ping_in()
which returns the measured distance in whole centimeters or inches. With this office yous do not need to accept a duration measurement and calculate the distance.
Interfacing ultrasonic sensors in 3 pin mode
The NewPing library also makes information technology easy to interface with ultrasonic sensors while using only 1 I/O pin. This tin be handy if y'all accept very few I/O pins available or if you want to utilise a 3 pin ultrasonic sensor similar the Parallax Ping.
To create a 3 pivot setup (GND, 5V and SIG) y'all have to connect both the trigger pin and the echo pin to the same digital pivot on the Arduino. In the lawmaking, the merely matter yous have to change is line 6-7 and define the aforementioned pin for both the trigPin and the echoPin. For example digital pin 2.
//Define Trig and Echo pin #ascertain trigPin 2 #ascertain echoPin two
How to employ ping_median() digital filter
The main thing I like about the NewPing library is that it has a congenital-in median filter. This filter can profoundly meliorate the accuracy of your HC-SR04 readings. Theping_median()
function takes many duration measurements in a row, throws away the out of range readings and and so averages the remaining ones. By default it will have 5 readings but you can specify how many information technology should accept. Replace line 19 with beneath lines.
int iterations = v; elapsing = sonar.ping_median(iterations);
Case lawmaking HC-SR04 with I2C LCD and Arduino
To display the measured distance on a 2004 or 1602 I2C LCD, all y'all take to do is make the following connections and upload the lawmaking beneath. The HC-SR04 sensor is connected in the same way as earlier.

I2C LCD Connections
I2C LCD | Arduino |
---|---|
GND | GND |
VCC | 5 V |
SDA | A4 |
SCL | A5 |
If you are not using an Arduino Uno, the SDA and SCL pins tin be at a different location. An Arduino UNO with the R3 layout (i.0 pinout), also has the SDA (data line) and SCL (clock line) pin headers shut to the AREF pin. Check the tabular array below for more details.
Board | SDA | SCL |
---|---|---|
Arduino Uno | A4 | A5 |
Arduino Nano | A4 | A5 |
Arduino Micro | 2 | iii |
Arduino Mega 2560 | twenty | 21 |
Arduino Leonardo | ii | three |
Arduino Due | 20 | 21 |
The lawmaking uses theLiquidCrystal_I2C library, which you can download here on GitHub. Make sure that you have this exact library installed! It also includes theWire.h library, which allows you to communicate with I2C devices. This library should come up pre-installed with the Arduino IDE.
If y'all desire to learn more about how to control a I2C LCD with Arduino, you tin can check out the total tutorial here.
- How to control a grapheme I2C LCD with Arduino
/* HC-SR04 ultrasonic distance sensor with Arduino and I2C LCD example code. More than info: https://www.makerguides.com */ // Include the libraries: #include <Wire.h> #include <LiquidCrystal_I2C.h> // Define Trig and Echo pin: #define trigPin two #ascertain echoPin 3 // Define SDA and SCL pin for LCD: #define SDAPin A4 // Data pin #ascertain SCLPin A5 // Clock pin // Connect to LCD via I2C, default address 0x27 (A0-A2 not jumpered): LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27,20,four); //Change to (0x27,16,2) for 1602 LCD // Define variables: long elapsing; int distance; void setup() { // Define inputs and outputs: pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); // Initiate the LCD: lcd.init(); lcd.backlight(); } void loop() { // Clear the trigPin by setting it LOW: digitalWrite(trigPin, LOW); delayMicroseconds(v); // Trigger the sensor past setting the trigPin loftier for 10 microseconds: digitalWrite(trigPin, Loftier); delayMicroseconds(ten); digitalWrite(trigPin, Low); // Read the echoPin. This returns the duration (length of the pulse) in microseconds: duration = pulseIn(echoPin, HIGH); // Calculate the altitude: distance = elapsing*0.034/2; // Display the altitude on the LCD: lcd.setCursor(0,0); // Set up the cursor to column 1, line 1 (counting starts at zero) lcd.print("Distance = "); // Prints string "Display = " on the LCD lcd.print(distance); // Prints the measured altitude lcd.print(" cm "); // Prints "cm" on the LCD, extra spaces are needed to articulate previously displayed characters delay(50); }
Note that I used a 20 x iv LCD brandish. If you take a different size LCD (sixteen 10 2 is besides common) yous need to modify line 20 toLiquidCrystal_I2C lcd(0x27,xvi,2);
. If your LCD doesn't have the default I2C address, 0x27, check out the consummate I2C tutorial where I explain how y'all can find out what the accost is.
Example code HC-SR04 with DHT11 temperature sensor and Arduino
As mentioned earlier, the speed of audio strongly depends on the air temperature. If you want to measure out long distances (3-4 grand) it can be a skilful idea to add a DHT11 or DHT22 temperature and humidity sensor to your setup. This volition allow you to calibrate the speed of sound in real time and thereby increase the accurateness of your measurements.
Adding a DHT11 sensor is actually simple. The wiring diagram below shows you which connections you need to make. Annotation that I am using a DHT11 with a breakout board, and then I just need to wire up three pins. Be sure to cheque the label of the sensor,the order of the pins can be different depending on the manufacturer. The HC-SR04 sensor is connected in the aforementioned way as before.

DHT11 Connections
DHT11 | Arduino |
---|---|
VCC (+) | 5 5 |
Signal (s) | Pin 4 |
GND (-) | GND |
The code below uses theAdafruit DHT Humidity & Temperature Sensorlibrary which y'all can download here on GitHub. This library only works if you too have theAdafruit_Sensorlibrary installed, which is also available on GitHub. Yous can also download the two libraries past clicking on the buttons beneath:
Yous tin click the button in the top right corner of the lawmaking field to copy the code.
/* HC-SR04 ultrasonic distance sensor with DHT11 and Arduino case lawmaking. More info: https://www.makerguides.com */ // Include Adafruit sensor library: #include <Adafruit_Sensor.h> //https://github.com/adafruit/Adafruit_Sensor // Include Adafruit DHT library: #include <DHT.h> //https://github.com/adafruit/DHT-sensor-library // Define Trig pin, Echo pin and DHTPin: #ascertain trigPin two #define echoPin 3 #ascertain DHTPin 4 // Define DHT sensor type: #define DHTType DHT11 // Define variables: long duration; int distance; float speedofsound; // Create a DHT sensor object: DHT dht = DHT(DHTPin,DHTType); void setup() { // Define inputs and outputs: pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); dht.begin(); // Begin Serial advice: Serial.begin(9600); // Starts the serial communication } void loop() { // Clear the trigPin by setting it Low: digitalWrite(trigPin, Low); delayMicroseconds(5); // Trigger the sensor by setting the trigPin high for 10 microseconds: digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); // Read the echoPin. This returns the duration (length of the pulse) in microseconds: elapsing = pulseIn(echoPin, Loftier); // Read the temperature: float temperature = dht.readTemperature(); // Calculate speed of sound in m/s: speedofsound = 331.3+(0.606*temperature); // Summate the altitude in cm: distance = elapsing*(speedofsound/10000)/2; // Print the distance and temperature on the Series Monitor: Serial.print("Temperature = "); Serial.impress(temperature); Serial.impress(" Celsius"); Serial.print(", Distance = "); Serial.print(distance); Serial.println("cm"); delay(100); }
Example code HC-SR04 with DHT11 and I2C LCD

The lawmaking below can be used to combine all 3 examples in a higher place. It displays both the temperature, the speed of sound and the measured distance on the LCD.
/* HC-SR04 ultrasonic altitude sensor with DHT11, I2C LCD and Arduino example code. More than info: https://www.makerguides.com */ // Include Adafruit sensor library: #include <Adafruit_Sensor.h> // https://github.com/adafruit/Adafruit_Sensor // Include Adafruit DHT library: #include <DHT.h> // https://github.com/adafruit/DHT-sensor-library #include <Wire.h> // Library for I2C advice #include <LiquidCrystal_I2C.h> // Library for LCD // Define Trig pin, Echo pin and DHTPin: #define trigPin 2 #define echoPin 3 #ascertain DHTPin 4 // Define SDA and SCL pivot from LCD: #define SDAPin A4 // Data pin #ascertain SCLPin A5 // Clock pin // Connect to LCD via i2c, default address 0x27 (A0-A2 not jumpered): LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27,xx,4); // Define DHT sensor type: #ascertain DHTType DHT11 // Define variables: long duration; int altitude; float speedofsound; // Create a DHT sensor object: DHT dht = DHT(DHTPin,DHTType); void setup() { // Ascertain inputs and outputs: pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); dht.begin(); // Initiate the LCD: lcd.init(); lcd.backlight(); // Brainstorm Serial communication at a baudrate of 9600: Series.brainstorm(9600); } void loop() { // Clear the trigPin by setting it LOW: digitalWrite(trigPin, Depression); delayMicroseconds(5); // Trigger the sensor past setting the trigPin high for 10 microseconds: digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); // Read the echoPin. This returns the duration (length of the pulse) in microseconds: duration = pulseIn(echoPin, Loftier); // Read the temperature: int temperature = dht.readTemperature(); // Summate speed of audio in m/s: speedofsound = 331.3+(0.606*temperature); // Calculate the distance in cm: altitude = duration*(speedofsound/10000)/2; // Print the altitude and temperature on the Series Monitor: lcd.setCursor(0,0); lcd.impress("Temperature: "); lcd.impress(temperature); lcd.print(" " "\xDF" "C"); lcd.setCursor(0,1); lcd.impress("Speed: "); lcd.impress(speedofsound); lcd.print(" m/south "); lcd.setCursor(0,ii); lcd.print("Distance: "); lcd.print(altitude); lcd.print(" cm "); delay(100); }
HC-SR04 Dimensions
Below you can find the dimensions of the HC-SR04 ultrasonic sensor. I accept noticed that there are some small differences between manufacturers, and so I recommend double-checking against your own sensor.

HC-SR04 CAD
I have created basic CAD drawings of the HC-SR04 ultrasonic sensor that you can download beneath.
Determination
In this article, I have shown y'all how the HC-SR04 ultrasonic distance sensor works and how you can apply it with Arduino. I promise you found it useful and informative. If you did,please share it with a friend that also likes electronics!
Personal project: A couple of months ago I built an interactive wall installation with some friends. Nosotros used around 30 ultrasonic distance sensors to observe people walking in front end of the wall. The wall included lights and sound effects that changed depending on how far away people were continuing.

I would love to know what projects y'all plan on building (or have already built) with the HC-SR04 altitude sensor. If you take whatsoever questions, suggestions or if you lot think that things are missing in this tutorial,please go out a comment down below.
Note that comments are held for moderation to prevent spam.

Source: https://www.makerguides.com/hc-sr04-arduino-tutorial/
0 Response to "How to Read Data From Ultrasonic Sensor"
Postar um comentário