Hello everyone!
I want to use 8 hc-sr04 ultrasonic sensors with arduino uno. For the first 7 sensors i want to know if there is an obstacle at 200 cm max in front of them and for the 8th sensor at 50cm. I tried the NewPing library but they are still pretty slow.
Can anyone tell me if there is something wrong with my code.This is the code that i used:
#include <NewPing.h>
#define SONAR_NUM 8 // Number or sensors.
#define MAX_DISTANCE 200 // Max distance in cm.
#define PING_INTERVAL 33 // Milliseconds between pings.
int k;
int k2=0;
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(6, 7, MAX_DISTANCE),
NewPing(4, A0, MAX_DISTANCE),
NewPing(12, 13, MAX_DISTANCE),
NewPing(8, 9, MAX_DISTANCE),
NewPing(2, A3, MAX_DISTANCE),
NewPing(5, A1, MAX_DISTANCE),
NewPing(3, A2, MAX_DISTANCE),
NewPing(10, 11, MAX_DISTANCE)
};
void setup() {
Serial.begin(9600);
pingTimer[0] = millis() + 35; // 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);
}
}
//k=0;
// 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.
k=0;
for (uint8_t i = 0; i < SONAR_NUM; i++) {
if(i<=6){
if(cm[i]>0 & cm[i]<200){
if(k==0){k=i+1;}}
}
if(i==7){
if(cm[i]>0 & cm[i]<50){
if(k==0){k=i+1;}}
}
}
if (k!=k2){
Serial.print(k);
k2=k;}
}