My Arduino Mega 2560 arrived in the post this morning!
I was hoping that somebody would be able to help me with the code to find the HC-SR04 sensor outputting the biggest value.
I am using the example code provided on the 'NewPing' page but I have changed the number of sensors to 3 rather than 15.
#include <NewPing.h>
#define SONAR_NUM 3 // Number or sensors.
#define MAX_DISTANCE 200 // Max distance in cm.
#define PING_INTERVAL 33 // Milliseconds between pings.
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(40, 41, MAX_DISTANCE),
NewPing(42, 43, MAX_DISTANCE),
NewPing(44, 45, 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);
}
}
// The rest of your code would go here.
}
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 ");
}
Serial.println();
I assume that I would put it after the "void oneSensorCycle()" bit of code if somebody would please be able to help me work out how to get the Arduino to feedback which sensor is giving out the highest distance value.
Thank you.