#include <WiFi.h>
#include <WebServer.h>
#include <DNSServer.h>
#include <WiFiManager.h>
#include <Preferences.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
Preferences preferences;
LiquidCrystal_I2C lcd(0x27, 20, 4);
int userThreshold = 2500;
int maxAlarm = 0;
int rebootCount = 0;
const int potPin = 34;
char thresholdValue[6] = "2500";
unsigned long startTime = 0;
void setup() {
lcd.init();
lcd.backlight();
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("=== WIFI MANAGER ===");
preferences.begin("iot_storage", false);
userThreshold = preferences.getInt("user_threshold", 2500);
maxAlarm = preferences.getInt("max_alarm", 0);
rebootCount = preferences.getInt("reboot_num", 0);
rebootCount++;
preferences.putInt("reboot_num", rebootCount);
sprintf(thresholdValue, "%d", userThreshold);
lcd.setCursor(0, 1);
lcd.print("Max Alarm: ");
lcd.print(maxAlarm);
lcd.setCursor(0, 2);
lcd.print("Connecting WiFi...");
WiFi.disconnect(true, true);
WiFiManager wm;
wm.setConnectTimeout(3);
wm.setConfigPortalTimeout(1);
WiFiManagerParameter custom_threshold("threshold", "Temp Limit", thresholdValue, 5);
wm.addParameter(&custom_threshold);
if (!wm.autoConnect("ESP32-Auto-Config", NULL)) {
WiFi.begin("Wokwi-GUEST", "");
unsigned long startAttempt = millis();
while (WiFi.status() != WL_CONNECTED && millis() - startAttempt < 5000) {
delay(100);
}
}
if (WiFi.status() != WL_CONNECTED) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("WiFi FAILED");
delay(3000);
ESP.restart();
}
if (custom_threshold.getValue() != NULL && strlen(custom_threshold.getValue()) > 0) {
userThreshold = atoi(custom_threshold.getValue());
preferences.putInt("user_threshold", userThreshold);
}
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("WiFi Connected");
lcd.setCursor(0, 2);
lcd.print("Max Alarm: ");
lcd.print(maxAlarm);
startTime = millis();
}
void loop() {
int potValue = analogRead(potPin);
unsigned long elapsed = (millis() - startTime) / 1000;
unsigned long timeLeft = (elapsed < 15) ? (15 - elapsed) : 0;
lcd.setCursor(0, 0);
if (potValue > userThreshold) {
lcd.print("!!! ALARM !!! ");
} else {
lcd.print("WiFi Connected ");
}
lcd.setCursor(0, 1);
char rebootBuf[21];
sprintf(rebootBuf, "Rbt: %d | Rem: %ds ", rebootCount, timeLeft);
lcd.print(rebootBuf);
lcd.setCursor(0, 3);
char potBuf[21];
sprintf(potBuf, "Pot: %d ", potValue);
lcd.print(potBuf);
if (potValue > 2500 && potValue > maxAlarm) {
maxAlarm = potValue;
preferences.putInt("max_alarm", maxAlarm);
lcd.setCursor(0, 2);
lcd.print("Max Alarm: ");
lcd.print(maxAlarm);
lcd.print(" ");
}
if (millis() - startTime >= 5000) {
lcd.clear();
lcd.setCursor(0, 1);
lcd.print(" REBOOTING... ");
delay(1000);
ESP.restart();
}
delay(500);
}