/* * MECRO FLIGHT CORE - PROYECTO 06: HUICHA DIGITAL
* Arquitectura: Sensores de Tiempo de Vuelo (ToF) y Displays
* Hardware: ESP32 + HC-SR04 + TM1637
* Librería requerida: TM1637 (by Avishay Orpaz)
*/
#include <TM1637Display.h>
// --- 1. DEFINICIONES DE PINES ---
const int PIN_TRIG = 5; // Salida de pulso (Trigger)
const int PIN_ECHO = 18; // Entrada de eco (Echo) - ¡Cuidado con 5V!
const int PIN_CLK = 19; // Reloj Display
const int PIN_DIO = 23; // Datos Display
// --- 2. FÍSICA DEL SONIDO ---
// Velocidad del sonido en aire a 20°C = ~343 m/s
// En cm/µs (centímetros por microsegundo) = 0.0343 cm/µs
const float VELOCIDAD_SONIDO = 0.0343;
// Inicializar Display
TM1637Display display(PIN_CLK, PIN_DIO);
void setup() {
Serial.begin(115200);
pinMode(PIN_TRIG, OUTPUT);
pinMode(PIN_ECHO, INPUT); // El sensor pone este pin en HIGH
// Configurar brillo (0-7). 0x0f es máximo.
display.setBrightness(0x0f);
// Animación de inicio "----"
uint8_t data[] = { 0xff, 0xff, 0xff, 0xff }; // Todos los segmentos
display.setSegments(data);
delay(1000);
display.clear();
Serial.println("--- MECRO TELEMETRY: SONAR READY ---");
}
void loop() {
// 1. LIMPIAR TRIGGER
digitalWrite(PIN_TRIG, LOW);
delayMicroseconds(2);
// 2. GENERAR PULSO DE 10µs
// Esto le dice al HC-SR04 que lance sus 8 ondas de sonido
digitalWrite(PIN_TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(PIN_TRIG, LOW);
// 3. MEDIR TIEMPO DE VUELO
// pulseIn espera a que el pin pase a HIGH y cuenta µs hasta que baja a LOW
// Timeout opcional para no bloquear el código si no hay eco
long duracion = pulseIn(PIN_ECHO, HIGH, 30000); // Max 30ms (~5 metros)
// 4. CALCULAR DISTANCIA
// Distancia = (Tiempo * Velocidad) / 2 (Ida y Vuelta)
float distancia = (duracion * VELOCIDAD_SONIDO) / 2;
// 5. VISUALIZACIÓN
Serial.print("Distancia: ");
Serial.print(distancia);
Serial.println(" cm");
// Mostrar en el display (sin decimales para simplicidad)
if (duracion == 0) {
// Si no hay eco (fuera de rango)
display.showNumberDec(8888, false); // Código de error visual
} else if (distancia > 400 || distancia < 2) {
// Rango físico del sensor HC-SR04
display.showNumberDec(0, false);
} else {
display.showNumberDec((int)distancia, false); // False = sin ceros a la izquierda
}
delay(200); // Tasa de refresco de 5Hz
}