Introduction: Ultrasonic Range Detector Using Arduino and the SR04 Ultrasonic Sensor

Picture of Ultrasonic Range Detector Using Arduino and the SR04 Ultrasonic Sensor

This is a preliminary instructable that will take you through the steps I took to get the SR04 ULTRASONIC SENSOR  connected  and working to the Arduino. It will then be incorporated to my mini environment monitor.  Eventually, if it all fits, it will end up in a Startrek  toy tricorder casing I found in my junk box..

Step 1: Connecting the SR04 Ultrasonic Sensor to the Arduino

Picture of Connecting the SR04  Ultrasonic Sensor to the Arduino

Step 2: Parts List

Picture of Parts List

1               Arduino uno R3, or any Arduino for that matter
1               SR04 Ultrasonic Sensor
1               breadboard
4               Jumper Wires

Step 3: Connect Ultrasonic Sensor to Arduino

Picture of Connect  Ultrasonic Sensor to Arduino

You Need 4 Jumper wires to conect the SR04 Ultrasonic Sensor to the Arduino:

1  From the SR04  VCC pin to the Arduino 5v
1 From the SR04  GND pin to the Arduino GND
1 From the SR04  TRG pin to the Arduino Digital pin 12
1 From the SR04  ECHO pin to the Arduino Digital pin 11

That's All The wireing you need... Easy,  no?

Next Step, load the Software library and sketches.

Step 4: Step 4 Download SR04 Library and Install to Arduino IDE

Picture of Step 4 Download SR04 Library and Install to Arduino IDE

You need to download another Library  to get the Arduino to talk with the SR04 sensor. The sensor I got didn't come with any documentation, so I Googled around until I found a library that works.
I found an optimized library here
Download the library unzip it,  and install it in the Arduino IDE. Place it inside your Arduino libraries folder , and restart the Arduino IDE. For convenience, I included the file  in  the files section below.

You should now be able to see the  library and examples in  select File > Examples > NewPing > NewPingexample sketch.
load the sketch to your Arduino.

If you were successful at installing the libraries, and loading the NewPingexample sketch,  Compile the sketch  by clicking on the verify button and make sure there are no errors.

It's time to connect your Arduino to your PC using the USB cable.  Click on the upload button  to upload the sketch to the Arduino.

Once uploaded to the Arduino, open the serial monitor, and you should see the distance  data stream   coming from the sensor.

Step 5: Final Step and Preview of the Sensor Conected to My Mini Enviroment Monitor, Soon to Be Tricorder.


LydiaR16 (author)2017-03-29

I hooked up two sensors using the same pins. The serial monitor shows the closest distance of the two.

JohnH845 (author)2017-02-28

Hey guys, I work with livestock animals, one of my duties it to make sure all feed bins never run out of feed. So, how I incorporate this concept into my application? Basically I would like to install the ultrasonic sensor inside the feed bin, measuring the distance from the top of the bin to feed below, then I would like the info to be transmitted to a LCD screen inside my feed making facility in the form of a graph. Can someone point in th right direction? Thank You!

raspio (author)2017-02-25

boss the program is working but display in serial monitor irrelevant

raspio (author)2017-02-25

error compiling on the board

mniyaz (author)2016-12-15

Hi, I used the same code. The sensor is giving wrong data, it shows only around half of the distance. Say if actual distance is 60cm's it returns 30cm's.

DavidM458 (author)2016-07-11

hi, how can i use one ultrasonic sensor to obtain two readings and compute area

kavalcoco (author)2016-07-05

I will build it tomorrow . I want to install it to measure hight of water in our pond and display the result in my room. I have all the parts, and hope to complete and test tomorrow. Thanks for clear instructions

RohanG28 (author)2016-04-26

hey guys i got the 0cm all the time problem too, and then some weird characters.

the problem was that the baud rate in the program was 115200 and the baud rate in the serial monitor(lower right) was set to the default 9600. change it to 115200 and you'll be set :D

BrunoS35 (author)RohanG282016-06-10

Thanks a lot, Rohan. I had not realized it, but got it working now...

ChrisP278 (author)RohanG282016-04-27

You might have the wires reversed

Try swapping the wires or swapping the pin numbers in the code

Lee Wilkerson (author)2016-06-01

The link you have listed in step 4 no longer works. The new one:

RaviP82 (author)2016-05-31

For some waterproofing experiment, I covered my receiver and trigger alternately with thin latex film getting correct reading. Then I covered both the receiver and transmitter with latex but now I am getting -1,means the pulse is not getting received.

kunj kapadia (author)2016-04-29

Arduino: 1.7.10 (Windows 8.1), Board: "Arduino Uno"

C:\Users\DELL\AppData\Local\Temp\build6771404923751407265.tmp/core.a(wiring.c.o): In function `delay':

C:\Users\DELL\Desktop\Saraswati Diksha\Arduino\hardware\arduino\avr\cores\arduino/wiring.c:114: undefined reference to `yield'

collect2.exe: error: ld returned 1 exit status

Error compiling.

This report would have more information with

"Show verbose output during compilation"

enabled in File > Preferences.

m.sathyap (author)2016-03-19

can I use both serial monitor and lcd in this project

SyedA58 (author)m.sathyap2016-04-16

yes u can..

SyedA58 (author)SyedA582016-04-16

Seril,println( distance );


blockswitch (author)2016-04-13

outputs this

Ping: 22cm


Ping: 7cm

Ping: 7cm

Ping: 7cm

Ping: 8cm

ing: 7cm

Ping: 8cm

Ping: 7cm

Ping: 8cm

Ping: 8cm

Ping: 8cm

Ping: 22cm

Ping: 8cm


Sermshar made it! (author)2016-03-21

Success! I had problems with it showing 0cm but fixed it by using different breadboard connections. Did a tutorial mashup and learned how to use the "Processing" app to graph it, I also made it change color if it was out of range.

JurieP (author)2015-06-30

I also had a problem with it reporting 0cm all the time. I finally figured out that the echo input pin for some reason was stuck on high. Adding the following line of code before conducting a sonar ping solved it: digitalWrite(ECHO_PIN, LOW);

mg53 (author)JurieP2016-02-24

Aim the sensor at a wall or other large solid object within 30cm. Just mentioning this on the off chanch that you haven't tried this. Good luck!

JusthatchedT (author)JurieP2015-07-20

I am having a problem of getting 0cm all the time. I tried using digitalWrite(ECHO_PIN,LOW) but its still giving 0cm

I changed the echo pin from 11 to 13 and it started working.However if the target is moved or I move the breadboard around. Sometime it resets to 0 and then doesn't recover :-(

MaahirX made it! (author)2015-08-27

after click serial port monitor showed me this type of data stream

plz what i should do to fix

tim.miles.f (author)MaahirX2015-09-09

According to the example code(that i got from the library anyway), the baud rate is at 115200. Your picture shows you are reading the data with 9600 baud, the default setting. Try switching to different baud rates(just click on it 115200 is part of 'em) or change the line in the code that chooses the baud rate aka Serial.begin(whatevernumberyouwant); Hopes this fixes your problem.

Drdray1 (author)tim.miles.f2016-01-30

Haha i had the same issue. Thanks!

tim.miles.f (author)Drdray12016-01-31

Np glad i could help :)

DorT1 (author)2016-01-05

Great project!

I made this game for drones with the same components!

FilipN3 (author)2015-12-16

great tutorial !! thanks :-)

RafaelO14 (author)2015-12-04

Hi I followed every step correctly and when I go to upload the program to the Arduino I get a " Exit Status 1 Error Compiling" What can this be, is there a solution to this?

Fatemeh Mohammadi (author)2015-11-26

Hi do you know about signal in dangrees

road bend,project?

NikhilS29 (author)2015-09-21

I set the baud rate but my sensor is continuously receiving the data....the data on serial monitor is coming very fast.It is not stopping.Why?

Thanks in adavance for any help.

ArunV13 (author)NikhilS292015-10-01

i think u hav to put a delay in the loop to make a time gap b/w 2 successive fetches...

MehdiL2 (author)2015-09-13

vivek87799 made it! (author)2015-09-13

Awesome tutorial. I tried it and it worked for me. thank you.

Hassan.Meligy94 (author)2015-08-12

please i want help

i build quad copter detect fish in water

how to use Ultrasonic Range detector to detect fish in water please help me

Nautis (author)Hassan.Meligy942015-08-20

Water reflects ultrasonic waves (when using the module above) which means you cant detect the fish. There are ultrasonic sensors which are placed INTO the water. But thats not what you are looking for when operating from a quadcopter.

Andréso3 (author)2015-06-10

piñas onjde descargo er minecrá?

tomasm9 (author)Andréso32015-06-10

aka tdejo la link

tomasm9 (author)2015-06-10

hay ya entiendo estan jugando maincrá

Andréso3 (author)tomasm92015-06-10

no seras tu aki el mas pussydestroyer?

tomasm9 (author)Andréso32015-06-10

onde vas loko yo tengob espada de diamont of cours

dferraro1 made it! (author)2015-05-28

Just done, it's my first try with this sensor. I only change Serial.begin to 9600 and monitor also works.


suryaS2 (author)2015-04-29

hii, when i am uploading it to my arduino uno. i am getting error like:

avrdude: ser_open(): can't set com-state for "\\.\COM13".

please help me. thank you

EdizonBlu (author)2015-03-31

Hi guys, I would like to ask on how to stabilize my ultrasonic sensor mounted in a servo motor. It is because everytime an "Out of Range" displays in the serial monitor it gives current to the servo motor causing it to sweep. The possibility of sweeping the servo left or right only is when there is an object being detected. BTW, the ultrasonic sensor is mounted above the servo mtor.

Here is my code://

Code: [Select]

#define trigPin 13
#define echoPin 12
#define led 11
#define led2 10
#include <Servo.h>
int pos = 0; // variable to store the servo position
int defPOS = 0;

Servo myservo;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(led, OUTPUT);
pinMode(led2, OUTPUT);


void loop() {
long duration, distance;
digitalWrite(trigPin, LOW); // Added this line
delayMicroseconds(2); // Added this line
digitalWrite(trigPin, HIGH);
// delayMicroseconds(1000); - Removed this line
delayMicroseconds(10); // Added this line
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
//0 Left
//1 Center
//2 Right
int buttonState1 = digitalRead(led); //red
int buttonState2 = digitalRead(led2); //green
if( (buttonState1 == 0 && buttonState2 == 1) && (defPOS != 1))
if(defPOS == 2)
for(pos = 0; pos <= 90; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(2); // waits 15ms for the servo to reach the position
else if(defPOS == 0)
for(pos = 0; pos <= 90; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(2); // waits 15ms for the servo to reach the position
defPOS = 1;

if (distance < 30) { // This is where the LED On/Off happens
digitalWrite(led,HIGH); // When the Red condition is met, the Green LED should turn off
if(defPOS == 0)
for(pos = 90; pos>=0; pos-=1) // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(2); // waits 15ms for the servo to reach the position
defPOS = 2;
else if(defPOS == 2)
for(pos = 0; pos <= 90; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(2); // waits 15ms for the servo to reach the position
defPOS = 1;
else if(defPOS == 1)
for(pos = 0; pos <= 180; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(2); // waits 15ms for the servo to reach the position
defPOS = 0;
// delay(1000);
else {

if (distance >= 400 || distance <= 0){
Serial.println("Out of range");
else {
Serial.println(" cm");

pigman_uk (author)2014-04-04

I used a MiniPro and added a i2c 16 X 2 LCD Display. Here is the battery operated version. Note that the output from the 12v battery pack must go to the RAW pin of the MiniPro and not the Vcc otherwise it will emit a small puff of smoke and die.

loradwan (author)pigman_uk2015-03-29

wow man great work i want to know about connections between LCD and arduino

DhireshN (author)pigman_uk2014-12-30

How do you use the LCD display with an arduino uno. Please send me the instructions for this. I wanted to make this for a long time

pigman_uk (author)DhireshN2014-12-30

This is the sketch I use to add an LCD display to a project.
It uses 2 libraries. Wire and LiquidCrystal_i2C.


//Compatible with the Arduino IDE 1.0

//Library version:1.1

#include <Wire.h>

#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x27 for a 16 chars and 2 line display

void setup()


lcd.init(); // initialize the lcd

// Print a message to the LCD.


lcd.print("Hello, world!"); //display top line

lcd.setCursor(0,1); //set cursor to first character of line 2

lcd.print("Hello Mars too"); //display to line 2


void loop()



pigman_uk (author)DhireshN2014-12-30

There are 2 ways to connect the LCD display to the Arduino so it depends which display you have bought. Essentially there is the parallel way which has lots of wires for each data line or the serial way (i2C) which uses only 4 wires (including the Vcc & Gnd). Once you have the right display (which has a serial converter board on the back) life becomes much easier. So lets find out which display you've bought please ?

johnag (author)pigman_uk2014-04-15

cool project, just try not to burn too many componemts!

About This Instructable




More by johnag:Arduino Portable EKG MonitorArduino Color LCD Message Clock Arduino  DEMO series
Add instructable to: