* Manuals and Curriculum Arduino StackExchange Board Setup and Configuration Development Tools Arduino on other Chips Interfacing With Hardware Output Input User Interface Storage Communication Power supplies General Snippets and Sketches Libraries Tutorials Interfacing with Software User Code Library Suggestions & Bugs Electronics Technique Sources for Electronic Parts Related Hardware and Initiatives Arduino People/Groups & Sites Exhibition Project Ideas Languages Participate Formatting guidelines All recent changes PmWiki WikiSandBox training Basic Editing Documentation index NewPing Library for Arduino Author: Tim Eckel Contact: tim@leethost.com Navigation History Background Features Download Constructor Methods Examples Information about this page History Release Date Changes 1.8 07/30/2016 Added support for non-AVR microcontrollers. Can now set a new max distance when pinging. Added support for ATmega16, ATmega32 andATmega8535 microcontrollers. Changed convert_cm() and convert_in() methods to static members so you can call them directly. 1.7 09/29/2015 Removed Due and Zero compatibility because boards are 3.3 volts and not 5 volt tolerant. 1.6 06/17/2014 Support for new Arduino boards and ultrasonic sensors. Better timeout method. 1.5 8/15/2012 New ping_median() method does multiple pings and returns the median (digital filter). 1.4 7/14/2012 Interface with sensors using only one Arduino pin. 1.3 6/8/2012 Supports a timer-based ping method. 1.2 5/25/2012 Rebuilt the ping timing code from scratch, now yields very accurate results. 1.1 5/16/2012 Uses port registers for ultra-fast and lean code. 1.0 5/15/2012 Initial Release. 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. Compatible with the entire Arduino line-up (and clones), Teensy family (including $19.80 96Mhz 32 bit Teensy 3.2) and non-AVR microcontrollers. 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. Download Download here: Download NewPing Library Put the "NewPing" folder in "libraries\". In the Arduino IDE, create a new sketch (or open one) and select from the menubar "Sktech->Import Library->NewPing". Constructor NewPing sonar(trigger_pin, echo_pin [, max_cm_distance]); Example: NewPing sonar(12, 11, 200); This initializes NewPing to use pin 12 for trigger output, pin 11 for echo input, with a maximum ping distance of 200cm. max_cm_distance is optional [default = 500cm]. If connecting using a single pin, specify the same pin for both trigger_pin and echo_pin as the same pin is doing both functions. Methods sonar.ping(); - Send a ping, returns the echo time in microseconds or 0 (zero) if no ping echo within set distance limit sonar.ping_in(); - Send a ping, returns the distance in inches or 0 (zero) if no ping echo within set distance limit sonar.ping_cm(); - Send a ping, returns the distance in centimeters or 0 (zero) if no ping echo within set distance limit sonar.ping_median(iterations); - Do multiple pings (default=5), discard out of range pings and return median in microseconds sonar.convert_in(echoTime); - Converts microseconds to distance in inches sonar.convert_cm(echoTime); - Converts microseconds to distance in centimeters sonar.ping_timer(function); - Send a ping and call function to test if ping is complete. sonar.check_timer(); - Check if ping has returned within the set distance limit. timer_us(frequency, function); - Call function every frequency microseconds. timer_ms(frequency, function); - Call function every frequency milliseconds. timer_stop(); - Stop the timer. Examples Sample NewPing Sketch 1. #include <NewPing.h> 2. 3. #define TRIGGER_PIN 12 4. #define ECHO_PIN 11 5. #define MAX_DISTANCE 200 6. 7. NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); 8. 9. void setup() { 10. Serial.begin(115200); 11.} 12. 13.void loop() { 14. delay(50); 15. Serial.print("Ping: "); 16. Serial.print(sonar.ping_cm()); 17. Serial.println("cm"); 18.} [Get Code] 15 Sensors Example Sketch 1. 2. 3. 4. 5. 6. 7. 8. // --------------------------------------------------------// This example code was used to successfully communicate // with 15 ultrasonic sensors. You can adjust the number of // sensors in your project by changing SONAR_NUM and the // number of NewPing objects in the "sonar" array. You also // need to change the pins for each sensor for the NewPing // objects. Each sensor is pinged at 33ms intervals. So, one // cycle of all sensors takes 495ms (33 * 15 = 495ms). The 9. // results are sent to the "oneSensorCycle" function which 10.// currently just displays the distance data. Your project 11.// would normally process the sensor results in this 12.// function (for example, decide if a robot needs to turn 13.// and call the turn function). Keep in mind this example is 14.// event-driven. Your complete sketch needs to be written so 15.// there's no "delay" commands and the loop() cycles at 16.// faster than a 33ms rate. If other processes take longer 17.// than 33ms, you'll need to increase PING_INTERVAL so it 18.// doesn't get behind. 19.// --------------------------------------------------------20.#include <NewPing.h> 21. 22.#define SONAR_NUM 15 // Number or sensors. 23.#define MAX_DISTANCE 200 // Max distance in cm. 24.#define PING_INTERVAL 33 // Milliseconds between pings. 25. 26.unsigned long pingTimer[SONAR_NUM]; // When each pings. 27.unsigned int cm[SONAR_NUM]; // Store ping distances. 28.uint8_t currentSensor = 0; // Which sensor is active. 29. 30.NewPing sonar[SONAR_NUM] = { // Sensor object array. 31. NewPing(41, 42, MAX_DISTANCE), 32. NewPing(43, 44, MAX_DISTANCE), 33. NewPing(45, 20, MAX_DISTANCE), 34. NewPing(21, 22, MAX_DISTANCE), 35. NewPing(23, 24, MAX_DISTANCE), 36. NewPing(25, 26, MAX_DISTANCE), 37. NewPing(27, 28, MAX_DISTANCE), 38. NewPing(29, 30, MAX_DISTANCE), 39. NewPing(31, 32, MAX_DISTANCE), 40. NewPing(34, 33, MAX_DISTANCE), 41. NewPing(35, 36, MAX_DISTANCE), 42. NewPing(37, 38, MAX_DISTANCE), 43. NewPing(39, 40, MAX_DISTANCE), 44. NewPing(50, 51, MAX_DISTANCE), 45. NewPing(52, 53, MAX_DISTANCE) 46.}; 47. 48.void setup() { 49. Serial.begin(115200); 50. pingTimer[0] = millis() + 75; // First ping start in ms. 51. for (uint8_t i = 1; i < SONAR_NUM; i++) 52. pingTimer[i] = pingTimer[i - 1] + PING_INTERVAL; 53.} 54. 55.void loop() { 56. for (uint8_t i = 0; i < SONAR_NUM; i++) { 57. if (millis() >= pingTimer[i]) { 58. pingTimer[i] += PING_INTERVAL * SONAR_NUM; 59. if (i == 0 && currentSensor == SONAR_NUM - 1) 60. oneSensorCycle(); // Do something with results. 61. sonar[currentSensor].timer_stop(); 62. currentSensor = i; 63. cm[currentSensor] = 0; 64. sonar[currentSensor].ping_timer(echoCheck); 65. } 66. } 67. // The rest of your code would go here. 68.} 69. 70.void echoCheck() { // If ping echo, set distance to array. 71. if (sonar[currentSensor].check_timer()) 72. cm[currentSensor] = sonar[currentSensor].ping_result / US_ROUNDTRIP_C M; 73.} 74. 75.void oneSensorCycle() { // Do something with the results. 76. for (uint8_t i = 0; i < SONAR_NUM; i++) { 77. Serial.print(i); 78. Serial.print("="); 79. Serial.print(cm[i]); 80. Serial.print("cm "); 81. } 82. Serial.println(); 83.} HC-SR04 Ping distance sensor: VCC to arduino 5v GND to arduino GND Echo to Arduino pin 7 Trig to Arduino pin 8 This sketch originates from Virtualmix: http://goo.gl/kJ8Gl Has been modified by Winkle ink here: http://winkleink.blogspot.com.au/2012/05/arduino-hc-sr04-ultrasonicdistance.html And modified further by ScottC here: http://arduinobasics.blogspot.com.au/2012/11/arduinobasics-hc-sr04ultrasonic-sensor.html on 10 Nov 2012. */ #define echoPin 7 // Echo Pin #define trigPin 8 // Trigger Pin #define LEDPin 13 // Onboard LED int maximumRange = 200; // Maximum range needed int minimumRange = 0; // Minimum range needed long duration, distance; // Duration used to calculate distance void setup() { Serial.begin (9600); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); pinMode(LEDPin, OUTPUT); // Use LED indicator (if required) } void loop() { /* The following trigPin/echoPin cycle is used to determine the distance of the nearest object by bouncing soundwaves off of it. */ digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); //Calculate the distance (in cm) based on the speed of sound. distance = duration/58.2; if (distance >= maximumRange || distance <= minimumRange){ /* Send a negative number to computer and Turn LED ON to indicate "out of range" */ Serial.println("-1"); digitalWrite(LEDPin, HIGH); } else { /* Send the distance to the computer using Serial protocol, and turn LED OFF to indicate successful reading. */ Serial.println(distance); digitalWrite(LEDPin, LOW); } //Delay 50ms before next reading. delay(50); First you have to define the Trig and Echo pins. In this case they are the pins number 9 and 10 on the Arduino Board and they are named trigPin and echoPin. Then you need a Long variable, named “duration” for the travel time that you will get from the sensor and an integer variable for the distance. In the setup you have to define the trigPin as an output and the echoPin as an Input and also start the serial communication for showing the results on the serial monitor. In the loop first you have to make sure that the trigPin is clear so you have to set that pin on a LOW State for just 2 µs. Now for generating the Ultra sound wave we have to set the trigPin on HIGH State for 10 µs. Using the pulseIn() function you have to read the travel time and put that value into the variable “duration”. This function has 2 parameters, the first one is the name of the echo pin and for the second one you can write either HIGH or LOW. In this case, HIGH means that thepulsIn() function will wait for the pin to go HIGH caused by the bounced sound wave and it will start timing, then it will wait for the pin to go LOW when the sound wave will end which will stop the timing. At the end the function will return the length of the pulse in microseconds. For getting the distance we will multiply the duration by 0.034 and divide it by 2 as we explained this equation previously. At the end we will print the value of the distance on the Serial Monitor. 1. ; 2. 3. void setup() { 4. pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output 5. pinMode(echoPin, INPUT); // Sets the echoPin as an Input 6. Serial.begin(9600); // Starts the serial communication 7. } 8. 9. void loop() { 10. // Clears the trigPin 11. digitalWrite(trigPin, LOW); 12. delayMicroseconds(2); 13. 14. // Sets the trigPin on HIGH state for 10 micro seconds 15. digitalWrite(trigPin, HIGH); 16. delayMicroseconds(10); 17. digitalWrite(trigPin, LOW); 18. 19. // Reads the echoPin, returns the sound wave travel time in microseconds 20. duration = pulseIn(echoPin, HIGH); 21. 22. // Calculating the distance 23. distance= duration*0.034/2; 24. 25. // Prints the distance on the Serial Monitor 26. Serial.print("Distance: "); 27. Serial.println(distance); 28. } Modified Arduino Ping))) example to work with 4-Pin HC-SR04 Ultrasonic Sensor Distance Measuring Module hc-sr04.ino /* HC-SR04 Sensor https://www.dealextreme.com/p/hc-sr04-ultrasonic-sensor-distance-measuring-module133696 This sketch reads a HC-SR04 ultrasonic rangefinder and returns the distance to the closest object in range. To do this, it sends a pulse to the sensor to initiate a reading, then listens for a pulse to return. The length of the returning pulse is proportional to the distance of the object from the sensor. The circuit: * VCC connection of the sensor attached to +5V * GND connection of the sensor attached to ground * TRIG connection of the sensor attached to digital pin 2 * ECHO connection of the sensor attached to digital pin 4 Original code for Ping))) example was created by David A. Mellis Adapted for HC-SR04 by Tautvidas Sipavicius This example code is in the public domain. */ const int trigPin = 2; const int echoPin = 4; void setup() { // initialize serial communication: Serial.begin(9600); } void loop() { // establish variables for duration of the ping, // and the distance result in inches and centimeters: long duration, inches, cm; // The sensor is triggered by a HIGH pulse of 10 or more microseconds. // Give a short LOW pulse beforehand to ensure a clean HIGH pulse: pinMode(trigPin, OUTPUT); digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); // Read the signal from the sensor: a HIGH pulse whose // duration is the time (in microseconds) from the sending // of the ping to the reception of its echo off of an object. pinMode(echoPin, INPUT); duration = pulseIn(echoPin, HIGH); // convert the time into a distance inches = microsecondsToInches(duration); cm = microsecondsToCentimeters(duration); Serial.print(inches); Serial.print("in, "); Serial.print(cm); Serial.print("cm"); Serial.println(); delay(100); } long microsecondsToInches(long microseconds) { // According to Parallax's datasheet for the PING))), there are // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per // second). This gives the distance travelled by the ping, outbound // and return, so we divide by 2 to get the distance of the obstacle. // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf return microseconds / 74 / 2; } long microsecondsToCentimeters(long microseconds) { // The speed of sound is 340 m/s or 29 microseconds per centimeter. // The ping travels out and back, so to find the distance of the // object we take half of the distance travelled. return microseconds / 29 / 2; }