#include <Preferences.h>
Preferences prefs;
const int PINO_NIVEL = 34;
const int PINO_LED = 5;
const int PINO_BUZZER = 18;
const int LIMIAR = 3000;
const int MAX_EVENTOS = 20;
unsigned int totalEventos = 0;
bool emAlerta = false;
void registrarEvento(int nivel) {
totalEventos++;
prefs.putUInt("total", totalEventos);
int slot = (totalEventos - 1) % MAX_EVENTOS;
char chave[16];
snprintf(chave, sizeof(chave), "ev%d", slot);
prefs.putInt(chave, nivel);
Serial.printf(">> EVENTO #%u registrado em NVS (slot %d, nivel=%d)\n",
totalEventos, slot, nivel);
}
void mostrarHistorico() {
Serial.println("\n--- HISTORICO PERSISTENTE ---");
int n = min((unsigned int)MAX_EVENTOS, totalEventos);
for (int i = 0; i < n; i++) {
int slot = (totalEventos - 1 - i) % MAX_EVENTOS;
char chave[16];
snprintf(chave, sizeof(chave), "ev%d", slot);
int nivel = prefs.getInt(chave, -1);
Serial.printf(" -%d: nivel=%d\n", i, nivel);
}
Serial.println("------------------------------\n");
}
void setup() {
Serial.begin(115200);
pinMode(PINO_LED, OUTPUT);
pinMode(PINO_BUZZER, OUTPUT);
prefs.begin("enchente", false);
totalEventos = prefs.getUInt("total", 0);
Serial.printf("\n=== NO DE MONITORAMENTO INICIADO ===\n");
Serial.printf("Eventos historicos: %u\n", totalEventos);
mostrarHistorico();
}
void loop() {
int nivel = analogRead(PINO_NIVEL);
if (nivel >= LIMIAR && !emAlerta) {
emAlerta = true;
digitalWrite(PINO_LED, HIGH);
tone(PINO_BUZZER, 1000);
registrarEvento(nivel);
} else if (nivel < LIMIAR && emAlerta) {
emAlerta = false;
digitalWrite(PINO_LED, LOW);
noTone(PINO_BUZZER);
Serial.println("Nivel normalizado.");
}
delay(500);
}