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

[SOLVED]

I gutted the timer2 bit. Actually the whole interupt segment as denoted by comments. Then it compiled fine and works much better than ultrasonic.h.

mattlogue:
Sadly, I get compile errors.

I and thousands of other people do not get compile errors. So you should really share what you're getting and what you changed. My guess is that you're not using Arduino hardware. But, who knows because you give no details.

Tim

Good day everyone, i want to know how if i can use "Timer Median Sketch" with 2 HC-SR04 Sensores.

I need to get a Median between both sensors, and aftes that get this median.

If someone can help, i will be very thanks.

I got 2 HCSR-04 getting a median between 30 measures.

So in the end, i need get 60 measures from both sensors, and get this median after that.

PLEASE HELP ME !

I try this way, but something dosnt work as expected.

// ---------------------------------------------------------------------------
// Calculate a ping median using the ping_timer() method.
// ---------------------------------------------------------------------------

#include <NewPing.h>

#define SONAR_NUM       2     // Number of sensors.
#define ITERATIONS      30    // Number of iterations.
#define MAX_DISTANCE    2000  // Maximum distance (in cm) to ping.
#define PING_INTERVAL   29    // Milliseconds between sensor pings (29ms is about the min to avoid cross-sensor echo).

unsigned long pingTimer[ITERATIONS]; // Holds the times when the next ping should happen for each iteration.
unsigned int cm[ITERATIONS];         // Where the ping distances are stored.
uint8_t currentIteration = 0;        // Keeps track of iteration step.
uint8_t currentSensor = 0;

NewPing sonar[SONAR_NUM] = {  
  NewPing(3, 9, MAX_DISTANCE),
  NewPing(10, 11, MAX_DISTANCE)
  };

void setup() {
  Serial.begin(115200);
  pingTimer[0] = millis() + 75;            // First ping starts at 75ms, gives time for the Arduino to chill before starting.
  for (uint8_t i = 1; i < ITERATIONS; i++) // Set the starting time for each iteration.
    pingTimer[i] = pingTimer[i - 1] + PING_INTERVAL;
}

void loop() 
{
  medicoes();
}

void medicoes()
{
  for (uint8_t v = 0; v < SONAR_NUM; v++)                                     // SONAR_NUM[0] = cm[30] ITERATIONS
  {                                                                           // SONAR_NUM[1] = cm[30] ITERATIONS
    for (uint8_t i = 0; i < ITERATIONS; i++)                                  // Loop through all the iterations.
    { 
      if (millis() >= pingTimer[i])                                           // Is it this iteration's time to ping?
      {          
        pingTimer[i] += PING_INTERVAL * ITERATIONS;                           // Set next time this sensor will be pinged.
        if (i == 0 && currentIteration == ITERATIONS - 1) 
        {
          oneSensorCycle();                                                   // Sensor ping cycle complete, do something with the results.
        }
        sonar[v].timer_stop();                                                // Make sure previous timer is canceled before starting a new ping (insurance).
        currentIteration = i;                                                 // Sensor being accessed.
        cm[currentIteration] = 0;                                             // Make distance zero in case there's no ping echo for this iteration.
        sonar[v].ping_timer(echoCheck);                                       // Do the ping (processing continues, interrupt will call echoCheck to look for echo).
      }
    }
    currentSensor = v;
  }
}

void echoCheck()                                                              // If ping received, set the sensor distance to array.
{ 
  if (sonar[currentSensor].check_timer())
  {
    cm[currentIteration] = sonar[currentSensor].ping_result / US_ROUNDTRIP_CM;
  }
}

void oneSensorCycle()                                                         // All iterations complete, calculate the median.
{ 
  unsigned int uS[ITERATIONS];
  uint8_t j, it = ITERATIONS;
  uS[0] = NO_ECHO;
  for (uint8_t i = 0; i < it; i++)                                            // Loop through iteration results.
  { 
    if (cm[i] != NO_ECHO)                                                     // Ping in range, include as part of median.
    { 
      if (i > 0)
      {          // Don't start sort till second ping.
        for (j = i; j > 0 && uS[j - 1] < cm[i]; j--) // Insertion sort loop.
          uS[j] = uS[j - 1];                         // Shift ping array to correct position for sort insertion.
      } 
      else j = 0;         // First ping is sort starting point.
      uS[j] = cm[i];        // Add last ping to array in sorted position.
    } 
    else it--;            // Ping out of range, skip and don't include as part of median.
  }
  Serial.println(uS[it >> 1]);
}

I Need to get 30 iterations from each sensor, and do a median between this 60 iterations.
And after that, print the result in Serial Port.

NariGODs:
Good day everyone, i want to know how if i can use "Timer Median Sketch" with 2 HC-SR04 Sensores.

I need to get a Median between both sensors, and aftes that get this median.

If someone can help, i will be very thanks.

I got 2 HCSR-04 getting a median between 30 measures.

So in the end, i need get 60 measures from both sensors, and get this median after that.

PLEASE HELP ME !

I try this way, but something dosnt work as expected.

// ---------------------------------------------------------------------------

// Calculate a ping median using the ping_timer() method.
// ---------------------------------------------------------------------------

#include <NewPing.h>

#define SONAR_NUM      2    // Number of sensors.
#define ITERATIONS      30    // Number of iterations.
#define MAX_DISTANCE    2000  // Maximum distance (in cm) to ping.
#define PING_INTERVAL  29    // Milliseconds between sensor pings (29ms is about the min to avoid cross-sensor echo).

unsigned long pingTimer[ITERATIONS]; // Holds the times when the next ping should happen for each iteration.
unsigned int cm[ITERATIONS];        // Where the ping distances are stored.
uint8_t currentIteration = 0;        // Keeps track of iteration step.
uint8_t currentSensor = 0;

NewPing sonar[SONAR_NUM] = { 
  NewPing(3, 9, MAX_DISTANCE),
  NewPing(10, 11, MAX_DISTANCE)
  };

void setup() {
  Serial.begin(115200);
  pingTimer[0] = millis() + 75;            // First ping starts at 75ms, gives time for the Arduino to chill before starting.
  for (uint8_t i = 1; i < ITERATIONS; i++) // Set the starting time for each iteration.
    pingTimer[i] = pingTimer[i - 1] + PING_INTERVAL;
}

void loop()
{
  medicoes();
}

void medicoes()
{
  for (uint8_t v = 0; v < SONAR_NUM; v++)                                    // SONAR_NUM[0] = cm[30] ITERATIONS
  {                                                                          // SONAR_NUM[1] = cm[30] ITERATIONS
    for (uint8_t i = 0; i < ITERATIONS; i++)                                  // Loop through all the iterations.
    {
      if (millis() >= pingTimer[i])                                          // Is it this iteration's time to ping?
      {         
        pingTimer[i] += PING_INTERVAL * ITERATIONS;                          // Set next time this sensor will be pinged.
        if (i == 0 && currentIteration == ITERATIONS - 1)
        {
          oneSensorCycle();                                                  // Sensor ping cycle complete, do something with the results.
        }
        sonar[v].timer_stop();                                                // Make sure previous timer is canceled before starting a new ping (insurance).
        currentIteration = i;                                                // Sensor being accessed.
        cm[currentIteration] = 0;                                            // Make distance zero in case there's no ping echo for this iteration.
        sonar[v].ping_timer(echoCheck);                                      // Do the ping (processing continues, interrupt will call echoCheck to look for echo).
      }
    }
    currentSensor = v;
  }
}

void echoCheck()                                                              // If ping received, set the sensor distance to array.
{
  if (sonar[currentSensor].check_timer())
  {
    cm[currentIteration] = sonar[currentSensor].ping_result / US_ROUNDTRIP_CM;
  }
}

void oneSensorCycle()                                                        // All iterations complete, calculate the median.
{
  unsigned int uS[ITERATIONS];
  uint8_t j, it = ITERATIONS;
  uS[0] = NO_ECHO;
  for (uint8_t i = 0; i < it; i++)                                            // Loop through iteration results.
  {
    if (cm[i] != NO_ECHO)                                                    // Ping in range, include as part of median.
    {
      if (i > 0)
      {          // Don't start sort till second ping.
        for (j = i; j > 0 && uS[j - 1] < cm[i]; j--) // Insertion sort loop.
          uS[j] = uS[j - 1];                        // Shift ping array to correct position for sort insertion.
      }
      else j = 0;        // First ping is sort starting point.
      uS[j] = cm[i];        // Add last ping to array in sorted position.
    }
    else it--;            // Ping out of range, skip and don't include as part of median.
  }
  Serial.println(uS[it >> 1]);
}




I Need to get 30 iterations from each sensor, and do a median between this 60 iterations.
And after that, print the result in Serial Port.

As I've described ad nauseam, don't use the 15 sensor sketch as a base for your code unless you know what you're doing. If you don't, I can almost guarantee it won't work. It's for experts only and no one will want to spend the time to debug and rewrite your sketch. So you've been warned... again.

Instead, why not just use the built-in ping_median() method? Use the Ping 3 sensors sketch as a basis:

https://bitbucket.org/teckel12/arduino-new-ping/wiki/Home#!ping-3-sensors-sketch

Change it to 2 sensors, and instead of doing a ping_cm(), do a ping_median(). Since you want to do 30 iterations from each sensor, you would be doing a ping_median(30). Then, take the two results from the 2 sensors and average them. Easy peasy. Don't over-complicate it.

Tim

I am using a single JSN-SR04T-2.0 with the NewPing 1.9.0 library on a stand alone Atmega 328P.
For testing I am cycling through 10 pings with a 200 ms delay between each call. If I use the simple ping() function I get good time results (all result values within 1% or so). If I use the ping_cm() function the distance results can vary wildly. (eg 125, 126, 64, 125, 63, 63 etc). I get the same experience after swapping to another of these sensors and to another of these sensor interface cards. Do you have any idea why I could be getting such different consistency results when comparing ping() and ping_cm()?

Timbergetter:
I am using a single JSN-SR04T-2.0 with the NewPing 1.9.0 library on a stand alone Atmega 328P.
For testing I am cycling through 10 pings with a 200 ms delay between each call. If I use the simple ping() function I get good time results (all result values within 1% or so). If I use the ping_cm() function the distance results can vary wildly. (eg 125, 126, 64, 125, 63, 63 etc). I get the same experience after swapping to another of these sensors and to another of these sensor interface cards. Do you have any idea why I could be getting such different consistency results when comparing ping() and ping_cm()?

My guess is that you setup a variable which is rolling over. You can just do:

sonar.ping() / US_ROUNDTRIP_CM

which is the same as ping_cm().

Tim

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

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