/* * MECRO FLIGHT CORE - PROYECTO 05: DADO DIGITAL (VERSIÓN ÁNODO COMÚN)
* Arquitectura: Arrays (Lookup Tables) y Generación de Azar
* Hardware: ESP32 + Display 7 Seg (ÁNODO COMÚN) + Botón
* Nota: El pin COMÚN del display debe ir a 3.3V o 5V.
*/
// --- 1. DEFINICIÓN DE PINES ---
// Orden estándar: A, B, C, D, E, F, G
const int PIN_A = 13;
const int PIN_B = 12;
const int PIN_C = 14;
const int PIN_D = 27;
const int PIN_E = 26;
const int PIN_F = 25;
const int PIN_G = 33;
const int PIN_BOTON = 4;
// Agrupamos los pines en un Array para iterar fácilmente
const int SEGMENTOS[7] = {PIN_A, PIN_B, PIN_C, PIN_D, PIN_E, PIN_F, PIN_G};
// --- 2. MAPA DE BITS (LOOKUP TABLE) ---
// Mantenemos la lógica humana: 1 = Segmento Activo, 0 = Segmento Inactivo.
// El código se encarga de invertir esto eléctricamente después.
const byte DIGITOS[10] = {
// A B C D E F G (1=Visualmente Activo)
0b1111110, // 0
0b0110000, // 1
0b1101101, // 2
0b1111001, // 3
0b0110011, // 4
0b1011011, // 5
0b1011111, // 6
0b1110000, // 7
0b1111111, // 8
0b1111011 // 9
};
void setup() {
Serial.begin(115200);
// Configurar pines de segmentos como salida
for(int i = 0; i < 7; i++) {
pinMode(SEGMENTOS[i], OUTPUT);
// IMPORTANTE PARA ÁNODO COMÚN:
// Iniciamos en HIGH para que los segmentos empiecen APAGADOS.
digitalWrite(SEGMENTOS[i], HIGH);
}
pinMode(PIN_BOTON, INPUT_PULLUP);
// --- INGENIERÍA DE ENTROPÍA ---
randomSeed(analogRead(34));
Serial.println("--- DADO DIGITAL (ANODO COMUN) LISTO ---");
mostrarNumero(0); // Test inicial
}
void loop() {
if (digitalRead(PIN_BOTON) == LOW) {
// Efecto de "Rodar" el dado
efectoRodar();
// Generar número final (1 al 6)
int resultado = random(1, 7);
mostrarNumero(resultado);
Serial.print("Resultado: ");
Serial.println(resultado);
// Esperar a que se suelte el botón
while(digitalRead(PIN_BOTON) == LOW);
delay(200); // Debounce
}
}
// Función auxiliar para pintar el número
void mostrarNumero(int num) {
byte patron = DIGITOS[num];
for(int i = 0; i < 7; i++) {
// Leemos si el bit es 1 (activo) o 0 (inactivo)
// Ajuste de lectura: Bit 6 (A) hasta Bit 0 (G)
int estadoLogico = bitRead(patron, 6 - i);
// --- ADAPTACIÓN ÁNODO COMÚN ---
// Si estadoLogico es 1 (queremos luz), enviamos LOW.
// Si estadoLogico es 0 (queremos apagado), enviamos HIGH.
// El operador '!' invierte el valor (NOT lógico).
digitalWrite(SEGMENTOS[i], !estadoLogico);
}
}
void efectoRodar() {
int velocidad = 50;
for(int i = 0; i < 15; i++) {
mostrarNumero(random(1, 7));
delay(velocidad);
velocidad += 20; // Efecto de frenado (fricción simulada)
}
}