#define BLYNK_TEMPLATE_ID "TMPL6wJBZ1UwE"
#define BLYNK_TEMPLATE_NAME "Smart Alert"
#define BLYNK_AUTH_TOKEN "7YRSjbv5NTXycPyzuislimA46KzxIYen"
#define BLYNK_PRINT Serial
#include <WiFi.h>
#include <BlynkSimpleEsp32.h>
// Pins
#define LED 18
#define EMERGENCY_BTN 19 // Physical push button pin (must be interrupt-capable)
char ssid[] = "Wokwi-GUEST";
char pass[] = "";
volatile bool emergencyFlag = false; // Marked volatile for interrupt
bool emergencyMode = false;
unsigned long lastBlinkTime = 0;
unsigned long lastDebounceTime = 0;
const unsigned long debounceDelay = 200; // Debounce time in ms
const int buzzerPin = 5; // GPIO pin connected to the passive buzzer
const int minFrequency = 500; // Minimum frequency in Hz
const int maxFrequency = 2000; // Maximum frequency in Hz
const int stepDuration = 15; // Time between frequency steps in ms
const int pauseBetweenCycles = 500; // Pause at the end of each siren cycle
WidgetLED led2(V0);
// Interrupt Service Routine (keep it short!)
IRAM_ATTR void handleInterrupt() {
if ((millis() - lastDebounceTime) > debounceDelay) {
emergencyFlag = true;
lastDebounceTime = millis();
}
}
void setup() {
Serial.begin(115200);
pinMode(LED, OUTPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(EMERGENCY_BTN, INPUT_PULLUP);
// Attach interrupt to the button pin
attachInterrupt(digitalPinToInterrupt(EMERGENCY_BTN), handleInterrupt, FALLING);
Blynk.begin(BLYNK_AUTH_TOKEN, ssid, pass);
}
void loop() {
Blynk.run();
// Check if interrupt was triggered
if (emergencyFlag) {
emergencyFlag = false;
emergencyMode = true;
Blynk.virtualWrite(V1, 1); // Update Blynk switch
Blynk.virtualWrite(V2, "Emergency State");
Blynk.logEvent("mergency_alert","Emergency");
}
// Handle emergency/normal modes
if (emergencyMode) {
siren();
}
else {
// Normal mode - blink every 10 minutes
if (millis() - lastBlinkTime >= 600000) {
digitalWrite(LED, HIGH);
led2.on();
delay(200);
digitalWrite(LED, LOW);
led2.off();
lastBlinkTime = millis();
}
Blynk.virtualWrite(V2, "Normal State");
}
}
// Blynk switch can ONLY turn off emergency
BLYNK_WRITE(V1) {
if (param.asInt() == 0) {
emergencyMode = false;
// digitalWrite(LED, LOW);
noTone(buzzerPin);
//led2.off();
Blynk.virtualWrite(V2, "Neutralized State");
delay(5000);
digitalWrite(LED, LOW);
led2.off();
lastBlinkTime = millis();
}
}
void siren() {
// Rising tone (low to high frequency)
for (int freq = minFrequency; freq <= maxFrequency; freq += 10) {
tone(buzzerPin, freq);
delay(stepDuration);
digitalWrite(LED, HIGH);
led2.on();
delay(50);
digitalWrite(LED, LOW);
delay(50);
led2.off();
}
// Falling tone (high to low frequency)
for (int freq = maxFrequency; freq >= minFrequency; freq -= 10) {
tone(buzzerPin, freq);
delay(stepDuration);
digitalWrite(LED, HIGH);
led2.on();
delay(50);
digitalWrite(LED, LOW);
delay(50);
led2.off();
}
// Short pause between siren cycles
noTone(buzzerPin);
delay(pauseBetweenCycles);
}