#include <Keypad.h>
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byte rowPins[ROWS] = {39, 38, 37, 36};
byte colPins[COLS] = {35, 0, 45, 48};
Keypad customKeypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
const int selectorPins[] = {15, 16, 17, 18};
const int segmentPins[] = {8, 3, 46, 9, 10, 11, 12};
const byte digitMap[10][7] = {
{1,1,1,1,1,1,0}, {0,1,1,0,0,0,0}, {1,1,0,1,1,0,1}, {1,1,1,1,0,0,1},
{0,1,1,0,0,1,1}, {1,0,1,1,0,1,1}, {1,0,1,1,1,1,1}, {1,1,1,0,0,0,0},
{1,1,1,1,1,1,1}, {1,1,1,1,0,1,1}
};
// --- VARIABLES DE MEMORIA Y CONTROL ---
int dataStorage[4] = {-1, -1, -1, -1}; // Almacén de los 4 dígitos; -1 significa posición vacía
int currentPos = 0; // Puntero que rastrea la ubicación de escritura (0 a 3)
bool isLocked = false; // Interruptor lógico para bloquear o permitir edición
void setup() {
for (int x = 0; x < 7; x++) {
pinMode(segmentPins[x], OUTPUT);
digitalWrite(segmentPins[x], HIGH); // En Ánodo Común, HIGH desactiva el segmento
}
for (int y = 0; y < 4; y++) {
pinMode(selectorPins[y], OUTPUT);
digitalWrite(selectorPins[y], LOW); // Desactiva la alimentación del dígito
}
}
void loop() {
char pressedKey = customKeypad.getKey();
if (pressedKey != NO_KEY) {
if (pressedKey == '*') {
// RESET: Limpia el arreglo de datos y libera el bloqueo de escritura
for (int k = 0; k < 4; k++) dataStorage[k] = -1;
currentPos = 0;
isLocked = false;
}
else if (!isLocked) {
if (pressedKey >= '0' && pressedKey <= '9' && currentPos < 4) {
// CONVERSIÓN: Transforma el carácter ASCII en un valor numérico real
dataStorage[currentPos] = pressedKey - '0';
currentPos++;
}
else if (pressedKey == '#') {
isLocked = true; // BLOQUEO: Fija los datos actuales en el panel
}
}
}
// CICLO DE MULTIPLEXACIÓN
for (int i = 0; i < 4; i++) {
if (dataStorage[i] != -1) {
// Carga el patrón de bits en los segmentos (Lógica Inversa)
for (int s = 0; s < 7; s++) {
digitalWrite(segmentPins[s], digitMap[dataStorage[i]][s] ? LOW : HIGH);
}
// Activa el dígito actual, espera un instante y lo apaga para evitar "fantasmas"
digitalWrite(selectorPins[i], HIGH);
delay(2);
digitalWrite(selectorPins[i], LOW);
}
}
}