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

NewPing Library Project Homepage

Background:
When I first received an ultrasonic sensor I was not happy with how poorly it performed. I soon realized the problem wasn't the sensor, it was the available ping and ultrasonic libraries causing the problem. The NewPing library totally fixes these problems, adds many new features, and breathes new life into these very affordable distance sensors.

Features:

  • Works with many different ultrasonic sensor models: SR04, SRF05, SRF06, DYP-ME007 & Parallax PING)))™.
  • Option to interface with all but the SRF06 sensor using only one Arduino pin.
  • Doesn't lag for a full second if no ping echo is received like all other ultrasonic libraries.
  • Ping sensors consistently and reliably at up to 30 times per second.
  • Compatible with the entire Arduino line-up (and clones), Teensy family (including $19.80 96Mhz 32 bit Teensy 3.2) and non-AVR microcontrollers.
  • Timer interrupt method for event-driven sketches.
  • Built-in digital filter method ping_median() for easy error correction.
  • Uses port registers when accessing pins for faster execution and smaller code size.
  • Allows setting of a maximum distance where pings beyond that distance are read as no ping "clear".
  • Ease of using multiple sensors (example sketch with 15 sensors).
  • More accurate distance calculation (cm, inches & uS).
  • Doesn't use pulseIn, which is slow and gives incorrect results with some ultrasonic sensor models.
  • Actively developed with features being added and bugs/issues addressed.

New in version 1.8:
Added support for non-AVR microcontrollers. For non-AVR microcontrollers, advanced ping_timer() timer methods are disabled due to inconsistencies or no support at all between platforms. However, standard ping methods are all supported. Added new optional variable to ping(), ping_in(), ping_cm(), ping_median(), and ping_timer() methods which allows you to set a new maximum distance for each ping. Added support for the ATmega16, ATmega32 and ATmega8535 microcontrollers. Changed convert_cm() and convert_in() methods to static members. You can now call them without an object. For example: cm = NewPing::convert_cm(distance);

Download:
Download NewPing v1.8

Show Your Appreciation:
Help future development by making a small donation (the teckel@bex.net payee is correct).

Common Problem Help:
15 Sensors Example Sketch (Multiple Sensors) Help
"vector_7" Error on Compile Help

Example Sketch:

#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(sonar.convert_cm(uS)); // Convert ping time to distance and print result (0 = outside set distance range, no ping echo)
  Serial.println("cm");
}

New in version 1.7:
Removed support for the Arduino Due and Zero because they're both 3.3 volt boards and are not 5 volt tolerant while the HC-SR04 is a 5 volt sensor. Also, the Due and Zero don't support pin manipulation compatibility via port registers which can be done (see the Teensy 3.2).

New in version 1.6:
Corrected delay between pings when using ping_median() method. Added support for the URM37 sensor (must change URM37_ENABLED from false to true). Added support for Arduino microcontrollers like the $20 32 bit ARM Cortex-M4 based Teensy 3.2. Added automatic support for the Atmel ATtiny family of microcontrollers. Added timer support for the ATmega8 microcontroller. Rounding disabled by default, reduces compiled code size (can be turned on with ROUNDING_ENABLED switch). Added TIMER_ENABLED switch to get around compile-time "_vector_7" errors when using the Tone library, or you can use the toneAC, NewTone or TimerFreeTone libraries. Other speed and compiled size optimizations.

New in version 1.5:
Added ping_median() method which does a user specified number of pings (default=5) and returns the median ping in microseconds (out of range pings ignored). This is a very effective digital filter. Optimized for smaller compiled size (even smaller than sketches that don't use a library).

New in version 1.4:
You can now interface with all but the SRF06 sensor using only one Arduino pin. Added support for the Parallax PING)))™ sensor. You can also interface with the SRF06 using one pin if you install a 0.1uf capacitor on the trigger and echo pins of the sensor then tie the trigger pin to the Arduino pin (doesn't work with Teensy). To use the same Arduino pin for trigger and echo, specify the same pin for both values. Various bug fixes.

New in version 1.3:
Big feature addition, event-driven ping! Uses Timer2 interrupt, so be mindful of PWM or timing conflicts messing with Timer2 may cause (namely PWM on pins 3 & 11 on Arduino, PWM on pins 9 and 11 on ATmega, and Tone library). Simple to use timer interrupt functions you can use in your sketches totaly unrelated to ultrasonic sensors (don't use if you're also using NewPing's ping_timer because both use Timer2 interrupts). Loop counting ping method deleted in favor of timing ping method after inconsistant results kept surfacing with the loop timing ping method. Conversion to cm and inches now rounds to the nearest cm or inch. Code optimized to save program space and fixed a couple minor bugs here and there. Many new comments added as well as line spacing to group code sections for better source readability.

NOTE: For Teensy/Leonardo (ATmega32U4) the library uses Timer4 instead of Timer2. Also, only 16Mhz microcontrollers are supported with the timer methods, which means the ATmega8 and ATmega128 will not work with the timer methods. However, the standard ping method should work just fine on 8Mhz microcontrollers.

New in version 1.2:
Lots of code clean-up thanks to Adruino Forum members. Rebuilt the ping timing code from scratch, ditched the pulseIn code as it doesn't give correct results (at least with ping sensors). The NewPing library is now VERY accurate and the code was simplified as a bonus. Smaller and faster code as well. Fixed some issues with very close ping results when converting to inches. All functions now return 0 only when there's no ping echo (out of range) and a positive value for a successful ping. This can effectively be used to detect if something is out of range or in-range and at what distance. Now compatible with Arduino 0023.

New in version 1.1:
Changed all I/O functions to use low-level port registers for ultra-fast and lean code (saves from 174 to 394 bytes). Tested on both the Arduino Uno and Teensy 2.0 but should work on all Arduino-based platforms because it calls standard functions to retrieve port registers and bit masks. Also made a couple minor fixes to defines.

Tim

Very good job, man!!!!
Two questions:

  • is it possible to use multiple ultrasonic sensors? i.e 4 sensors?
  • with multiple sensors and a distance between 10 and 20 cm how fast can be the readings?
    Thanks

Nice job! I just got 4 of those sensors, and I have one hooked up at home. I will can't wait to try it out!

alegiaco:
Very good job, man!!!!
Two questions:

  • is it possible to use multiple ultrasonic sensors? i.e 4 sensors?
  • with multiple sensors and a distance between 10 and 20 cm how fast can be the readings?
    Thanks

YES! The NewPing library is designed with multiple sensors in mind. It's one of the reasons I created the library. With the other ping/ultrasonic libraries, if there's no ping echo it waits a full second for the reply. During that time, the Arduino is doing nothing, it's like a delay(1000). Multiply that by 3 if you have 3 sensors. So, you're waiting for 3 full seconds doing nothing if there's no pings. Imagine an autonomous bot where you add a delay(3000) right in the middle of the sketch. A lot can happen in 3 full seconds, or the bot can just sit there for 3 seconds to figure out which way to go. Unacceptable.

I plan on creating a proper sample sketch using multiple sensors and also creating another library specifically optimized for 3 sensors. But, here's basically what you would do:

#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 :)
}

The above code is incomplete and doesn't do anything with the ping results (ready to add your own code). But, it should give you an idea of what to do.

As to your second question, I suggest waiting at least 35ms between pings per sensor to avoid possible echo issues. This isn't a library limitation or something that can be made faster by setting a shorter maximum distance. The pinging frequency has to do with the speed of sound and the sensor specs. You can, however, get away with making this faster if you need to. My sensors are a little hard of hearing and can't detect the maximum 500cm. So, I've successfully pinged every 25ms without a problem. Never really tried to see how quickly it would work as typically in a real-world situation 10 times a second is plenty fast as your sketch is also doing other things too.

What you gain by setting the maximum distance to a lower value is not how fast you can ping. What you gain is how much time your sketch is off in limbo doing nothing waiting for the ping reply. This allows your sketch to do multiple things without waiting for the ping echo (like in the other ping and ultrasonic libraries out there). Here's an example. If you use the 500cm maximum distance, the Arduino could set idle for up to 34ms for each ping. If you only care about reading distances 20cm or less, the most the Arduino would wait for a ping would be 1.4ms. Therefore, the Arduino has time to do other things. Basically, the Arduino can better multitask if you set a shorter maximum distance. But, due to the speed of sound, and sensor specs, you can't ping faster even if you set the maximum distance to a very low value, you still need to wait for the previous ping to fade or you'll get echo readings.

Let me know if you have any other questions or issues.

Tim

Thanks for your answer. Very clear. So, if I have 4 sensors the minum elapsed is 35 ms for the readings and Arduino time. I start reading the first sensor, the second, the third and the forth. If the distance is 20 cm it take 1.4ms x 4 = 5.6 ms. I have almost 30 ms for Arduino to do other things and after restart next reading. But in my experience a normal algo in Arduino, without too much serial monitor printing, take 10-15 ms. If you don't print in the serial monitor the time is always under 10 ms. So 15-20 ms are lost waiting for new sensor reading to avoid the echo.Shame.

Hi Tim,

Great work! I will be trying this out Real Soon!!!

There are quite a few "HC-S04" labelled modules around. Have you tested any variety??

Here are a couple I have: http://goo.gl/VZkSy

The one labelled SRF-06 is said by the supplier to have temperature compensation. It does have a different circuit board / chips.

I'll send you one of each of the HC-SR04 and SRF-06 modules if you want to test them and see if you see any differences.. drop me a PM or email terry@yourduino.com

I'm writing a library for these: http://goo.gl/FWMjI and I'd love to try some cool mapping ideas with your code...

DISCLAIMER: Mentioned stuff from my own shop...

OTHER QUESTION: Your example is for Arduino IDE 1.0 Does the library work for both 0023 and 1.0??

alegiaco:
Thanks for your answer. Very clear. So, if I have 4 sensors the minum elapsed is 35 ms for the readings and Arduino time. I start reading the first sensor, the second, the third and the forth. If the distance is 20 cm it take 1.4ms x 4 = 5.6 ms. I have almost 30 ms for Arduino to do other things and after restart next reading. But in my experience a normal algo in Arduino, without too much serial monitor printing, take 10-15 ms. If you don't print in the serial monitor the time is always under 10 ms. So 15-20 ms are lost waiting for new sensor reading to avoid the echo.Shame.

With 4 sensors, you would ping each one with a minimum of 35ms between each ping. So, 35 x 4 = 140ms to ping 4 sensors. Therefore, you could ping all 4 sensors 7 times a second. As your maximum distance is only 20cm, and at that range the MAX it would wait is 1.4ms to get the ping results per sensor, the most processing time used to wait for pings would be around 40ms per second (1.4 x 4 x 7 = 39.2), with 960ms per second for other tasks. Basically, with a 20cm range, the ping process only uses a maximum of 4% of the Arduino's processing time. That's also the max, as if the sensor detects something closer, it will use even less. That's also assuming you ping every 35ms. If you don't need pings 7 times a second, it would be even less. Also keep in mind that this time is not lost to processing, but simply waiting for a pin to go high. It is a shame, but a good illustration of how fast the Arduino is and how slow the speed of sound is.

With that said, the NewPing library is much smarter and my example sketches are more event driven than the others out there. Looking at my examples, you can tell that I'm not much of a fan of sequential programming (where's the "delay" some would say looking at my code). The only sequential part of the NewPing library and my example sketches is the actual listening for the ping using pulseIn. That's something I'm working on, and will be more important with my future Ping3 library designed to ping 3 sensors.

Tim

terryking228:
Hi Tim,

Great work! I will be trying this out Real Soon!!!

There are quite a few "HC-S04" labelled modules around. Have you tested any variety??

Here are a couple I have: http://goo.gl/VZkSy

The one labelled SRF-06 is said by the supplier to have temperature compensation. It does have a different circuit board / chips.

I'll send you one of each of the HC-SR04 and SRF-06 modules if you want to test them and see if you see any differences.. drop me a PM or email terry@yourduino.com

I'm writing a library for these: http://goo.gl/FWMjI and I'd love to try some cool mapping ideas with your code...

DISCLAIMER: Mentioned stuff from my own shop...

OTHER QUESTION: Your example is for Arduino IDE 1.0 Does the library work for both 0023 and 1.0??

I have (3) HC-SR04's from two different sources. One from Amazon and two direct from China. All work fairly similar. I believe the SRF05 is compatible in mode 1 (2 wire) with NewPing, adding support for PING))) would be fairly easy (1 wire) as would mode 2 (1 wire) of the SRF05. Then there's the SRF02, which is a totally different animal as it uses either I2C or serial so it would need a totally different library. It appears the SRF-06 is a 2 wire device so my guess would be that it would work very well with the NewPing library. I'd love to test your sensors, as I'd like to grow NewPing into a library used for all ultrasonic sensors. I'll PM you.

How I can see this working going forward is to make the NewPing library compatible with all the different ultrasonic interfaces (1 wire, 2 wire, I2C and serial) and compatible with as many sensor models as possible.

I'm an Arduino newb, coming in after the 1.0 release. So, I never used the 0023 platform. I would think at this point supporting 0023 wouldn't be too important. I know there's some old sketches out there that won't compile in 1.0 and using my library may be useful. But, it seems like everything has moved to 1.0 fairly quickly and almost all libraries I see are all written only for 1.0 these days with 0023 stuff being un-linked or listed as legacy, don't use. I wouldn't have a huge problem installing 0023 to address compatibility problems, but not sure if it's really needed at this point.

Tim

Report back: Success!!! I tried your sample sketch on IDE 23 and 1.0. I got an error with 23, it said it could not find NewPing.h. I then put the same library and sketch into 1.0 and it compiled fine. Next, I modified the sketch to print the output from the sensors and also added a delay to slow the data to a readable level.

Here is the modified sketch that I tested with my 2 sensors.

#include <NewPing.h>

NewPing sonar1(12, 13, 200); // Sensor 1: trigger pin, echo pin, maximum distance in cm
NewPing sonar2(10, 11, 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() {
  Serial.begin(9600); 
  // 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();
    Serial.println(in1);
  }
  if (millis() >= pingTimer2) {
    pingTimer2 = pingTimer1 + (pingSpeed / 2); // Make sensor 2 fire again 50ms after sensor 1 fires
    int in2 = sonar2.ping_in();
    Serial.println(in2);
    // Both sensors pinged, process results here
  }
  delay(1000);
  // Do other stuff here, notice how there's no delays in this sketch, so you have processing cycles to do other things :)
}

First off, yes, it's designed for Arduino 1.0 only. I'm not sure if at this point development for old versions is really required.

Anyway, I have a bit of a problem with your sketch. You use a delay! Really, you should try to avoid using a delay at all cost, and the sketch is built to not need to use it. The entire problem with the other ping/ultrasonic libraries out there is that because they can add up to a second of delay, it breaks your event-driven sketch.

If you want to slow it down, simply change the pingSpeed, that's what it's there for. It appears you want to only do a ping once a second, so set pingSpeed to 1000 and remove the delay. My guess is that your goal is to have both sensors ping as close to the same time as each other, then print the results, and do that once per second. Here's the proper event-driven code to do that:

#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 1000 // Ping frequency (in milliseconds), fastest we should ping is about 35ms per sensor
unsigned long pingTimer1, pingTimer2;
int in1, in2;

void setup() {
  Serial.begin(9600); 
  pingTimer1 = millis() + pingSpeed; // Sensor 1 fires after 1 second (pingSpeed)
  pingTimer2 = pingTimer1 + 35; // Sensor 2 fires 35ms later
}

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

This code will ping both sensors once per second as close in time to each other as possible, then output the results. It also will never get in a situation where it could have a 2 second delay. It will always fire exactly every 1 second.

Hope that helps better understand the event-driven programming method and why it's so important for real-world applications.

Tim

You've got two virtually-identical constructors; you could eliminate code by defaulting "max_cm_distance" to "MAX_SENSOR_DISTANCE", couldn't you?

int NewPing::convert_cm(int echoTime) {
	if (!echoTime) return false;
	else return echoTime / US_ROUNDTRIP_CM;
}

If "echoTime" is zero, then "echoTime / US_ROUNDTRIP_CM" is also zero; no need to test up front - slightly longer execution time, shorter code.

Agree with AWOL's proposal , especially as the original code mixes type (false=bool and ints)

you can even make it a macro:

#define convert_cm(echotime) ((echoTime) / US_ROUNDTRIP_CM)

I'm not really sure the "volatile" qualifiers are necessary, except for "_echoInput", either.

"pulseInNew" may as well be "inline"

Hi, I got it to compile under 0023. Modify the beginning of newping.h like this:

---------------------( COPY )--------------------------
#ifndef NewPing_h
#define NewPing_h
#endif

#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
-----------------( END COPY )----------------------
This includes the right system .h file...

Hmmm. Maybe that ends up with the #endifs wrong?? But it works? Maybe someone 1/3 my age who knows about this could check it....

Maybe the Arduino check should go first??

..."And the first one now will later be last, for the times they are a'changing "

AWOL:
You've got two virtually-identical constructors; you could eliminate code by defaulting "max_cm_distance" to "MAX_SENSOR_DISTANCE", couldn't you?

I created two constructors to be compatible with existing ping/ultrasonic libraries that only pass 2 variables. I would expect users to use the one that sets the maximum distance. I also wouldn't expect someone to use both in the same sketch, so there's no wasted compiled code space as only one would be compiled. I would love to consolidate the two, as they're basically identical. But, I lack the knowledge of C++ to accommodate a constructor that has a different number of variables to pass while keeping the same constructor name. I come from very long PHP programming background but haven't touched C in at least 20 years. In PHP I would do something like this:

function NewPing(trigger_pin, echo_pin, max_cm_distance=MAX_SENSOR_DISTANCE) {...}

AWOL:

int NewPing::convert_cm(int echoTime) {
if (!echoTime) return false;
else return echoTime / US_ROUNDTRIP_CM;

}



If "echoTime" is zero, then "echoTime / US_ROUNDTRIP_CM" is also zero; no need to test up front - slightly longer execution time, shorter code.

Inexperience on my part and confusion with other languages. I think of false as not the same as zero. false !== 0. If false === 0 (strict) in Arduino, that changes many things.

Tim

function NewPing(trigger_pin, echo_pin, max_cm_distance=MAX_SENSOR_DISTANCE)

Yup, that's pretty much how you would do it in NewPing.h.

 NewPing(int trigger_pin, int echo_pin, int max_cm_distance = MAX_SENSOR_DISTANCE);

Even if you couldn't consolidate in this way, you should always factor the common code into a single function.

I think of false as not the same as zero

The C/C++ paradigm is that zero is false, and everything else is true.

terryking228:
---------------------( COPY )--------------------------
#ifndef NewPing_h
#define NewPing_h
#endif

#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
-----------------( END COPY )----------------------

Wouldn't it be?:

#ifndef NewPing_h
#define NewPing_h
 
#if defined(ARDUINO) && ARDUINO >= 100
	#include <Arduino.h>
#else
	#include "WProgram.h"
#endif

Also, did you try this with v1.1 which uses the shift registers?

Tim

robtillaart:
Agree with AWOL's proposal , especially as the original code mixes type (false=bool and ints)

you can even make it a macro:

#define convert_cm(echotime) ((echoTime) / US_ROUNDTRIP_CM)

After learning that false===0 in C++, I've had to rework some things. Basically, I want a ping to return false (zero) if there's no ping echo within the distance allowed. Also, if there is a ping echo, the result needs to be >0. We don't want to confuse a <1 inch ping echo with infinity as this difference would be very important to what you're using the sensor for.

In an case, I've reworked a bunch of the code to accommodate this and to give expected results. Here's the macro that's used for both cm and inch conversion:

#define _convert(echoTime, conversionFactor) (max(echoTime / conversionFactor, (echoTime ? 1 : 0)))

echoTime is obviously the microsecond time and conversionFactor is either US_ROUNDTRIP_CM or US_ROUNDTRIP_IN. It may appear that it's overly complex with code reduction possible. But, I need to make sure 0="no ping echo" and we never get a 0 for a really close range (happens with inches). If there's a better way do write this macro, let me know.

Tim

AWOL:
I'm not really sure the "volatile" qualifiers are necessary, except for "_echoInput", either.

"pulseInNew" may as well be "inline"

Without the "volatile" it won't compile, which is why I used it. Feel free to correct me if I'm wrong.

You're right, I should have made pulseInNew inline, in a hurry and it was late I guess. I've made it inline now. But, that's a part of the code I need to totally rework as I'd really like to see it totally event driven (or an option to have it event driven at least). I really hate delays or small loops that wait for an event without processing something else.

Tim

An echoPing can only be positive as any distance is positive .

That makes it ideal to use the negative values as error codes, but those should be in the primary ping function

something like ..

...
  if (time > MAXTIME) return -100;
  if (other error) return -200;
  // etc
  return time;
}

thinking along that line, the conversion function to cm should only accept unsigned ints for echoTime.

unsigned int NewPing::convert_cm(unsigned int echoTime)
{
  return (echoTime + US_ROUNDTRIP_CM/2) / US_ROUNDTRIP_CM;   // added rounding
}