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

solaron99:
Hi! Fantastic library.

I simply want to use 2 HC-SR04 sensors and use the result to turn on their appropriate LED when MAX_DISTANCE is less than 30.

SR04 #1 - turns on LED1 when MAX_DISTANCE is less than 30

  • turns off LED1 when MAX_DISTANCE is greater than 30

SR04 #2 - turns on LED2 when MAX_DISTANCE is less than 30

  • turns off LED2 when MAX_DISTANCE is greater than 30

I added an if/else statement in the pingResults() function, LED 1 turns ON and remains on when
either sensor is triggered.
What do I have to do to declare both sensor 1 and sensor 2 in the function?

Sounds pretty simple but I'm kinda new at this so be gentle! :slight_smile:

Thanks.

Here's the sketch:

#include <NewPing.h>

#define SONAR_NUM 2
#define MAX_DISTANCE 30
#define PING_INTERVAL 33
//LED setup
#define LED_1 12
#define LED_2 13

unsigned long pingTimer[SONAR_NUM];
uint8_t currentSensor = 0;

NewPing sonar[SONAR_NUM] = {
NewPing(4, 5, MAX_DISTANCE),
NewPing(6, 7, MAX_DISTANCE)
};

void setup() {
pinMode(LED_1, OUTPUT);
pinMode(LED_2, OUTPUT);

Serial.begin(115200);
pingTimer[0] = millis() + 75;
for (uint8_t i = 1; i < SONAR_NUM; i++)
pingTimer = pingTimer[i - 1] + PING_INTERVAL;
}
void loop() {

  • for (uint8_t i = 0; i < SONAR_NUM; i++) {*
    _ if (millis() >= pingTimer*) { _
    pingTimer += PING_INTERVAL * SONAR_NUM;
    sonar[currentSensor].timer_stop();
    _ currentSensor = i; _
    sonar[currentSensor].ping_timer(echoCheck);
    _ }
    }
    }
    void echoCheck() { _
    if (sonar[currentSensor].check_timer())

    pingResult(currentSensor, sonar[currentSensor].ping_result / US_ROUNDTRIP_CM);
    _}
    void pingResult(uint8_t sensor, int cm) { // Sensor got a ping, do something with the result.
    // The following code would be replaced with your code that does something with the ping result.*_

* if (cm < MAX_DISTANCE) {
digitalWrite(LED_1, HIGH);
_ }
else {_
digitalWrite(LED_1, LOW);*

* }*

* for (uint8_t i = 0; i < SONAR_NUM; i++) {
_ Serial.print(sensor);
Serial.print(" ");
Serial.print(cm);
Serial.println("cm");
}*
Serial.println();_

}
[/quote]
The 15 sensor example sketch is more for advanced users that require a multi-tasking type script where multiple things will be happening at basically the same time. Therefore, your use is well outside these parameters.
Instead, simply use the basic one sensor example sketch and add a second sensor.
Basically, you're trying to make it much more complicated than it needs to be, which is why you're having problems.
Now, if you had an already event driven sketch and you wanted to add two sensors while still keeping your sketch event-driven, then using the 15 sensor sketch would be appropriate.
Tim