https://wokwi.com/projects/347478624767574611
const byte numSensors = 3; //const means constant variables, byte means small space in memory, numSensors is the variable name.
const byte ECHO_PIN[numSensors] = {2, 5, 8}; //We create an array to be used in a for loop
const byte TRIG_PIN[numSensors] = {3, 4, 7};
void setup() {
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT);
for (byte s=0; s< numSensors; s++) { /*Due to for loop, we reduce pinMode instructions from 6 to only 2
pinMode(3, OUTPUT);
pinMode(2, INPUT);
pinMode(4, OUTPUT);
pinMode(5, INPUT);
pinMode(7, OUTPUT);
pinMode(8, INPUT); */
pinMode(TRIG_PIN[s], OUTPUT);
pinMode(ECHO_PIN[s], INPUT);
}
}
float readDistanceCM(byte s) { /*This is a function with a parameter (s) and return a value that depends on the duration of a pulseIn function and a mathemtical calcules with the velocity of sound*/
digitalWrite(TRIG_PIN[s], LOW); /*We need to have the trigger pin Controlled to a low value in order to measure the duration of the high value that is proportional to the distance of the sensor*/
delayMicroseconds(2);
digitalWrite(TRIG_PIN[s], HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN[s], LOW);
int duration = pulseIn(ECHO_PIN[s], HIGH);
return duration * 0.034 / 2; //Divided by 2 because the ultrasound goes and returns back
}
void loop() {
bool isNearby = false;
Serial.print("Measured distance: ");
for (byte s=0; s< numSensors; s++) {
float distance = readDistanceCM(s);
isNearby |= distance < 100;
Serial.print(distance);
Serial.print(" ");
}
Serial.println();
digitalWrite(LED_BUILTIN, isNearby);
delay(100);
}