// ESP32 - Button + SIM800 → Firebase
// Notifications handled by Web App (index.html)
// 100% FREE!
// By: Muhmmad Ali
#include <WiFi.h>
#include <HTTPClient.h>
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
#define FIREBASE_URL "https://sim800-controller-default-rtdb.firebaseio.com"
#define FIREBASE_AUTH "YUdjhcfUvLbp9s2ELz1x2wSx1iHhA1QnHAaQMzxw"
#define BUTTON_PIN 4
HardwareSerial sim800Serial(2); // RX=GPIO16, TX=GPIO17
String smsBuffer = "";
bool waitingContent = false;
bool lastButtonState = HIGH;
void connectWiFi() {
Serial.print("Connecting to WiFi");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
int tries = 0;
while (WiFi.status() != WL_CONNECTED && tries < 20) {
delay(500);
Serial.print(".");
tries++;
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println("\n✅ WiFi Connected: " + WiFi.localIP().toString());
} else {
Serial.println("\n❌ WiFi failed!");
}
}
void sendToFirebase(String message) {
if (WiFi.status() != WL_CONNECTED) { connectWiFi(); return; }
HTTPClient http;
String url = String(FIREBASE_URL) + "/alerts.json?auth=" + FIREBASE_AUTH;
http.begin(url);
http.addHeader("Content-Type", "application/json");
String body = "{\"message\":\"" + message + "\",\"timestamp\":" + String(millis()) + "}";
int code = http.POST(body);
Serial.println((code == 200 || code == 201) ? "✅ Firebase saved!" : "❌ Firebase error: " + String(code));
http.end();
}
void parseSIM800(String line) {
line.trim();
if (line.length() == 0) return;
Serial.println("[SIM800] " + line);
if (line.indexOf("+CMTI:") != -1) {
Serial.println("📩 New SMS! Reading...");
int comma = line.indexOf(",");
String idx = line.substring(comma + 1);
idx.trim();
sim800Serial.println("AT+CMGR=" + idx);
waitingContent = true;
return;
}
if (line.indexOf("+CMGR:") != -1) { waitingContent = true; return; }
if (waitingContent && line != "OK" && line.length() > 0) {
waitingContent = false;
Serial.println("📨 SMS: " + line);
sendToFirebase(line);
}
}
void setup() {
Serial.begin(115200);
Serial.println("=== SIM800 Alert System ===");
pinMode(BUTTON_PIN, INPUT_PULLUP);
sim800Serial.begin(9600, SERIAL_8N1, 16, 17);
delay(1000);
sim800Serial.println("AT"); delay(300);
sim800Serial.println("AT+CMGF=1"); delay(300);
sim800Serial.println("AT+CNMI=1,2,0,0,0"); delay(300);
connectWiFi();
Serial.println("✅ Ready! Press button or wait for SMS...");
}
void loop() {
if (WiFi.status() != WL_CONNECTED) connectWiFi();
// Push Button
bool currentButtonState = digitalRead(BUTTON_PIN);
if (currentButtonState == LOW && lastButtonState == HIGH) {
Serial.println("🔴 Button Pressed!");
sendToFirebase("ALERT: Button pressed!");
delay(300);
}
lastButtonState = currentButtonState;
// SIM800
while (sim800Serial.available()) {
char c = sim800Serial.read();
if (c == '\n') { parseSIM800(smsBuffer); smsBuffer = ""; }
else smsBuffer += c;
}
delay(10);
}