Instructables
loading
loading

Ultrasonic Range detector using Arduino and the SR04 Ultrasonic sensor

Picture of Ultrasonic Range detector using Arduino and the SR04 Ultrasonic sensor
WP_20130612_005.jpg
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..
 
Remove these adsRemove these ads by Signing Up

Step 1: Connecting the SR04 Ultrasonic Sensor to the Arduino

Picture of Connecting the SR04  Ultrasonic Sensor to the Arduino
WP_20130612_010.jpg
WP_20130612_008.jpg

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
WP_20130612_007.jpg
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
WP_20130613_010.jpg
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.

suryaS223 days ago

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

EdizonBlu1 month ago

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);
myservo.attach(9);
myservo.write(0);

}

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))
{
delay(2000);
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
digitalWrite(led2,LOW);
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;
}
//myservo.write(180);
// delay(1000);
//myservo.write(0);
}
else {
digitalWrite(led,LOW);
digitalWrite(led2,HIGH);
}

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

pigman_uk1 year ago

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.

DSC_0398a.jpg

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

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

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

//DFRobot.com

//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.backlight();

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()

{

}

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_uk1 year ago

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

can anyone tell me what is the maximum range of this ultrasonic sensor??

i need a sensor with a range of atleast 4-5 mts,should i go for this??

DhireshN4 months ago

Hi, I love doing new things with the Arduino Uno I have. I have connected the wires correctly and have downloaded the NewPing file and added it to the arduino library. Once I upload the sketch and open the serial monitor I don't recieve any data. Please help!

20141230_224114[1].jpg20141230_224129[1].jpg

Your Power and Ground are the opposite of my board...mine is working. IF this was connected backwards, you may have bigger problems. Best of Luck!

-fab

kumarsrt3 months ago

hello sir can im doing obstacle avoidance robot with vacuum cleaning robot.im need to use 3 ultrasonic HC-SR04 sensors in front of the robot.can i connect VCC and Gnd pin directly to the regulated 5V from IC7805 will affect the working of sensors.if not is there any way to connect 3 sensors.

kumarsrt3 months ago

hello sir can im doing obstacle avoidance robot with vacuum cleaning robot.im need to use 3 ultrasonic HC-SR04 sensors in front of the robot.can i connect VCC and Gnd pin directly to the regulated 5V from IC7805 will affect the working of sensors.if not is there any way to connect 3 sensors

kumarsrt3 months ago

hello sir can im doing obstacle avoidance robot with vacuum cleaning robot.im need to use 3 ultrasonic HC-SR04 sensors in front of the robot.can i connect VCC and Gnd pin directly to the regulated 5V from IC7805 will affect the working of sensors.if not is there any way to connect 3 sensors

duhonarrain3 months ago

i want the ultrasonic sensor to measure a constant distance(eg 5cm), i want to use it under water to do wall following..can any one help.

viswadevan3 months ago

Hi Do you any idea how to activate a relay when the ultrasonic sensor detects a presence?

viswadevan3 months ago

Hi Do you any idea how to activate a relay when the ultrasonic sensor detects a presence?

fansblink made it!5 months ago

Cool...............

IMG_20141126_224104.jpg
can i use more than one ultrasonic sensor with arduino uno
and if not which arduino should I buy to use several ultrasonic
chong.sime6 months ago

Hi, I am very new in Arduino and programming. I have recently purchased a SR04 and got it working in detecting distance.

Is there a way to turn off the emitter, and only produce the graph of ultrasonic sound wave produced by other sources? In other words, i just wanna make use of the ultrasonic receiver.

Thanks.

psycho.maggot6 months ago

i've following the instructions, but after i finish, the result just 0cm 0cm 0cm on the serial monitor, whats wrong with this?.. did my sensors got error?.. seems the code was right. help me please.

For anyone wondering how to use this with servos, as in; "if a certain distance is measured stop servo motors" I have managed to change the code slightly allowing for this, Enjoy!

// ---------------------------------------------------------------------------

// Example NewPing library sketch that does a ping about 20 times per second.

// ---------------------------------------------------------------------------

#include <NewPing.h>

#include <Servo.h>

Servo myservo;

#define TRIGGER_PIN 12 // Arduino pin tied to trigger pin on the ultrasonic sensor.

#define ECHO_PIN 11 // Arduino pin tied to echo pin on the ultrasonic sensor.

#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

void setup() {

Serial.begin(9600); // Open serial monitor at 9600 baud to see ping results

myservo.attach(9);

}

void loop() {

delay(50); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.

unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).

Serial.print("Ping: ");

Serial.print(uS / US_ROUNDTRIP_CM); // Convert ping time to distance in cm and print result (0 = outside set distance range)

Serial.println("cm");

if(uS / US_ROUNDTRIP_CM < 10) {myservo.write(82);}

if(uS / US_ROUNDTRIP_CM > 10) {myservo.write(180);}

}

saymowan8 months ago

Cool project! :D

chestef8 months ago

I am extremely interested in the many applications of this type of sensor I find on "Instructibles.

What is the sensitivity of these sensors? I wish to control a probe that will extend to an object and stop at a distance closer than the 3mm I see in advertising.

Can anyone clarify if I can use this type of sensor and is it variable, say through a potentiometer, to set the range closer than 3mm?

I will certainly post my project if I can get throught this type of hurdle.

John Johnson

LeoZ19 months ago

Thanks for the nice and straightforward tutorial! One problem is occurring for me: I hooked up the Ping sensor like shown and I keep getting 0cm. In the example code, a value of 0cm is stated to be "outside set distance range." What does this mean and how can I fix it?

framirez111 year ago

Hi, really straightforward, easy and useful instructable. Thanks!
I wonder if the New Ping library supports analog input pins, or can this even be done with these sensors?

johnag (author)  framirez111 year ago

I haven't heard of any ultrasonic analog sensors...

pigman_uk1 year ago

I've added an i2c LCD display and this works great .. can someone explain why the maximum distance using the NewPing library is not as far as the normal non-interrupt method ? Thanks for the article .. well explained and it works.

T-_-K1 year ago

how to connect the SR04 with a 3pins sensor shield, i need a work around

I just received one of these, haven't found a practical purpose but did take note of the fact that Cats can here the sound clearly.

It could be much better if you expand this tutorial in order to build more complex robotics applications with ultrasonic sensors
ricarz161 year ago
well, it works, but there are just two conditions, 0cm and 1423cm i don´t know why? is my sensor defect? or am i just a little noob who cannot connect four wires... :(
fgarci031 year ago
When I open the serial monitor it just writes non-sense random characters there, everything on the same line.

Any idea what it might be?
Ok I found it. Just changed "Serial.begin(115200); to Serial.begin(9600);"

The Serial Monitor is 9600baud by default, so in order for the sketch to work, you either have to change the code like I said, or manually change the "speed" of the serial monitor on the dropdown menu of it.

Nice! Been messing with my SR04 for a couple of hours and I love it :)
johnag (author)  fgarci031 year ago
Glad you could help yourself.. You could also change the baud rate in the serial monitor, in the bottom right there is a pull-down option to change the TX rx speed..good job