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

Hey,

I just recently started using this library and noticed that when I disconnect my sensor and use ping(), instead of getting NO_ECHO (0) sometimes it reports a random number (usually 20-30cm below MAX_SENSOR_DISTANCE). Wondering if anyone else is experiencing this issue?

This is especially impacting the reliability of ping.median() as NO ECHOs are factored out, so even just 1 faulty reading is sufficient for the sensor to still report a measurement.

NewPing.h (renamed to sr4t)

#include "WProgram.h"

#define sr4t_h
#define MAX_SENSOR_DISTANCE 300
#define US_ROUNDTRIP_CM 58
#define NO_ECHO 0
#define MAX_SENSOR_DELAY 5800   // Maximum uS it takes for sensor to start the ping
#define ECHO_TIMER_FREQ 24      // Frequency to check for a ping echo
#define PING_MEDIAN_DELAY 29000
#define PING_OVERHEAD 5
#define PING_TIMER_OVERHEAD 13
#define NewPingConvert(echoTime, conversionFactor) (max(((unsigned int)echoTime + conversionFactor / 2) / conversionFactor, (echoTime ? 1 : 0)))

class sr4t {
public:
sr4t(uint8_t trigger_pin, uint8_t echo_pin, unsigned int max_cm_distance = MAX_SENSOR_DISTANCE);
unsigned int ping(unsigned int max_cm_distance = 0);
unsigned long ping_cm(unsigned int max_cm_distance = 0);
unsigned long ping_in(unsigned int max_cm_distance = 0);
unsigned long ping_median(uint8_t it = 5, unsigned int max_cm_distance = 0);
static unsigned int convert_cm(unsigned int echoTime);
static unsigned int convert_in(unsigned int echoTime);
private:
boolean ping_trigger();
void set_max_distance(unsigned int max_cm_distance);
uint8_t _triggerPin;
uint8_t _echoPin;
unsigned int _maxEchoTime;
unsigned long _max_time;
   };

NewPing.cpp

#include "sr4t.h"

sr4t::sr4t(uint8_t trigger_pin, uint8_t echo_pin, unsigned int max_cm_distance) {
    _triggerPin = trigger_pin;
    _echoPin = echo_pin;
	set_max_distance(max_cm_distance);
    }

unsigned int sr4t::ping(unsigned int max_cm_distance) {
	if (max_cm_distance > 0) set_max_distance(max_cm_distance); // Call function to set a new max sensor distance.
	if (!ping_trigger()) return NO_ECHO; // Trigger a ping, if it returns false, return NO_ECHO to the calling function.
	while (digitalRead(_echoPin))                 // Wait for the ping echo.
	    if (micros() > _max_time) return NO_ECHO; // Stop the loop and return NO_ECHO (false) if we're beyond the set maximum distance.
	    return (micros() - (_max_time - _maxEchoTime) - PING_OVERHEAD); // Calculate ping time, include overhead.
    }

unsigned long sr4t::ping_cm(unsigned int max_cm_distance) {
	unsigned long echoTime = sr4t::ping(max_cm_distance); // Calls the ping method and returns with the ping echo distance in uS.
	return (echoTime / US_ROUNDTRIP_CM);              // Call the ping method and returns the distance in centimeters (no rounding).
    }

unsigned long sr4t::ping_median(uint8_t it, unsigned int max_cm_distance) {
	unsigned int uS[it], last;
	uint8_t j, i = 0;
	unsigned long t;
	uS[0] = NO_ECHO;
	while (i < it) {
		t = micros();                  // Start ping timestamp.
		last = ping(max_cm_distance);  // Send ping.
		if (last != 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] < last; 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] = last;              // Add last ping to array in sorted position.
			i++;                       // Move to next ping.
		    } 
		else it--;                   // Ping out of range, skip and don't include as part of median.
		if (i < it && micros() - t < PING_MEDIAN_DELAY)
			delay((PING_MEDIAN_DELAY + t - micros()) / 1000); // Millisecond delay between pings.
	    }
	return (uS[it >> 3]); // Return the ping 12.5th percentile distance.
    }

boolean sr4t::ping_trigger() {
	pinMode(_triggerPin, OUTPUT); // Set trigger pin to output.
	digitalWrite(_triggerPin, LOW);
	delayMicroseconds(4);
	digitalWrite(_triggerPin, HIGH);
	delayMicroseconds(10);
	digitalWrite(_triggerPin, LOW);
    pinMode(_triggerPin, INPUT);  // Set trigger pin to input (when using one Arduino pin, this is technically setting the echo pin to input as both are tied to the same Arduino pin).
	if (digitalRead(_echoPin)) return false;                // Previous ping hasn't finished, abort.
	_max_time = micros() + _maxEchoTime + MAX_SENSOR_DELAY; // Maximum time we'll wait for ping to start (most sensors are <450uS, the SRF06 can take up to 34,300uS!)
	while (!digitalRead(_echoPin))                          // Wait for ping to start.
	    if (micros() > _max_time) return false;             // Took too long to start, abort.
	    _max_time = micros() + _maxEchoTime; // Ping started, set the time-out.
	    return true;                         // Ping started successfully.
    }

void sr4t::set_max_distance(unsigned int max_cm_distance) {
	_maxEchoTime = min(max_cm_distance + 1, (unsigned int) MAX_SENSOR_DISTANCE + 1) * US_ROUNDTRIP_CM; // Calculate the maximum distance in uS (no rounding).
    }

unsigned int sr4t::convert_cm(unsigned int echoTime) {
	return (echoTime / US_ROUNDTRIP_CM);              // Convert uS to centimeters (no rounding).
    }

enjoyneering:
So why do we need it? it just takes ram and time to execute the code.

You have the option! Turn it off and save a bit of memory, or leave it on and it works with one pin. The default "on" method works either way, which is why it's default. Also, the saved memory is VERY small, probably 8 bytes. So it's not much of a hit for 100% compatibility.

But, you have the option so I'm not sure what the issue is. 100% compatibility out of the box and a user option to save 8 bytes sounds like the only solution to me. But, make an argument if you wish.

Tim

Vitesze:
Hey,

I just recently started using this library and noticed that when I disconnect my sensor and use ping(), instead of getting NO_ECHO (0) sometimes it reports a random number (usually 20-30cm below MAX_SENSOR_DISTANCE). Wondering if anyone else is experiencing this issue?

This is especially impacting the reliability of ping.median() as NO ECHOs are factored out, so even just 1 faulty reading is sufficient for the sensor to still report a measurement.

NewPing.h (renamed to sr4t)

#include "WProgram.h"

#define sr4t_h
#define MAX_SENSOR_DISTANCE 300
#define US_ROUNDTRIP_CM 58
#define NO_ECHO 0
#define MAX_SENSOR_DELAY 5800  // Maximum uS it takes for sensor to start the ping
#define ECHO_TIMER_FREQ 24      // Frequency to check for a ping echo
#define PING_MEDIAN_DELAY 29000
#define PING_OVERHEAD 5
#define PING_TIMER_OVERHEAD 13
#define NewPingConvert(echoTime, conversionFactor) (max(((unsigned int)echoTime + conversionFactor / 2) / conversionFactor, (echoTime ? 1 : 0)))

class sr4t {
public:
sr4t(uint8_t trigger_pin, uint8_t echo_pin, unsigned int max_cm_distance = MAX_SENSOR_DISTANCE);
unsigned int ping(unsigned int max_cm_distance = 0);
unsigned long ping_cm(unsigned int max_cm_distance = 0);
unsigned long ping_in(unsigned int max_cm_distance = 0);
unsigned long ping_median(uint8_t it = 5, unsigned int max_cm_distance = 0);
static unsigned int convert_cm(unsigned int echoTime);
static unsigned int convert_in(unsigned int echoTime);
private:
boolean ping_trigger();
void set_max_distance(unsigned int max_cm_distance);
uint8_t _triggerPin;
uint8_t _echoPin;
unsigned int _maxEchoTime;
unsigned long _max_time;
  };



NewPing.cpp


#include "sr4t.h"

sr4t::sr4t(uint8_t trigger_pin, uint8_t echo_pin, unsigned int max_cm_distance) {
    _triggerPin = trigger_pin;
    _echoPin = echo_pin;
set_max_distance(max_cm_distance);
    }

unsigned int sr4t::ping(unsigned int max_cm_distance) {
if (max_cm_distance > 0) set_max_distance(max_cm_distance); // Call function to set a new max sensor distance.
if (!ping_trigger()) return NO_ECHO; // Trigger a ping, if it returns false, return NO_ECHO to the calling function.
while (digitalRead(_echoPin))                // Wait for the ping echo.
    if (micros() > _max_time) return NO_ECHO; // Stop the loop and return NO_ECHO (false) if we're beyond the set maximum distance.
    return (micros() - (_max_time - _maxEchoTime) - PING_OVERHEAD); // Calculate ping time, include overhead.
    }

unsigned long sr4t::ping_cm(unsigned int max_cm_distance) {
unsigned long echoTime = sr4t::ping(max_cm_distance); // Calls the ping method and returns with the ping echo distance in uS.
return (echoTime / US_ROUNDTRIP_CM);              // Call the ping method and returns the distance in centimeters (no rounding).
    }

unsigned long sr4t::ping_median(uint8_t it, unsigned int max_cm_distance) {
unsigned int uS[it], last;
uint8_t j, i = 0;
unsigned long t;
uS[0] = NO_ECHO;
while (i < it) {
t = micros();                  // Start ping timestamp.
last = ping(max_cm_distance);  // Send ping.
if (last != 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] < last; 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] = last;              // Add last ping to array in sorted position.
i++;                      // Move to next ping.
    }
else it--;                  // Ping out of range, skip and don't include as part of median.
if (i < it && micros() - t < PING_MEDIAN_DELAY)
delay((PING_MEDIAN_DELAY + t - micros()) / 1000); // Millisecond delay between pings.
    }
return (uS[it >> 3]); // Return the ping 12.5th percentile distance.
    }

boolean sr4t::ping_trigger() {
pinMode(_triggerPin, OUTPUT); // Set trigger pin to output.
digitalWrite(_triggerPin, LOW);
delayMicroseconds(4);
digitalWrite(_triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(_triggerPin, LOW);
    pinMode(_triggerPin, INPUT);  // Set trigger pin to input (when using one Arduino pin, this is technically setting the echo pin to input as both are tied to the same Arduino pin).
if (digitalRead(_echoPin)) return false;                // Previous ping hasn't finished, abort.
_max_time = micros() + _maxEchoTime + MAX_SENSOR_DELAY; // Maximum time we'll wait for ping to start (most sensors are <450uS, the SRF06 can take up to 34,300uS!)
while (!digitalRead(_echoPin))                          // Wait for ping to start.
    if (micros() > _max_time) return false;            // Took too long to start, abort.
    _max_time = micros() + _maxEchoTime; // Ping started, set the time-out.
    return true;                        // Ping started successfully.
    }

void sr4t::set_max_distance(unsigned int max_cm_distance) {
_maxEchoTime = min(max_cm_distance + 1, (unsigned int) MAX_SENSOR_DISTANCE + 1) * US_ROUNDTRIP_CM; // Calculate the maximum distance in uS (no rounding).
    }

unsigned int sr4t::convert_cm(unsigned int echoTime) {
return (echoTime / US_ROUNDTRIP_CM);              // Convert uS to centimeters (no rounding).
    }

I haven't experienced this, but it could be based on the sensor and microcontroller you're using. I would try to tweak these values higher to see if that resolves the problem:

#define MAX_SENSOR_DELAY 5800
#define PING_MEDIAN_DELAY 29000

These values worked for all of my sensors, but because they are sensor dependent, I made them easy to modify. As a starting point, double both and see if that resolves the problem. If so, it's then just a matter of figuring out what the best value is for your microcontroller.

Tim

Vitesze:
Hey,

I just recently started using this library and noticed that when I disconnect my sensor and use ping(), instead of getting NO_ECHO (0) sometimes it reports a random number (usually 20-30cm below MAX_SENSOR_DISTANCE). Wondering if anyone else is experiencing this issue?

If you leave pins floating sometimes it happens that they get sufficient noise that is evaluated as a echo.

teckel:
I haven't experienced this, but it could be based on the sensor and microcontroller you're using. I would try to tweak these values higher to see if that resolves the problem:

#define MAX_SENSOR_DELAY 5800

#define PING_MEDIAN_DELAY 29000




These values worked for all of my sensors, but because they are sensor dependent, I made them easy to modify. As a starting point, double both and see if that resolves the problem. If so, it's then just a matter of figuring out what the best value is for your microcontroller.

Tim

I'm using the Particle Electron, and JSN-SR04T sensor. Changing these values hasn't worked - I tried adding a pull-up/down resistor and it also didn't appear to help much.

So you're saying you can use this library, leave the actual TRIG/ECHO pin unpopulated (or non-functioning sensor) and it will always return the NO ECHO value (i.e. 0)?

Vitesze:
I'm using the Particle Electron, and JSN-SR04T sensor. Changing these values hasn't worked - I tried adding a pull-up/down resistor and it also didn't appear to help much.

So you're saying you can use this library, leave the actual TRIG/ECHO pin unpopulated (or non-functioning sensor) and it will always return the NO ECHO value (i.e. 0)?

No, as zoomx stated, if nothing is connected to a pin it's in a floating state, and that could read as a distance measurement. Adding a pull-down to echo should help, but I've never tired doing this as I've always connected a sensor.

In any case, this would be outside the scope of software as it's totally a hardware situation (missing sensor or floating echo pin). Nothing software can do in this situation, you need hardware to create the wanted pin state (keep echo pin low).

Tim

Hi! Can you please help me with my code?

I want combine motor code and newping. I use 1 stepper motor and 6 ultrasonic sensor. My intention is to program motor that rotate after take 200 cycles of newping reading. I have no idea how to program 200 sensorcycle reading of newping per rotation motor. When i try combine motor with 6 newping sensor, the reading only show at last sensor(refer photo attached).

I attach a copy below.

#include <NewPing.h>
#include <Stepper.h>

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

unsigned long pingTimer[SONAR_NUM]; // Holds the times when the next ping should happen for each sensor.
unsigned int cm[SONAR_NUM];         // Where the ping distances are stored.
uint8_t currentSensor = 0;          // Keeps track of which sensor is active.

const int stepsPerRevolution = 200;
int stepCount = 0;
Stepper myStepper(stepsPerRevolution, 32,33,34,35);

NewPing sonar[SONAR_NUM] = {     // Sensor object array.
  NewPing(2, 3, MAX_DISTANCE), // Each sensor's trigger pin, echo pin, and max distance to ping.
  NewPing(4, 5, MAX_DISTANCE),
  NewPing(6, 7, MAX_DISTANCE),
  NewPing(8, 9, MAX_DISTANCE),
  NewPing(10, 11, MAX_DISTANCE),
  NewPing(12, 13, 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 < SONAR_NUM; i++) // Set the starting time for each sensor.
    pingTimer[i] = pingTimer[i - 1] + PING_INTERVAL;
}

void loop() {
  for (uint8_t i = 0; i < SONAR_NUM; i++) { // Loop through all the sensors.
    if (millis() >= pingTimer[i]) {         // Is it this sensor's time to ping?
      pingTimer[i] += PING_INTERVAL * SONAR_NUM;  // Set next time this sensor will be pinged.
      if (i == 0 && currentSensor == SONAR_NUM - 1) oneSensorCycle(); // Sensor ping cycle complete, do something with the results.
      sonar[currentSensor].timer_stop();          // Make sure previous timer is canceled before starting a new ping (insurance).
      currentSensor = i;                          // Sensor being accessed.
      cm[currentSensor] = 0;                      // Make distance zero in case there's no ping echo for this sensor.
      sonar[currentSensor].ping_timer(echoCheck); // Do the ping (processing continues, interrupt will call echoCheck to look for echo).
    }
  }
  
  // Other code that *DOESN'T* analyze ping results can go here.
{    if(stepCount < 10) 
  {
    RotateMotor();
    Serial.print("steps:");
    Serial.println(stepCount);
  }
  else {
    StopMotor();
  }
  stepCount++;}
}

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

void oneSensorCycle() { // Sensor ping cycle complete, do something with the results.
  // The following code would be replaced with your code that does something with the ping results.
  for (uint8_t i = 0; i < SONAR_NUM; i++) {

    Serial.print("US");
    Serial.print(i+1);
    Serial.print("=");
    Serial.print(cm[i]);
    Serial.print("cm ");
  }
  Serial.println();
}

void RotateMotor() {
  myStepper.step(1);
  delay(500);
}

void StopMotor() {
  myStepper.step(0);
  delay(500);
}

Sadly, I get compile errors.

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