domingo, 1 de marzo de 2026

Lectura HC-SR04 con Alerta (If/Else)

 /*

   TITULO: Lectura HC-SR04 con Alerta (If/Else)
   CURSO: Grado Séptimo
   
   OBJETIVO:
   1. Medir distancia con el sensor.
   2. Usar un condicional (IF/ELSE) para tomar una decisión:
      - SI algo está muy cerca (< 15 cm): ¡ENCENDER LED! (Alarma)
      - SINO (está lejos): APAGAR LED (Todo tranquilo)
*/

// --- 1. CONFIGURACIÓN DE PINES ---
const int PIN_TRIG = 5;       // Pin que envía la señal (Grita)
const int PIN_ECHO = 18;      // Pin que recibe el eco (Escucha)
const int PIN_LED_INTERNO = 2; // El LED que ya viene pegado en la ESP32

// Variables matemáticas
long duracion;  // Tiempo que demora el eco
int distancia;  // Distancia calculada en cm

void setup() {
  Serial.begin(115200); // Iniciar comunicación con el PC
 
  // Configuramos los modos de los pines
  pinMode(PIN_TRIG, OUTPUT);      // El sensor habla (Salida)
  pinMode(PIN_ECHO, INPUT);       // El sensor escucha (Entrada)
  pinMode(PIN_LED_INTERNO, OUTPUT); // El LED es una salida de luz
 
  Serial.println("--- SISTEMA DE ALARMA INICIADO ---");
}

void loop() {
  // --- PASO 1: LIMPIAR Y PREPARAR ---
  digitalWrite(PIN_TRIG, LOW);
  delayMicroseconds(2);

  // --- PASO 2: ENVIAR EL PULSO (PING) ---
  digitalWrite(PIN_TRIG, HIGH);
  delayMicroseconds(10);
  digitalWrite(PIN_TRIG, LOW);

  // --- PASO 3: CALCULAR EL TIEMPO ---
  duracion = pulseIn(PIN_ECHO, HIGH);

  // --- PASO 4: CONVERTIR A CENTÍMETROS ---
  distancia = duracion * 0.034 / 2;

  // --- PASO 5: IMPRIMIR EN PANTALLA ---
  Serial.print("Distancia detectada: ");
  Serial.print(distancia);
  Serial.println(" cm");

  // --- PASO 6: TOMAR DECISIONES (CEREBRO DEL PROGRAMA) ---
  // Aquí usamos el condicional IF (Si) y ELSE (Si no)
 
  if (distancia < 15) {
    // CASO A: SI la distancia es menor a 15cm (Hay un intruso cerca)
    digitalWrite(PIN_LED_INTERNO, HIGH); // ¡ENCENDER ALARMA!
    Serial.println("¡ALERTA! Objeto muy cerca");
   
  } else {
    // CASO B: SI NO se cumple lo de arriba (Está lejos)
    digitalWrite(PIN_LED_INTERNO, LOW);  // Apagar alarma
  }

  // Esperar un poco antes de medir de nuevo
  delay(200);
}


ACTIVITY:

🍄 MISSION: PROGRAMMING THE ORELLANA FARM COBOT

Instructions for students: Read the code carefully. Copy the questions and write your answers in your notebook (cuaderno).

1. The Decision Maker

To automate the Orellana farm, the Cobot needs to make choices.

  • Look at Step 6 in the code. Which two keywords allow the Cobot to choose between two different actions?

  • Answer in your notebook: The two words are ________ and ________.

2. Protecting the Mushrooms

The Cobot uses the HC-SR04 sensor to detect if a harvest basket or a person is too close to the Orellana bags.

  • If the sensor detects an object at 10 cm, what happens to the LED? (ON or OFF?)

  • Why is this "Alarm" important for a mushroom farm?

3. Translate the Code

Translate these technical instructions into simple Spanish for the farm workers:

  • if (distancia < 15) -> ________________________________

  • digitalWrite(PIN_LED_INTERNO, HIGH); -> ________________________________

  • else -> ________________________________

4. Code Detective: Brackets { }

In C++, we use "Curly Brackets" { } to group the Cobot's actions.

  • Look at the code. What symbols do we use to "open" and "close" the actions of the if and the else?

  • What happens if you forget to close a bracket in the Arduino IDE?

5. Adjusting the Sensor

The Orellana bags are growing! now you need more space. You want the Cobot to alert you only when something is closer than 25 cm.

  • Write the new line of code for this change in your notebook:

  • New code: if (distancia < ____ )


6. WOKWI CHALLENGE: THE FARM SAFETY SYSTEM 🛠️

Build the Orellana protection circuit in Wokwi.com.

  1. The Controller: Add an ESP32 DevKit V1.

  2. The Sensor: Connect Trig to Pin 5 and Echo to Pin 18.

  3. The Alarm: Connect an LED to Pin 2.

  4. The Goal: Run the simulation. The LED must turn ON only when the distance is less than 15 cm.

Sensor HC-SR04ESP32 (Pin)Color de cable sugerido
VCC5V o VINRojo (Energía)
TrigD5Verde (Señal)
EchoD18Amarillo (Eco)
GNDGNDNegro (Tierra)

No hay comentarios:

Publicar un comentario