#include <Wire.h>
#include <Keypad.h>
#include <LiquidCrystal_I2C.h>
#include <WiFi.h>
#include <time.h>
#define LED_PIN 4
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// LCD I2C
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Keypad config
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] = {13, 12, 14, 27};
byte colPins[COLS] = {26, 25, 33, 32};
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
// Variables globales
int alarmHour = -1, alarmMinute = -1;
String alarmInput = "";
bool settingAlarm = false, alarmValid = false;
void setup() {
pinMode(LED_PIN, OUTPUT);
lcd.init();
lcd.backlight();
WiFi.begin(ssid, password);
lcd.setCursor(0,0); lcd.print("Conectando WiFi");
while (WiFi.status() != WL_CONNECTED) delay(500);
configTime(-5 * 3600, 0, "pool.ntp.org"); // UTC-5 para Perú
lcd.clear();
}
void loop() {
struct tm timeinfo;
if(!getLocalTime(&timeinfo)){
lcd.setCursor(0,0);
lcd.print("Sin hora NTP ");
//delay(1000);
return;
}
int currentHour = timeinfo.tm_hour;
int currentMinute = timeinfo.tm_min;
int currentSecond = timeinfo.tm_sec;
char key = keypad.getKey();
if (!settingAlarm) {
showCurrentTime(currentHour, currentMinute, currentSecond);
if (key == 'A') {
settingAlarm = true;
alarmInput = "";
lcd.clear();
lcd.setCursor(2,0);
lcd.print("Configurar");
lcd.setCursor(0,1);
lcd.print("Alarma HHMM:");
}
} else {
if (key) {
if (key >= '0' && key <= '9' && alarmInput.length() < 4) {
alarmInput += key;
lcd.setCursor(alarmInput.length() + 11,1);
lcd.print(key);
} else if (key == 'B') {
validateAlarm();
} else if (key == '#') {
settingAlarm = false;
lcd.clear();
}
}
}
// Verifica alarma
if (alarmValid && currentHour == alarmHour && currentMinute == alarmMinute) {
blinkLed();
} else {
digitalWrite(LED_PIN, LOW);
}
delay(100);
}
void showCurrentTime(int h, int m, int s) {
lcd.setCursor(0, 0);
lcd.print("Hora: ");
if (h < 10) lcd.print("0");
lcd.print(h);
lcd.print(":");
if (m < 10) lcd.print("0");
lcd.print(m);
lcd.print(":");
if (s < 10) lcd.print("0");
lcd.print(s);
lcd.setCursor(0, 1);
lcd.print("A:Alarma");
}
void validateAlarm() {
if (alarmInput.length() == 4) {
int h = alarmInput.substring(0,2).toInt();
int m = alarmInput.substring(2,4).toInt();
if (h >= 0 && h <= 23 && m >= 0 && m <= 59) {
alarmHour = h;
alarmMinute = m;
alarmValid = true;
lcd.clear();
lcd.setCursor(3,0);
lcd.print("Alarma ok");
} else {
alarmValid = false;
lcd.clear();
lcd.setCursor(2,0);
lcd.print("Hora Invalida");
}
} else {
lcd.clear();
lcd.setCursor(2,0);
lcd.print("Hora Invalida");
}
delay(1500);
settingAlarm = false;
lcd.clear();
}
void blinkLed() {
static unsigned long lastBlink = 0;
static bool ledOn = false;
if (millis() - lastBlink > 500) {
ledOn = !ledOn;
digitalWrite(LED_PIN, ledOn ? HIGH : LOW);
lastBlink = millis();
}
}