NewPing Library: HC-SR04, SRF05, SRF06, DYP-ME007, Parallax PING))) - v1.7

Edwooong:
Good day ! i'm currently making a project (distance measuring device) that can measure distance max range of 500cm by using HC-SR04.
Now what ive noticed measuring distance from 1 to 200 cm is accurate but when it reaches 300,400,500cm it will now have an error of 5-10cm. Im new to arduino programming and i think one problem is my code . thanks in advance.

This is the code im using:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const int trigPin = 9 ;
const int echoPin = 10;
long duration;
int distanceCm, distanceInch;

void setup() {
Serial.begin(9600);
lcd.begin(16,2);
pinMode(trigPin,OUTPUT);
pinMode(echoPin,INPUT);
}
void loop() {
digitalWrite(trigPin,LOW);
delayMicroseconds(2);
digitalWrite(trigPin,HIGH);
delayMicroseconds(10);
digitalWrite(trigPin,LOW);
duration = pulseIn(echoPin,HIGH);
distanceCm = duration*0.034/2;
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Measuring.....");
lcd.setCursor(0,1);
lcd.print("Distance:");
lcd.print(distanceCm);
lcd.print(" Cm ");
}

Quite simple, the distance is wrong because you're not using the correct speed of sound for your temperature. Also, you're not even using the NewPing library so your entire question is out of scope. Use the NewPing library in your sketch and use the built-in speed of sound calculations and then if it's wrong I can give guidance.

Tim

teckel:
Quite simple, the distance is wrong because you're not using the correct speed of sound for your temperature. Also, you're not even using the NewPing library so your entire question is out of scope. Use the NewPing library in your sketch and use the built-in speed of sound calculations and then if it's wrong I can give guidance.

Tim

Thank you Very much Sir Tim.

Here is my code.

#include <NewPing.h>
#include <LiquidCrystal.h>

unsigned long previousMillis = 0;        
const long interval = 500;           

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int ledLCD = 6;

#define TRIGGER_PIN  9 
#define ECHO_PIN     10  

NewPing sonar(TRIGGER_PIN, ECHO_PIN); 

void setup() {
  lcd.begin(16,2);
  pinMode(ledLCD,OUTPUT);
   
}

void loop() {
   unsigned long currentMillis = millis();
  digitalWrite(ledLCD,HIGH);
  
  delay(35);                      
  unsigned int uS = sonar.ping(); 
 if (uS != NO_ECHO) {
  
    if (currentMillis - previousMillis >= interval) {
        previousMillis = currentMillis;

    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Ping: ");
    lcd.print(uS / US_ROUNDTRIP_CM); 
    lcd.print(" cm ");
   }
 }
}

Edwooong:
Thank you Very much Sir Tim.

Here is my code.

#include <NewPing.h>

#include <LiquidCrystal.h>

unsigned long previousMillis = 0;       
const long interval = 500;

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int ledLCD = 6;

#define TRIGGER_PIN  9
#define ECHO_PIN    10

NewPing sonar(TRIGGER_PIN, ECHO_PIN);

void setup() {
  lcd.begin(16,2);
  pinMode(ledLCD,OUTPUT);
 
}

void loop() {
  unsigned long currentMillis = millis();
  digitalWrite(ledLCD,HIGH);
 
  delay(35);                     
  unsigned int uS = sonar.ping();
if (uS != NO_ECHO) {
 
    if (currentMillis - previousMillis >= interval) {
        previousMillis = currentMillis;

lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Ping: ");
    lcd.print(uS / US_ROUNDTRIP_CM);
    lcd.print(" cm ");
  }
}
}

Yup, that works!

US_ROUNDTRIP_CM is the default ESTIMATED speed of sound. It works well virtually all the time. But, the accuracy is off the further the distance or the more the temperature you're at is off from the default speed of sound built into the library.

Typically, "good enough" is all the more a project needs. Or, it doesn't really matter the distance, just that it's more or less than before or whatever being measured. If, however, you need more accurate measurements, you'll need to do some work on your own. To do that, you'll need to know the speed of sound at your altitude, humidity and temperature. So, you'll take those measurements (maybe with different sensors, maybe hard-coded) do the math, and replace US_ROUNDTRIP_CM for whatever it is in your environment.

US_ROUNDTRIP_CM is exactly what it says, it's the number of uS it takes to sound to travel 1 cm round trip (in other words, 2 cm [1 cm there, 1 cm back]). NewPing defaults to an integer for the US_ROUNDTRIP_CM because "good enough" is all the more 99.999% of projects need. Using an integer is also great because it uses less memory and executes faster.

But by all means, use whatever number you want for the speed of sound that makes you feel good about the distance measurements.

Tim

teckel:
Yup, that works!

US_ROUNDTRIP_CM is the default ESTIMATED speed of sound. It works well virtually all the time. But, the accuracy is off the further the distance or the more the temperature you're at is off from the default speed of sound built into the library.

Typically, "good enough" is all the more a project needs. Or, it doesn't really matter the distance, just that it's more or less than before or whatever being measured. If, however, you need more accurate measurements, you'll need to do some work on your own. To do that, you'll need to know the speed of sound at your altitude, humidity and temperature. So, you'll take those measurements (maybe with different sensors, maybe hard-coded) do the math, and replace US_ROUNDTRIP_CM for whatever it is in your environment.

US_ROUNDTRIP_CM is exactly what it says, it's the number of uS it takes to sound to travel 1 cm round trip (in other words, 2 cm [1 cm there, 1 cm back]). NewPing defaults to an integer for the US_ROUNDTRIP_CM because "good enough" is all the more 99.999% of projects need. Using an integer is also great because it uses less memory and executes faster.

But by all means, use whatever number you want for the speed of sound that makes you feel good about the distance measurements.

Tim

This will help me a Lot.
Thank You So much Sir Tim :slight_smile:

Hey Tim, Great work!

I am currently working on my bachelor thesis and I do have a question about the HC-SR04 Sensor. My thesis is about autonomous driving Robots. They have to navigate in a room and avoid each other. I am planning to use the HC-SR04 Sensor for optical avoidance. The problem that I am facing is, that if there are many Robots in one room, the ultrasonic sounds from different Robots are interfering with each other, so that on Sensor of let's say Robot_1 detects the Ultrasonic sound from the Sensor of Robot_2. My question is now if it is possible to physically limit the Range of the Ultrasonic sensor? I mean not to wait for a shorter amount of time for the signal to come back. I would like to limit the distance that ultrasonic waves travel through the room. Maybe by changing the 40 kHz Burst-Signal to a higher frequency or changing the voltage of the sensor or simply by putting tape over the sensor. Have you ever tried something like that?
Thanks a lot in advance.

English is not my first language so please excuse any mistakes.

C_J_K:
Hey Tim, Great work!

I am currently working on my bachelor thesis and I do have a question about the HC-SR04 Sensor. My thesis is about autonomous driving Robots. They have to navigate in a room and avoid each other. I am planning to use the HC-SR04 Sensor for optical avoidance. The problem that I am facing is, that if there are many Robots in one room, the ultrasonic sounds from different Robots are interfering with each other, so that on Sensor of let's say Robot_1 detects the Ultrasonic sound from the Sensor of Robot_2. My question is now if it is possible to physically limit the Range of the Ultrasonic sensor? I mean not to wait for a shorter amount of time for the signal to come back. I would like to limit the distance that ultrasonic waves travel through the room. Maybe by changing the 40 kHz Burst-Signal to a higher frequency or changing the voltage of the sensor or simply by putting tape over the sensor. Have you ever tried something like that?
Thanks a lot in advance.

English is not my first language so please excuse any mistakes.

The sensors can't really be changed to a different frequency. It would require different hardware on the sensors and different software as well. You'll need to consider other options if you're going to have multiple individual systems all trying to work in the same environment.

Tim

Thanks a lot for your advice. Do you know if there are any "near field" ultrasonic sensors for Arduino on the marked ore I guess I just have to go with a other kind of sensor like an Infrared sensor.
Thank you

Hello! I am currently trying to use the NewPing.h file, but I keep receiving the error "cannot open source file WProgram.h" but I am unable to actually find this file anywhere in your links. Is this necessary to be included or could I just take it out? Thank you!

egarvie:
Hello! I am currently trying to use the NewPing.h file, but I keep receiving the error "cannot open source file WProgram.h" but I am unable to actually find this file anywhere in your links. Is this necessary to be included or could I just take it out? Thank you!

That's a core Arduino file, nothing to do with NewPing. The fact that this can't be found sounds like you don't have Arduino installed correctly or are using non-standard hardware in an improper way.

Basically, you should ask for general help, not help with NewPing.

Tim

Hi Tim,
Is it possible to have -1 when it's out of range?
Thank you

Thank you very much.
Your library is awesome.
However, I want to use with five ultrasonic sensors and one hall sensor.
It is embarrassed if there are any delay time in loop.
Is it mean it will be few delay time/ or no delay if I use the similar way like with calling NewPing five times?

#include <NewPing.h>

NewPing sonar1(11, 12, 200); // Sensor 1: trigger pin, echo pin, maximum distance in cm
NewPing sonar2(9, 10, 200); // Sensor 2: same stuff

#define pingSpeed 100 // Ping frequency (in milliseconds), fastest we should ping is about 35ms per sensor
unsigned long pingTimer1, pingTimer2;

void setup() {
 // Do other stuff here
 pingTimer1 = millis() + pingSpeed; // Sensor 1 fires after 100ms (pingSpeed)
 pingTimer2 = pingTimer1 + (pingSpeed / 2); // Sensor 2 fires 50ms later
}

void loop() {
 if (millis() >= pingTimer1) {
   pingTimer1 += pingSpeed; // Make sensor 1 fire again 100ms later (pingSpeed)
   int in1 = sonar1.ping_in();
 }
 if (millis() >= pingTimer2) {
   pingTimer2 = pingTimer1 + (pingSpeed / 2); // Make sensor 2 fire again 50ms after sensor 1 fires
   int in2 = sonar2.ping_in();
   // Both sensors pinged, process results here
 }
 // Do other stuff here, notice how there's no delays in this sketch, so you have processing cycles to do other things :)
}

onire:
Hi Tim,
Is it possible to have -1 when it's out of range?
Thank you

That's exactly what it does by default.

Tim

KSWang:
Thank you very much.
Your library is awesome.
However, I want to use with five ultrasonic sensors and one hall sensor.
It is embarrassed if there are any delay time in loop.
Is it mean it will be few delay time/ or no delay if I use the similar way like with calling NewPing five times?

#include <NewPing.h>

NewPing sonar1(11, 12, 200); // Sensor 1: trigger pin, echo pin, maximum distance in cm
NewPing sonar2(9, 10, 200); // Sensor 2: same stuff

#define pingSpeed 100 // Ping frequency (in milliseconds), fastest we should ping is about 35ms per sensor
unsigned long pingTimer1, pingTimer2;

void setup() {
// Do other stuff here
pingTimer1 = millis() + pingSpeed; // Sensor 1 fires after 100ms (pingSpeed)
pingTimer2 = pingTimer1 + (pingSpeed / 2); // Sensor 2 fires 50ms later
}

void loop() {
if (millis() >= pingTimer1) {
  pingTimer1 += pingSpeed; // Make sensor 1 fire again 100ms later (pingSpeed)
  int in1 = sonar1.ping_in();
}
if (millis() >= pingTimer2) {
  pingTimer2 = pingTimer1 + (pingSpeed / 2); // Make sensor 2 fire again 50ms after sensor 1 fires
  int in2 = sonar2.ping_in();
  // Both sensors pinged, process results here
}
// Do other stuff here, notice how there's no delays in this sketch, so you have processing cycles to do other things :slight_smile:
}

While there are no delays in that sketch, the ping_in() method does it's own pauses. While it will work with 5 sensors, it will still be using a blocking mode programming paradigm. You would need to use the ping_timer() method to not be using a blocking programming paradigm. I include examples but if you're not an expert on the subject, it will probably be difficult to understand as it's a totally different programming paradigm than you are probably used to using. The above sketch is still basically blocking mode programming.

Tim

KSWang:
Thank you very much.
Your library is awesome.
However, I want to use with five ultrasonic sensors and one hall sensor.
It is embarrassed if there are any delay time in loop.
Is it mean it will be few delay time/ or no delay if I use the similar way like with calling NewPing five times?

Few months ago I had a similar requirement of using 4 ultrasonic sensors together attached to 4 corners. Instead of killing time hassling and fine tuning 4 separate sensors I had bought a board which had 4 transducers/probe with 1 board. I believe it had UART output of distances so not much calculation code required on the micro-controller side.

Edit: Found out the item I had bought couple months ago. It was something like this 1-to-4 Waterproof Integrated Ultrasonic Ranging Sensor Smart Trash Can arduino | eBay. Also here is another model which showed up in the search results serving the same purpose: https://www.ebay.com/itm/254203570456

Hi there,

Apologies if this has been answered already, im a beginner so just trying some small experiments out. When the sensor distance exceeds its maximum it defaults to 0cm. Is there anyway this can be changed to the max distance value?

Thanks

harrygover:
Hi there,

Apologies if this has been answered already, im a beginner so just trying some small experiments out. When the sensor distance exceeds its maximum it defaults to 0cm. Is there anyway this can be changed to the max distance value?

Thanks

This is a common question/confusion but if you think about it, it makes total sense that it works the way it does.

Imagine you set the max distance to 100cm. Now the way the library works, any non-zero value means there's something in front of the sensor. Let's say the object was 100cm away, it would return a value of 100.

If instead, it would return the max distance when there wasn't an object at all in the way, how would you know there wasn't an object at all? Or if there was an object 100cm away? So there would be no difference between an object detected at 100cm and no object at all. That's not good logic, and it makes it impossible to know what the condition is.

Keep in mind that a result of 0 doesn't mean the object is further away than the max distance. It means there isn't an object AT ALL, which is why a value of 0 makes total sense.

If, however, for your use, you want this ambiguous logic, that's totally possible. Simply read the sensor distance, then if 0 make it any value you want. For example:

if (dist == 0) {
 dist = 100;
}

Or whatever you want it to be. Writing the library in this way, you can both detect when an object doesn't exist or just set the max distance (if that makes sense to your project).

Basically, this is where your programming needs to take over and deal with the results as your program needs.

Tim

Zero is much better because you can use a better sensor with longer range so the max distance is not always the same.

Hello, thank you very much for your contribution! I have a problem in my project. I have a car, Arduino + L293D shield. I have connected 4x ultrasonic sensors on pins: 3,4,5,6. I have put a delay of 60ms and 5s in setup.

However, the front sensor measures are like 12,12,12,0,12,12,0,12,12... etc a sensor from left measures 0,0,0,0,0,18,0,0,0,18. How could I make a consistent measurment? Some of the sensors are measuring good, some have a lot of zeros.

I need the car to avoid obstacles in its way. Thank you.

Aylee:
Hello, thank you very much for your contribution! I have a problem in my project. I have a car, Arduino + L293D shield. I have connected 4x ultrasonic sensors on pins: 3,4,5,6. I have put a delay of 60ms and 5s in setup.

However, the front sensor measures are like 12,12,12,0,12,12,0,12,12... etc a sensor from left measures 0,0,0,0,0,18,0,0,0,18. How could I make a consistent measurment? Some of the sensors are measuring good, some have a lot of zeros.

I need the car to avoid obstacles in its way. Thank you.

Not enough information to help. But, I would first guess that your sensors are not compatible with the one pin method or you didn't install the capacitor (you don't specify the sensor, circuit, nor code, so who knows).

Also, you're over-complicating things if you're having a problem. SIMPLIFY when you have a problem. If I were you, I would have just one sensor and use two pins (trigger and echo pins). See if that works, if it does, see what it takes to make it fail, then you've found your problem.

In any case, it seems you just need some basic deductive reasoning to isolate what the problem is.

Tim

teckel:
Not enough information to help. But, I would first guess that your sensors are not compatible with the one pin method or you didn't install the capacitor (you don't specify the sensor, circuit, nor code, so who knows).

Also, you're over-complicating things if you're having a problem. SIMPLIFY when you have a problem. If I were you, I would have just one sensor and use two pins (trigger and echo pins). See if that works, if it does, see what it takes to make it fail, then you've found your problem.

In any case, it seems you just need some basic deductive reasoning to isolate what the problem is.

Tim

Thank you very much for the answer. I didn't used any capacitor on them.
As an idea, i wanted to do something like this: Obstacle Avoiding Robot. Object Following Robot. Arduino Project 2018. Part 2.3. - YouTube . He uses hc-sr04 too and it seems to work fine even tough they are 6 sensors, not 4.I have attached the electric scheme, hope you understand something.
All the sonic sensors are connected on the top of l293d shield on +5v and gnd.

Hope you could help me, i need it to get it working fast... thank you for your time.

I would like to connect a capacitor, maybe it helps... what capacitor i need to use?

for coding i used this

NewPing sonar[4] = { 
  NewPing(3, 3, MAX_DISTANCE),
  NewPing(6, 6, MAX_DISTANCE), 
  NewPing(5, 5, MAX_DISTANCE), 
  NewPing(4, 4, MAX_DISTANCE) 
};

SETUP
delay(5000)
serial begin 9600 

LOOP
delay(60)
Serial.println(sonar[0].ping_cm());
delay(300); to see what i receive from the sensor. I used println for every sensor.
[code]