Hi there,
I'm using the sample code from the NewPing library to control 3 HC_SR04 sensors.
Even though the code works as intended the symbols displayed are not the distance readings.
How can this be corrected? Is it a glitch in the library?
Thanks in advance,
Charles
#include <NewPing.h>
#define SONAR_NUM 3 // Number or sensors.
#define MAX_DISTANCE 400 // Max distance in cm.
#define PING_INTERVAL 33 // Milliseconds between pings.
#define LEDL 6
#define LEDM 6
#define LEDR 6
int LEDS[] = {5, 4, 6};
unsigned long pingTimer[SONAR_NUM]; // When each pings.
unsigned int cm[SONAR_NUM]; // Store ping distances.
uint8_t currentSensor = 0; // Which sensor is active.
NewPing sonar[SONAR_NUM] = { // Sensor object array.
NewPing(10, 7, MAX_DISTANCE),
NewPing(12, 9, MAX_DISTANCE),
NewPing(11, 8, MAX_DISTANCE),
};
void setup() {
Serial.begin(115200);
pingTimer[0] = millis() + 75; // First ping start in ms.
for (uint8_t i = 1; i < SONAR_NUM; i++)
pingTimer[i] = pingTimer[i - 1] + PING_INTERVAL;
}
void loop() {
for (uint8_t i = 0; i < SONAR_NUM; i++) {
if (millis() >= pingTimer[i]) {
pingTimer[i] += PING_INTERVAL * SONAR_NUM;
if (i == 0 && currentSensor == SONAR_NUM - 1)
oneSensorCycle(); // Do something with results.
sonar[currentSensor].timer_stop();
currentSensor = i;
cm[currentSensor] = 0;
sonar[currentSensor].ping_timer(echoCheck);
}
}
}
void echoCheck() { // If ping echo, set distance to array.
if (sonar[currentSensor].check_timer())
cm[currentSensor] = sonar[currentSensor].ping_result / US_ROUNDTRIP_CM;
}
void oneSensorCycle() { // Do something with the results.
for (uint8_t i = 0; i < SONAR_NUM; i++) {
Serial.print(i);
Serial.print("=");
Serial.print(cm[i]);
Serial.print("cm ");
if (cm[i] < 10) {
digitalWrite(LEDS[i], HIGH);
} else {
digitalWrite(LEDS[i], LOW);
}
}
Serial.println();
}