Hc-sr04 Ultrasonic Distance Sensor

68,647

92

20

Published

Introduction: Hc-sr04 Ultrasonic Distance Sensor

About: My name is Zach Sousa and I'm a Canadian highschool student that has a passion for making.

In this instructable I will show you how to make an ultrasonic sensor (hc-sr04) that measures distances up to 200 cm.


Step 1: Parts and Tools

These are the parts and tools needed to make this project:

Step 2: Attach Ultrasonic Sensor

Attach the ultrasonic sensor to the breadboard and attach 4 wires from the rails corresponding to the pins on the ultrasonic sensor.

Step 3: Connect the Arduino to Appropriate Pins

Connect the trig. Pin to pin 12 on the arduino and the echo pin to pin 11 and connect the negative and positive pins to the negative and positive rails on the breadboard.

Step 4: Connect Negative and Positive Pins

Connect the negative rail on the breadboard to the negative pin on the arduino and the positive rail on the breadboard to the 5 volt pin on the arduino.

Step 5: Get NewPing Library

Step 6: Upload Test Code


#include <NewPing.h>
#define TRIGGER_PIN 12;
#define ECHO_PIN 11;
#define MAX_DISTANCE 200;

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

void setup() {
Serial.begin(115200);
}

void loop() {
delay(50);
unsigned int uS = sonar.ping();
Serial.print("Ping: ");
Serial.print(uS / US_ROUNDTRIP_CM);
Serial.println("cm");
}

Step 7: Test by Using Serial Monitor

Open the serial monitor in the arduino IDE and Set the baud rate to 115200 and move your hand in front of the sensor and look at the serial monitor you should see the distance change on the serial monitor.

Step 8: Going Further... Adding an Led

If you want to use an led to indicate the distance you can connect an led to pin 13 and negative and upload this code:
// ---------------------------------------------------------------------------
// Example NewPing library sketch that does a ping about 20 times per second.
// ---------------------------------------------------------------------------
#define ledPin 13
#include <NewPing.h>

#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() {
pinMode (ledPin, OUTPUT);
Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}

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 > 20) { // This is where the LED On/Off happens
digitalWrite(ledPin,HIGH); // When the Red condition is met, the Green LED should turn off

}
else {
digitalWrite(ledPin,LOW);

}
if (uS / US_ROUNDTRIP_CM <= 20 || uS / US_ROUNDTRIP_CM >= 0){

}
else {
Serial.print(uS / US_ROUNDTRIP_CM);
Serial.println(" cm");
}
delay(500);
}

3 People Made This Project!

Recommendations

  • Oil Contest

    Oil Contest
  • Creative Misuse Contest

    Creative Misuse Contest
  • Clocks Contest

    Clocks Contest

20 Discussions

0
user
MihirC

2 years ago

ERORRS FACED WHILE USING NEW PING LIBRARY FOR MEDIATEK LINKITONE!!

C:\Program Files (x86)\Arduino\hardware\arduino\mtk\libraries\NewPing\NewPing.cpp: In constructor 'NewPing::NewPing(uint8_t, uint8_t, unsigned int)':

C:\Program Files (x86)\Arduino\hardware\arduino\mtk\libraries\NewPing\NewPing.cpp:16:47: error: 'digitalPinToBitMask' was not declared in this scope

_triggerBit = digitalPinToBitMask(trigger_pin); // Get the port register bitmask for the trigger pin.

^

C:\Program Files (x86)\Arduino\hardware\arduino\mtk\libraries\NewPing\NewPing.cpp:19:66: error: 'digitalPinToPort' was not declared in this scope

_triggerOutput = portOutputRegister(digitalPinToPort(trigger_pin)); // Get the output port register for the trigger pin.

^

C:\Program Files (x86)\Arduino\hardware\arduino\mtk\libraries\NewPing\NewPing.cpp:19:67: error: 'portOutputRegister' was not declared in this scope

_triggerOutput = portOutputRegister(digitalPinToPort(trigger_pin)); // Get the output port register for the trigger pin.

^

C:\Program Files (x86)\Arduino\hardware\arduino\mtk\libraries\NewPing\NewPing.cpp:20:59: error: 'portInputRegister' was not declared in this scope

_echoInput = portInputRegister(digitalPinToPort(echo_pin)); // Get the input port register for the echo pin.

^

C:\Program Files (x86)\Arduino\hardware\arduino\mtk\libraries\NewPing\NewPing.cpp:22:75: error: 'portModeRegister' was not declared in this scope

_triggerMode = (uint8_t *) portModeRegister(digitalPinToPort(trigger_pin)); // Get the port mode register for the trigger pin.

1 reply

Hi, MihirC

Did you solve the problem, I am using the same board.

0
user
MihirC

2 years ago

Hello Sir! I face a similar problem working with ultrasonic sensors. The data provided by ultrasonic sensor is stuck to out of range!! i.e. 0.. Can you please provide me with some suggestion on how to solve this problem??

Thanks for the info here, especially NewPing - much easier to understand than the original library. I do have a problem though when the sensor is out of range, as do a number of my students, using both the old library and NewPing. Most of the time (maybe 80% of the time), I correctly get a distance of 0 cm as per the example NewPing code but 20% of the time with nothing going on or getting in the way, the sketch reports a distance of 4cm and then returns to 0 cm on the next ping. I've tried changing Arduino pins and various delays to no avail. Any idea what causes this behavior? I don't have anything except the SR04 in my circuit (no LED). I also set my serial monitor speed to 9600 in case it was swamping the Arduino.

void loop() {

int uS = sonar.ping();

Serial.print("Ping: ");

Serial.print(uS / US_ROUNDTRIP_CM);

Serial.println("cm");

delay(550);

}

0
user
mzbas

2 years ago

the solution to the sensor being stuck at zero is in this link. its the 2. post, by docdoc.

You just add

"pinMode(ECHO_PIN,OUTPUT);

digitalWrite(ECHO_PIN,LOW);

pinMode(ECHO_PIN,INPUT);"

after the line

"unsigned int uS = sonar.ping();"

link: http://forum.arduino.cc/index.php?topic=55119.15

I have successfully done this project. But there is a problem during the operation, whenever the sensor goes to out of range, it does not ping more. If I touch the backside board of the sensor then it start again. So what is the problem?

1 reply

the solution to the sensor being stuck at zero is in this link. its the 2. post, by docdoc.

You just add

"pinMode(ECHO_PIN,OUTPUT);

digitalWrite(ECHO_PIN,LOW);

pinMode(ECHO_PIN,INPUT);"

after the line

"unsigned int uS = sonar.ping();"

link: http://forum.arduino.cc/index.php?topic=55119.15

I hope there is a new instructions for "How to connect the Ultrasonic sensor to WTV020 with Arduino"

If you want you can add an LED. I programmed mine that if the distance ( cm ) is smaller than 100 it you be OFF.

#include <NewPing.h>

#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 450 // 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(115200); // Open serial monitor at 115200 baud to see ping results.

pinMode(13,OUTPUT); // pin pe 13, fara rezistenta

}

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

analogWrite(13, 255);

else

analogWrite(13, 0);

}

The specs on the HC-SR04 says it can read up to 400cm. I downloaded your program and can't seem to get it anywhere near that, even after changing the range to 400. Is there an assumption in NEWPING code that constrains the measurement?

#include <NewPing.h>


#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(115200); // Open serial monitor at 115200 baud to see ping results.
}

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");




here's my sketch and it does not work ?

3 replies

cool thanks, I wanted to check out my sensor, this did the trick, now if I can figure out how to change it to inches so I can understand what it is saying, I am metric illiterate even though I did 8 years in the Army, all we dealt with was meters and kilometers. I think I saw that formula somewhere back when I began trying to get up and running. I will save your code to work with if that is OK.

I tried your code, the only problem I had with it was the ending } was missing, it compiled and uploaded to my uno just fine and works great after I set the Serial Monitor to 115200 baud. Thanks a million I don't know why you can't get it working unless you haven't installed the library properly

Sorry when I paste in the code from the arduino IDE it sometimes changes the format of the code (some semicolons went missing and comments went to the next line) try it out now I have edited it and there arent any comments in the code

when I type #include <NewPing.h> it dosn't become orange and so when I try to correct the sketch this message appears :

'newPing' does not name a type

Make sure to include the <NewPing.h> after #include like how it is in the picture of the code. it is not in the code posted above. you will have to type it in

1 reply

I copied NewPing Library in my Library folder under Arduino folder in my Program Files post which the Code worked flawlessly.

I had ordered 2 HC-SR04, one from Simple Labs and another from Amazon. I was able to test them both using this code. Thank you.