-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathESP32_Arduino_Code.ino
More file actions
535 lines (427 loc) Β· 17.1 KB
/
ESP32_Arduino_Code.ino
File metadata and controls
535 lines (427 loc) Β· 17.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
/*****************************************************************************************
*
* SHEild-X ESP32 Firmware (Clean & Optimized v2.0)
*
* Fully optimized, cleaned, stable Arduino String-based firmware.
*
* Features:
* - BLE communication (Command, Status, Data characteristics)
* - SOS Trigger + 10s Countdown + Cancellation
* - Police Alert
* - SMS sending (SIM800L/SIM900)
* - Battery monitoring (ADC + virtual fallback)
* - Button control with Debounce + Single/Double Press logic
* - Status notifications & Data notifications
* - Non-blocking architecture
*
*****************************************************************************************/
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
/* ------------------------- CONFIGURATION ------------------------- */
#define LED_PIN 2
#define BUTTON_PIN 0
#define BATTERY_ADC_PIN 34
#define GSM_RX_PIN 16
#define GSM_TX_PIN 17
#define GSM_POWER_PIN 4
#define DEVICE_NAME "SHEild-ESP32"
#define BUTTON_DEBOUNCE_MS 50
#define DOUBLE_PRESS_WINDOW_MS 500
#define SOS_COUNTDOWN_MS 10000 // 10s
// BLE UUIDs
#define SERVICE_UUID "0000ff00-0000-1000-8000-00805f9b34fb"
#define COMMAND_CHAR_UUID "0000ff01-0000-1000-8000-00805f9b34fb"
#define STATUS_CHAR_UUID "0000ff02-0000-1000-8000-00805f9b34fb"
#define DATA_CHAR_UUID "0000ff03-0000-1000-8000-00805f9b34fb"
// Commands
#define CMD_GET_STATUS 0x01
#define CMD_TRIGGER_SOS 0x02
#define CMD_CANCEL_SOS 0x03
#define CMD_TRIGGER_POLICE 0x04
#define CMD_SET_EMERGENCY 0x05
#define CMD_SET_LED 0x06
#define CMD_GET_BATTERY 0x07
#define CMD_SEND_SMS 0x08
/* ------------------------- GLOBALS ------------------------- */
BLEServer *pServer = NULL;
BLECharacteristic *pCommandCharacteristic = NULL;
BLECharacteristic *pStatusCharacteristic = NULL;
BLECharacteristic *pDataCharacteristic = NULL;
bool deviceConnected = false;
bool oldDeviceConnected = false;
bool ledState = false;
bool sosActive = false;
unsigned long sosStartTime = 0;
String emergencyContact = "+1234567890";
int batteryLevel = 87; // fallback battery %
HardwareSerial gsmSerial(2);
// Button states - Enhanced logic
int lastReading = HIGH;
int buttonState = HIGH;
unsigned long lastDebounceMillis = 0;
int pressCount = 0;
unsigned long lastPressTime = 0;
bool inFirstCancelWindow = false; // 10s window after double press
bool inSecondCancelWindow = false; // 30s window after SOS sent
unsigned long cancelWindowStart = 0;
/* ------------------------- FUNCTION DECLARATIONS ------------------------- */
void sendStatusUpdate();
void setLED(bool on);
void updateBattery();
void sendSMS(String phone, String message);
void sendButtonEvent(uint8_t eventType);
void handleGetStatus();
void handleTriggerSOS();
void handleCancelSOS();
void handleTriggerPolice();
void handleSetEmergencyContact(const String &payload);
void handleSetLED(const String &payload);
void handleGetBattery();
void handleSendSMS(const String &payload);
/* ------------------------- BLE CALLBACKS ------------------------- */
class MyServerCallbacks : public BLEServerCallbacks {
void onConnect(BLEServer *pServer) {
deviceConnected = true;
Serial.println("BLE: Device connected.");
}
void onDisconnect(BLEServer *pServer) {
deviceConnected = false;
Serial.println("BLE: Device disconnected.");
}
};
class MyCommandCallbacks : public BLECharacteristicCallbacks {
void onWrite(BLECharacteristic *pCharacteristic) {
String payload = pCharacteristic->getValue();
if (payload.length() == 0) return;
uint8_t cmd = payload[0];
Serial.print("BLE command received: 0x");
Serial.println(cmd, HEX);
switch (cmd) {
case CMD_GET_STATUS: handleGetStatus(); break;
case CMD_TRIGGER_SOS: handleTriggerSOS(); break;
case CMD_CANCEL_SOS: handleCancelSOS(); break;
case CMD_TRIGGER_POLICE: handleTriggerPolice(); break;
case CMD_SET_EMERGENCY: handleSetEmergencyContact(payload); break;
case CMD_SET_LED: handleSetLED(payload); break;
case CMD_GET_BATTERY: handleGetBattery(); break;
case CMD_SEND_SMS: handleSendSMS(payload); break;
default:
Serial.println("Unknown BLE command.");
break;
}
}
};
/* ------------------------- STATUS HANDLING ------------------------- */
void sendStatusUpdate() {
if (!deviceConnected || !pStatusCharacteristic) return;
updateBattery();
uint8_t buff[4] = {
(uint8_t)batteryLevel,
1, // GSM active (static ON)
ledState ? 1 : 0,
deviceConnected ? 1 : 0
};
pStatusCharacteristic->setValue(buff, 4);
pStatusCharacteristic->notify();
Serial.printf("STATUS SENT β Battery:%d%% LED:%d BLE:%d\n",
batteryLevel, ledState, deviceConnected);
}
/* ------------------------- COMMAND HANDLERS ------------------------- */
void handleGetStatus() {
sendStatusUpdate();
}
void handleTriggerSOS() {
if (sosActive) {
Serial.println("SOS already active.");
return;
}
sosActive = true;
sosStartTime = millis();
setLED(true);
Serial.println("SOS Triggered - SMS will be sent after 10s countdown.");
Serial.println("(Note: This is separate from button cancel window)");
sendStatusUpdate();
}
void handleCancelSOS() {
if (!sosActive) { Serial.println("SOS not active."); return; }
sosActive = false;
setLED(false);
Serial.println("SOS Cancelled.");
sendStatusUpdate();
}
void handleTriggerPolice() {
Serial.println("POLICE ALERT TRIGGERED!");
String msg = "π¨ POLICE ALERT π¨\nImmediate danger detected.\nTime: "
+ String(millis()/1000) + "s";
sendSMS(emergencyContact, msg);
for (int i=0;i<4;i++){ setLED(true); delay(150); setLED(false); delay(150); }
sendStatusUpdate();
}
void handleSetEmergencyContact(const String &payload) {
String phone = payload.substring(1);
phone.trim();
if (phone.length() > 5) {
emergencyContact = phone;
Serial.print("Updated emergency contact: ");
Serial.println(emergencyContact);
}
}
void handleSetLED(const String &payload) {
bool state = payload[1] == 0x01;
setLED(state);
sendStatusUpdate();
}
void handleGetBattery() {
updateBattery();
sendStatusUpdate();
}
void handleSendSMS(const String &payload) {
if (payload.length() < 3) return;
uint8_t len = payload[1];
String phone = payload.substring(2, 2 + len);
String msg = payload.substring(2 + len);
sendSMS(phone, msg);
}
/* ------------------------- HARDWARE CONTROL ------------------------- */
void setLED(bool on) {
ledState = on;
digitalWrite(LED_PIN, on ? HIGH : LOW);
}
void updateBattery() {
#ifdef BATTERY_ADC_PIN
int adc = analogRead(BATTERY_ADC_PIN);
float voltage = (adc/4095.0f) * 3.3f * 2.0f;
batteryLevel = constrain((int)((voltage - 2.8f) / 1.4f * 100), 0, 100);
#else
batteryLevel--; if (batteryLevel < 20) batteryLevel = 87;
#endif
}
void sendSMS(String phone, String message) {
Serial.println("SMS β " + phone);
Serial.println(message);
// Add real GSM handling here
}
// Send button event to web app via BLE
void sendButtonEvent(uint8_t eventType) {
if (!deviceConnected) {
Serial.println("β Button event: BLE not connected");
return;
}
if (!pDataCharacteristic) {
Serial.println("β Button event: Data characteristic not available");
return;
}
// Format: [0xFF, eventType]
// eventType: 0x01 = Single press, 0x02 = Double press
uint8_t eventData[2] = {0xFF, eventType};
pDataCharacteristic->setValue(eventData, 2);
pDataCharacteristic->notify();
Serial.print("β Button event sent to web app: ");
Serial.println(eventType == 0x01 ? "SINGLE PRESS" : "DOUBLE PRESS");
}
/* ------------------------- BUTTON LOGIC ------------------------- */
void handleButton() {
int reading = digitalRead(BUTTON_PIN);
unsigned long now = millis();
static bool buttonWasPressed = false;
// Detect button press (with debounce)
if (reading == LOW && !buttonWasPressed) {
delay(50); // Debounce
if (digitalRead(BUTTON_PIN) == LOW) {
buttonWasPressed = true;
pressCount++;
lastPressTime = now;
Serial.print("[BTN] Press detected (Count: ");
Serial.print(pressCount);
Serial.println(")");
// Wait for button release
while (digitalRead(BUTTON_PIN) == LOW) {
delay(10);
}
buttonWasPressed = false;
}
}
// Handle First Cancel Window (10s after double press)
if (!inFirstCancelWindow && pressCount == 2) {
Serial.println("βββββββββββββββββββββββββββββββββββββββ");
Serial.println("ππ DOUBLE PRESS β 10s Cancel Window Started");
Serial.println("βββββββββββββββββββββββββββββββββββββββ");
inFirstCancelWindow = true;
cancelWindowStart = now;
pressCount = 0;
// Notify web app: double press detected, cancel window started
sendButtonEvent(0x02); // Double press = cancel window started
}
// Check First Cancel Window (10 seconds)
if (inFirstCancelWindow) {
unsigned long elapsed = now - cancelWindowStart;
unsigned long remaining = 10000 - elapsed;
// Check for triple press to cancel
if (pressCount >= 3) {
Serial.println("βββββββββββββββββββββββββββββββββββββββ");
Serial.println("πππ TRIPLE PRESS β SOS CANCELLED");
Serial.println("βββββββββββββββββββββββββββββββββββββββ");
// Flash LED to confirm cancellation
for (int i = 0; i < 3; i++) {
setLED(true);
delay(200);
setLED(false);
delay(200);
}
inFirstCancelWindow = false;
pressCount = 0;
sendButtonEvent(0x03); // Triple press = cancelled
return;
}
// Time expired - trigger SOS
if (elapsed >= 10000) {
Serial.println("βββββββββββββββββββββββββββββββββββββββ");
Serial.println("β° 10s Window Expired β SOS TRIGGERED");
Serial.println("βββββββββββββββββββββββββββββββββββββββ");
handleTriggerSOS();
sendButtonEvent(0x01); // Single press = SOS triggered
inFirstCancelWindow = false;
inSecondCancelWindow = true;
cancelWindowStart = now;
pressCount = 0;
}
}
// Check Second Cancel Window (30 seconds after SOS)
if (inSecondCancelWindow) {
unsigned long elapsed = now - cancelWindowStart;
unsigned long remaining = 30000 - elapsed;
// Check for triple press to cancel police alert
if (pressCount >= 3) {
Serial.println("βββββββββββββββββββββββββββββββββββββββ");
Serial.println("πππ TRIPLE PRESS β Police Alert CANCELLED");
Serial.println("βββββββββββββββββββββββββββββββββββββββ");
// Flash LED to confirm cancellation
for (int i = 0; i < 3; i++) {
setLED(true);
delay(200);
setLED(false);
delay(200);
}
inSecondCancelWindow = false;
pressCount = 0;
sendButtonEvent(0x04); // Triple press in second window = police cancelled
return;
}
// Time expired - trigger police alert
if (elapsed >= 30000) {
Serial.println("βββββββββββββββββββββββββββββββββββββββ");
Serial.println("β° 30s Window Expired β POLICE ALERT TRIGGERED");
Serial.println("βββββββββββββββββββββββββββββββββββββββ");
handleTriggerPolice();
sendButtonEvent(0x05); // Police alert triggered
inSecondCancelWindow = false;
pressCount = 0;
}
}
// Reset press count if too much time passed (prevent accidental counts)
if (!inFirstCancelWindow && !inSecondCancelWindow && (now - lastPressTime > 2000)) {
pressCount = 0;
}
lastReading = reading;
}
/* ------------------------- SETUP ------------------------- */
void setup() {
Serial.begin(115200);
delay(200);
Serial.println("\n\nβββββββββββββββββββββββββββββββββββββββ");
Serial.println(" SHEild-X ESP32 Starting...");
Serial.println("βββββββββββββββββββββββββββββββββββββββ\n");
pinMode(LED_PIN, OUTPUT);
setLED(false);
pinMode(BUTTON_PIN, INPUT_PULLUP);
delay(10); // Stabilize pin
lastReading = digitalRead(BUTTON_PIN);
buttonState = lastReading;
Serial.print("Button Pin: GPIO ");
Serial.println(BUTTON_PIN);
Serial.print("Initial State: ");
Serial.println(buttonState == HIGH ? "HIGH (not pressed)" : "LOW (pressed)");
Serial.print("Debounce: ");
Serial.print(BUTTON_DEBOUNCE_MS);
Serial.println("ms");
Serial.print("Double Press Window: ");
Serial.print(DOUBLE_PRESS_WINDOW_MS);
Serial.println("ms\n");
BLEDevice::init(DEVICE_NAME);
pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks());
BLEService *svc = pServer->createService(SERVICE_UUID);
pCommandCharacteristic = svc->createCharacteristic(COMMAND_CHAR_UUID, BLECharacteristic::PROPERTY_WRITE);
pCommandCharacteristic->setCallbacks(new MyCommandCallbacks());
pStatusCharacteristic = svc->createCharacteristic(STATUS_CHAR_UUID, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY);
pStatusCharacteristic->addDescriptor(new BLE2902());
pDataCharacteristic = svc->createCharacteristic(DATA_CHAR_UUID, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_NOTIFY);
pDataCharacteristic->addDescriptor(new BLE2902());
svc->start();
BLEAdvertising *adv = BLEDevice::getAdvertising();
adv->addServiceUUID(SERVICE_UUID);
adv->setScanResponse(true);
BLEDevice::startAdvertising();
Serial.println("BLE Ready. Advertisingβ¦");
Serial.println("βββββββββββββββββββββββββββββββββββββββ\n");
Serial.println("Ready! Button Press Pattern:");
Serial.println(" β’ Double press β 10s cancel window");
Serial.println(" β’ Triple press in 10s β Cancel SOS");
Serial.println(" β’ No triple press β SOS triggered");
Serial.println(" β’ After SOS β 30s police alert window");
Serial.println(" β’ Triple press in 30s β Cancel police");
Serial.println(" β’ No triple press β Police alert sent\n");
sendStatusUpdate();
}
/* ------------------------- LOOP ------------------------- */
void loop() {
// Handle BLE connection state
if (!deviceConnected && oldDeviceConnected) {
delay(500);
pServer->startAdvertising();
Serial.println("BLE: Restarting advertising...");
oldDeviceConnected = deviceConnected;
}
if (deviceConnected && !oldDeviceConnected) {
oldDeviceConnected = deviceConnected;
sendStatusUpdate();
}
// Handle button presses (call frequently for responsiveness)
handleButton();
// Handle SOS countdown
if (sosActive && millis() - sosStartTime >= SOS_COUNTDOWN_MS) {
Serial.println("βββββββββββββββββββββββββββββββββββββββ");
Serial.println("β° SOS Countdown finished β Sending SMS");
Serial.println("βββββββββββββββββββββββββββββββββββββββ");
String msg = "π¨ SOS ALERT π¨\nUser requires help.\nTime: "
+ String(millis()/1000) + "s";
sendSMS(emergencyContact, msg);
sosActive = false;
setLED(false);
sendStatusUpdate();
}
// Periodic status updates (every 10 seconds when connected)
static unsigned long lastStatusUpdate = 0;
if (deviceConnected && (millis() - lastStatusUpdate > 10000)) {
updateBattery();
sendStatusUpdate();
lastStatusUpdate = millis();
}
// Debug: Show button state every 3 seconds (for troubleshooting)
static unsigned long lastButtonDebug = 0;
if (millis() - lastButtonDebug > 3000) {
int currentState = digitalRead(BUTTON_PIN);
Serial.print("[DEBUG] Button GPIO");
Serial.print(BUTTON_PIN);
Serial.print(" = ");
Serial.print(currentState == HIGH ? "HIGH" : "LOW");
Serial.print(" | BLE: ");
Serial.print(deviceConnected ? "CONNECTED" : "DISCONNECTED");
Serial.print(" | SOS: ");
Serial.println(sosActive ? "ACTIVE" : "INACTIVE");
lastButtonDebug = millis();
}
delay(10); // Small delay for button responsiveness
}