#define LED_PIN 26
#define BUZZER_PIN 25
#define BUTTON_PIN 27
// States
bool deviceConnected = true;
bool alarmActive = false;
bool deviceOn = true;
const int RSSI_THRESHOLD = -80;
int simulatedRssi = -70;
// Button variables
unsigned long buttonPressTime = 0;
bool buttonActive = false;
bool buttonHeld = false;
int pressCount = 0;
unsigned long lastPressTime = 0;
const int debounceTime = 50;
const int holdTime = 1000;
const int doublePressTime = 500;
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
digitalWrite(LED_PIN, LOW);
digitalWrite(BUZZER_PIN, LOW);
}
void triggerAlarm() {
if (!deviceOn || alarmActive) return;
Serial.println("🚨 ALARM: Phone out of range!");
digitalWrite(LED_PIN, HIGH);
digitalWrite(BUZZER_PIN, HIGH); // CONTINUOUS BUZZER
alarmActive = true;
}
void stopAlarm() {
if (!alarmActive) return;
Serial.println("🛑 Alarm stopped");
digitalWrite(LED_PIN, LOW);
digitalWrite(BUZZER_PIN, LOW); // TURN OFF BUZZER
alarmActive = false;
}
void toggleDevicePower() {
deviceOn = !deviceOn;
if (deviceOn) {
Serial.println("🔛 Device turned ON");
} else {
Serial.println("🔴 Device turned OFF");
digitalWrite(LED_PIN, LOW);
digitalWrite(BUZZER_PIN, LOW);
alarmActive = false;
}
}
void handleButton() {
if (digitalRead(BUTTON_PIN) == LOW) {
if (!buttonActive) {
buttonActive = true;
buttonPressTime = millis();
}
if ((millis() - buttonPressTime > holdTime) && !buttonHeld) {
buttonHeld = true;
toggleDevicePower();
}
} else {
if (buttonActive) {
if (!buttonHeld) {
if (millis() - lastPressTime < doublePressTime) {
pressCount++;
} else {
pressCount = 1;
}
lastPressTime = millis();
}
buttonActive = false;
buttonHeld = false;
}
}
if (pressCount >= 2 && (millis() - lastPressTime > debounceTime)) {
if (deviceOn && alarmActive) {
stopAlarm();
}
pressCount = 0;
}
}
void checkConnection() {
if (!deviceOn) return;
if (simulatedRssi < RSSI_THRESHOLD) {
if (deviceConnected && !alarmActive) {
triggerAlarm();
}
} else {
if (alarmActive) {
stopAlarm();
}
deviceConnected = true;
}
}
void loop() {
if (Serial.available()) {
char cmd = Serial.read();
switch (cmd) {
case 'c':
if (deviceOn) {
deviceConnected = true;
simulatedRssi = -70;
Serial.println("📱 Phone connected");
}
break;
case 'd':
if (deviceOn) {
deviceConnected = false;
simulatedRssi = -90;
Serial.println("📴 Phone disconnected");
}
break;
case '+':
simulatedRssi += 5;
Serial.print("📶 RSSI: ");
Serial.println(simulatedRssi);
break;
case '-':
simulatedRssi -= 5;
Serial.print("📶 RSSI: ");
Serial.println(simulatedRssi);
break;
}
}
handleButton();
checkConnection();
delay(10);
}