Go Down

Topic: NewPing Library: HC-SR04, SRF05, SRF06, DYP-ME007, Parallax PING))) - v1.5 (Read 128 times) previous topic - next topic


NewPing Library Project Homepage

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.


  • 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.

  • 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.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).

Download NewPing v1.5

Show Your Appreciation:
Help future development by making a small donation (yes, the FreeRingers payee is correct).

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

Example Sketch:
Code: [Select]
#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)

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.

Arduino - Teensy - Raspberry Pi
My libraries: NewPing - LCDBitmap - toneAC - NewTone - TimerFreeTone


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?


  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!


May 16, 2012, 07:54 pm Last Edit: Jul 13, 2012, 10:10 pm by teckel Reason: 1

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?

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:

Code: (Two sensor example) [Select]

#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.

Arduino - Teensy - Raspberry Pi
My libraries: NewPing - LCDBitmap - toneAC - NewTone - TimerFreeTone


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.

Go Up