const byte numSensors = 3;
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};
// const = que es constante y byte = mas pequeño ocupa menos memoria, y mas rapido puede ir
//numSensors is my variable name
void setup() {
Serial.begin(115200);
//pinMode(LED_BUILTIN, OUTPUT);
pinMode(0, OUTPUT); // led 4 salida
pinMode(9, OUTPUT); // led 5 salida
pinMode(13, OUTPUT); // led 6 salida
for (byte s=0; s< numSensors; s++) { /* due to for loop we reduce pin mode instructions from 6 to only 2 (
pinMode(2, OUTPUT),
pinMode(3, 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 mathematical calculus with the velocity of souns
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 proporcional 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() { // https://sites.google.com/view/profesebaproyectos/3-1-sensor-ultras%C3%B3nico-con-3-leds-bloques
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(" ");
}
{ // imprimir en pantalla la distancia de los objetos
if (distance >= 0 && distance <= 15) { // SI la distancia es mayor o menor a... entonces...
digitalWrite(4, HIGH);
digitalWrite(5, HIGH);
digitalWrite(6, HIGH);
}
if (distance >= 15 && distance <= 30) { // SI la distancia es mayor o menor a... entonces...
digitalWrite(5, HIGH);
digitalWrite(6, HIGH);
digitalWrite(4, LOW);
} else { // si no ocurre nada de lo anterior entonces...
digitalWrite(6, HIGH);
digitalWrite(5, LOW);
digitalWrite(4, LOW);
}
ledVariable=map(distance,2,400,0,250);
digitalwritte (2, ledVariable) // 13 és el pin
Serial.println();
digitalWrite(LED_BUILTIN, isNearby ? HIGH : LOW);
delay(100);
}