Hello, I'm new here so sorry if this is the wrong place to post this.
I'm trying to run a program that uses multiple HC-SR04 ultrasonic sensors for obstacle detection simultaneously, so that whenever a sensor detects an object less than 20cm away, a corresponding DC vibrating motor will turn on. However, I read online that the pulseIn() function that's used in the standard code for these sensors won't work for this purpose since it basically "stalls" the controller and so at best I can just include a timeout and run the sensors consecutively. I wrote a program that uses micros() to time everything and would like to ask, is this a viable solution? I also read that it's possible to use interrupts but am not familiar with those and decided to avoid them. I wrote the code so it would work with a general number of sensors but in this case I've only defined the pins for 2 sensors.
/* General number of ultrasonic sensors */
const int range = 20;
const int buffer_size = 2;
const int trigPins[] = {4, 7};
const int echoPins[] = {5, 6};
const int motorPins[] = {9, 10};
int distance[buffer_size] = {0};
int power[buffer_size] = {};
void setup() {
for (int i = 0; i < buffer_size; i++) {
pinMode(trigPins[i], OUTPUT);
pinMode(echoPins[i], INPUT);
pinMode(motorPins[i], OUTPUT);
digitalWrite(trigPins[i], LOW);
}
delayMicroseconds(2);
Serial.begin(9600);
}
void loop() {
for (int i = 0; i < buffer_size; i++) {
digitalWrite(trigPins[i], LOW);
}
delayMicroseconds(2);
for (int i = 0; i < buffer_size; i++) {
digitalWrite(trigPins[i], HIGH);
}
delayMicroseconds(10);
for (int i = 0; i < buffer_size; i++) {
digitalWrite(trigPins[i], LOW);
}
while (1) {
int counter1 = 0;
for (int i = 0; i < buffer_size; i++) {
if (digitalRead(echoPins[i]) == HIGH)
counter1++;
}
if (counter1 == buffer_size) break;
}
long timer = micros();
while (1) {
int counter2 = 0;
for (int i = 0; i < buffer_size; i++) {
if (digitalRead(echoPins[i]) == HIGH)
distance[i] = (micros() - timer) * 0.034 / 2;
else counter2++;
}
if (counter2 == buffer_size) break;
}
for (int i = 0; i < buffer_size; i++) {
if (distance[i] <= range)
power[i] = 255 - distance[i] * 255 / (2 * range);
else
power[i] = 0;
}
for (int i = 0; i < buffer_size; i++) {
analogWrite(motorPins[i], power[i]);
}
// DEBUGGING
for (int i = 0; i < buffer_size; i++) {
Serial.println("NEW CYCLE");
Serial.print("Distance sensor ");
Serial.print(i);
Serial.print(" is ");
Serial.println(distance[i]);
Serial.print("Motor power ");
Serial.print(i);
Serial.print(" is ");
Serial.println(power[i]);
Serial.println("END CYCLE");
Serial.println();
}
}