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

why serial.print do'nt exactly distance "?
please help me!
#include <NewPing.h>

#define TRIGGER_PIN A0 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN A1 // 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.
#define TRIGGER_PIN2 A2 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN2 A3
#define TRIGGER_PIN3 A4 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN3 A5
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
NewPing sonar1(TRIGGER_PIN2, ECHO_PIN2, MAX_DISTANCE);
NewPing sonar2(TRIGGER_PIN3, ECHO_PIN3, MAX_DISTANCE);
void setup() {
Serial.begin(115200);
}

void loop() {
delay(50); .
unsigned int uS = sonar.ping();
unsigned int uS1 = sonar1.ping();
unsigned int uS2 = sonar2.ping();
Serial.print('left');
Serial.print(uS2 / US_ROUNDTRIP_CM);
Serial.println('');
Serial.print('right');
Serial.print(uS1 / US_ROUNDTRIP_CM); // Convert ping time to distance in cm and print result (0 = outside set distance range)
Serial.println();
Serial.print('frent');
Serial.print(uS / US_ROUNDTRIP_CM); // Convert ping time to distance in cm and print result (0 = outside set distance range)
Serial.println();
}

Serial.print('left');

Double quotes

Please use code tags.

phamtuan1151:
why serial.print do'nt exactly distance "?
please help me!

Yes, what he said --^ Use double quotes, not single quotes. For example:

Serial.print("stalker");

Let us know if that fixes things for you.

Tim

fernandossala:

teckel:

fernandossala:
It works like a champion!
Thanks a bunch, next time, i will send pictures and videos of the final project!
Best Regards,
Fernando

Glad I could help! Would love to see the final project. I hope it's something fast-moving that chases your cat around the house or something cool like that.

Tim

not fast moving chasing cat cool, but still cool...
here's a picture of the installation without the electronics
the relays will give power to three industrial fans (one for each letter). the middle one needs to be filled first, this is why i need to relays, as soon as i put the electronics inside the case, i will take more pictures and video for you guys
cheers
Fernando

here's the video of the Intervention I did with my installation in Copacabana

and you can see the sensor working at its best

fernandossala:
here's the video of the Intervention I did with my installation in Copacabana

EGO in Copacabana - YouTube
and you can see the sensor working at its best

I could tell the dog's ego was inflated due to your project.

Tim

Hello!

I noticed SR06 sensor has a temperature sensor on the board as well, which can be used for temperature compensation.
Are those measurements more accurate?
How much more? Let's say I have a sensor without temperature compensation and I set my code to 20°, but ambient temperature is 30°C. How big of a deviation would I see?

Matej

levak:
Hello!

I noticed SR06 sensor has a temperature sensor on the board as well, which can be used for temperature compensation.
Are those measurements more accurate?
How much more? Let's say I have a sensor without temperature compensation and I set my code to 20°, but ambient temperature is 30°C. How big of a deviation would I see?

Matej

The formula for the speed of sound is: m/s = 331.3 + (0.606 x C°)

So, at 20°, the speed of sound is 343.42 m/s and at 30° it's 349.48.

Towards the extreme edge of the sensor range, lets say you get a ping time of 29,000 ms. That would give you:

29,000 ms / 10,000 x 343.42 m/s / 2 = 497.96 cm
29,000 ms / 10,000 x 349.48 m/s / 2 = 506.75 cm

So, temperature does make a difference, in this example, almost 9cm. Likewise, at 100cm, the difference would still be about 1.75 cm, so still sizable.

With this said, it's typically not an issue. Because for normal uses, the sensor is not being used to measure an exact distance, but instead to see if something is approaching or too close relative to a previous ping. However, if you're using the sensor to measure an exact distance (say a water level) and you must get very precise distance results over a long period of time at various temperatures, then using a thermostat and doing the above calculation would be very important. All depends on your need. NewPing is designed to work easily with the built-in ping_cm() method, or you can roll your own with ping().

Tim

Does NewPing library supports temperature compensation with SRF06 sensor?
Can it automatically read temperature and use it in it's calculation?

lp, Matej

levak:
Does NewPing library supports temperature compensation with SRF06 sensor?
Can it automatically read temperature and use it in it's calculation?

lp, Matej

The sensor does not output the temperature. It simply reads the temp and adjusts the output based on the temp. So yes, NewPing works along with the thermostat and is used in the calculations.

Tim

I did some reading on SR-06 and I found out it does the corrections on the sensor itself... So yea, your lib does support that:)

levak:
I did some reading on SR-06 and I found out it does the corrections on the sensor itself... So yea, your lib does support that:)

I think that's what I said, or at least I meant to say that.

Tim

I have try upload the sketch with arduino1.05R2 but i get 1 of sensor sornar aktive 1 more not working please... help me...it.s make me crazy :stuck_out_tongue:

the sketch as bellow :stuck_out_tongue:

/* Code modified for analog output by: mOuchadino
 
 Available PWM pin : 3, 5, 6, 9, 10, 11
 Available Digital I/O pin : 2 to 13
*/

#include <NewPing.h>

#define SONAR_NUM 2 // Number or sensors.
#define MAX_DISTANCE 400 // Maximum distance (in cm) to ping.
#define PING_INTERVAL 30 // 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.

NewPing sonar[SONAR_NUM] = { // Sensor object array.
  NewPing(5, 6, MAX_DISTANCE), // Each sensor's echo pin, trigger pin, and max distance to ping.
  NewPing(7, 8, MAX_DISTANCE),
};

int pwmPins[SONAR_NUM] = {
  9, 10 }; // array Nomor pin utk keluaran PWM Analog out 0-5v
int led = 13;

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

  for (uint8_t i = 0; i < SONAR_NUM; i++) { // pwm output pin counter
    pinMode(pwmPins[i], OUTPUT);
  }
 
  {               
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);     
}
 
  Serial.println();
}

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

{
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(2000);               // wait for a second
}
  // Other code that *DOESN'T* analyze ping results can go here.
}

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

// Sensor ping cycle complete, do something with the results. Location option 1 for code processing

void oneSensorCycle()
{
  for (uint8_t i = 0; i < SONAR_NUM; i++) {
    // turn the pin on:
    // http://arduino.cc/en/Reference/analogWrite
    analogWrite(pwmPins[i], cm[i]);

    //        Serial.print(i); // print sensor number accessed
    //        Serial.print("="); // = märk
    //        Serial.print(cm[i]); // sensor distance value
    //        Serial.println("cm "); // cm
    //        Print format i = xxx cm
  }
} 

===========================================================================================

#include <NewPing.h>

#define SONAR_NUM 2 // Number or sensors.
#define MAX_DISTANCE 400 // 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.

NewPing sonar[SONAR_NUM] = { // Sensor object array.
 // Each sensor's trigger pin, echo pin, and max distance to ping.
  NewPing(5, 6, MAX_DISTANCE),
  NewPing(7, 8, MAX_DISTANCE),
  
};

int pwmPins[SONAR_NUM] = {9, 10 };  // an array of pin numbers to which pwm output is written
int led = 13;

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

  for (uint8_t i = 0; i < SONAR_NUM; i++) { // pwm output pin counter
    pinMode(pwmPins[i], OUTPUT);
   }
 {               
  
   // initialize the digital pin as an output.
   
  pinMode(led, OUTPUT);     
}
 
  Serial.println();
}

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

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

// Sensor ping cycle complete, do something with the results. Location option 1 for code processing

void oneSensorCycle()
{
  for (uint8_t i = 0; i < SONAR_NUM; i++) {
    // turn the pin on:
    
    analogWrite(pwmPins[i], cm[i]);

            Serial.print(i); // print sensor number accessed
            Serial.print("="); // = märk
            Serial.print(cm[i]); // sensor distance value
            Serial.println("cm "); // cm
    //        Print format i = xxx cm
  }
}

moderator update: added code tags --> # button above smileys

==============================================================================
i modifed the sketch like as bellow =( still not working with 2 sonar

#include <NewPing.h>

#define SONAR_NUM 2 // Number or sensors.
#define MAX_DISTANCE 400 // Maximum distance (in cm) to ping.
#define PING_INTERVAL 100 // 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.

NewPing sonar[SONAR_NUM] = { // Sensor object array.
  NewPing(5, 6, MAX_DISTANCE), // Each sensor's echo pin, trigger pin, and max distance to ping.
  NewPing(7, 8, MAX_DISTANCE),
};

int pwmPins[SONAR_NUM] = {9, 10 }; // array Nomor pin utk keluaran PWM Analog out 0-5v
int ledPins[SONAR_NUM] = {12, 13};

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

for (uint8_t i = 0; i < SONAR_NUM; i++) { // pwm output pin counter
    pinMode(pwmPins[i], OUTPUT);
  }
                
  // initialize the digital pin as an output.
  
for (uint8_t i = 0; i < SONAR_NUM; i++) { // pwm output pin counter
    pinMode(ledPins[i], OUTPUT);
  }  
 
  Serial.println();
}

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

{
{
  digitalWrite(ledPins[12,13], HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(500);               // wait for a second
  digitalWrite(ledPins[13,12], LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second
}
}
  // Other code that *DOESN'T* analyze ping results can go here.
}

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

// Sensor ping cycle complete, do something with the results. Location option 1 for code processing

void oneSensorCycle()
{
  for (uint8_t i = 0; i < SONAR_NUM; i++) {
    // turn the pin on:

    analogWrite(pwmPins[i], cm[i]);

            Serial.print(i); // print sensor number accessed
            Serial.print("="); // = märk
            Serial.print(cm[i]); // sensor distance value
            Serial.println(" -cm "); // cm
    //        Print format i = xxx cm
  }
}

===========================================================================

but if i.m delete the as bellow the 2 sensor work fine :stuck_out_tongue:

{
  digitalWrite(ledPins[12,13], HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(500);               // wait for a second
  digitalWrite(ledPins[13,12], LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second
}

every body please help me ..... =( =(

moderator update: added code tags --> # button above smileys

Hi Tim,

Any Plans for releasing the version 1.6 soon?

I am using this with ATtiny as well as arduino and trying to avoid keeping the timers commented/uncommented for each use :slight_smile:

Thanks for the great library BTW

Shomar

I have problem with this library. If I upload example sketch, everything works, but if I use this library for my project, Arduino loose USB communication, does anybody knows what should I do?
Thanks

Thank you for writing this library out for us.

I just got DYP-ME007Y module, and I've never played around with it. So, I straight away use your library.. and..

NewPingExample does not seem to work.

NewPingEventTimer work. But we have to only grab the first reading of the second wave onwards if the reading is important to you. Pardon me if my linggo is not correct.

So let say, the first wave (1, 2, 3, 4, 5, 6, 7), ignore this.

Then, subsequent waves onwards, it looks like (77, 67, 57, 47, 37, 28, 25). So, you may pick any one of this. I would prefer picking the first reading in my case.

PLEASE, PLEASE include code for the 3 pin parallax 28015 sensors. They are available now for 1/10 the price of the 4 pin sensors.

OK here is a suprise: set the Trigger_Pin and Echo_Pin to the same port and by golly it seems to be working fine!

Ping / Parallax 28015 3-pin sensor

I am not sure why I'm not getting a return of zero for sensor readings that are out of range. I get wildly varying distances when there is nothing in front of the sensors, but accurate readings when I have something in front. Any ideas? I have two HC-SR04s on my bot, so I modified the NewPingExample for 2 sensors, but it does the same thing when only one sensor is being pinged.

#include <NewPing.h>

#define L_TRIG 46  // Arduino pin tied to trigger pin on the left ultrasonic sensor.
#define L_ECHO 47  // Arduino pin tied to echo pin on the left ultrasonic sensor.

#define R_TRIG 48  // Arduino pin tied to trigger pin on the right ultrasonic sensor.
#define R_ECHO 49  // Arduino pin tied to echo pin on the right 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_L(L_TRIG, L_ECHO, MAX_DISTANCE); // NewPing setup of pins and maximum distance for left sensor.
NewPing sonar_R(R_TRIG, R_ECHO, MAX_DISTANCE); // NewPing setup of pins and maximum distance for right sensor.

unsigned int uS; //declare variable for ping time in microseconds

void setup() {
  Serial.begin(9600); // Open serial monitor at 9600 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.
  uS = sonar_L.ping(); // Send ping, get ping time in microseconds (uS).
 
  Serial.print("L Ping: "); 
  Serial.print(uS / US_ROUNDTRIP_CM); // Convert ping time to distance in cm and print result (0 = outside set distance range)
 
   
  uS = sonar_R.ping(); // Send ping, get ping time in microseconds (uS).

  Serial.print("\tR Ping: ");
  Serial.println(uS / US_ROUNDTRIP_CM); // Convert ping time to distance in cm and print result (0 = outside set distance range)
 
}

ping sensor data.xlsx (10.3 KB)

Hi Tim,

Can this library be used to work with the maxsonar range of proximity sensors? Like this one.....

The sensor generates a pulse whose width is proportional to distance, the problem is that measuring the pulse width requires the use of the pulseIn() function which can take some time.

Thanks