#define BLYNK_PRINT Serial
#define BLYNK_TEMPLATE_ID "TMPL6liBVvQMC"
#define BLYNK_TEMPLATE_NAME "Incident Alert"
#define BLYNK_AUTH_TOKEN "qJskr9rGY8kNaU9OCHFgg0pHjji6CxG9"
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 32 // Reduced screen height to save memory
#define OLED_RESET -1
#define SCREEN_ADDRESS 0x3C
#include <BlynkSimpleEsp32.h>
#include <Wire.h>
#include <MPU6050.h>
#include <WiFi.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
char ssid[] = "Wokwi-GUEST";
char pass[] = "";
char auth[] = BLYNK_AUTH_TOKEN;
BlynkTimer timer;
MPU6050 mpu;
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
const float fallThreshold = 2.0; //threshold for fall detection
void connectWiFi() {
Serial.print(F("Connecting to WiFi..."));
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(F("."));
}
Serial.println(F("Connected to WiFi"));
}
void Initializedisplay() {
if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
Serial.println(F("SSD1306 allocation failed"));
while (true);
}
display.display();
delay(1000);
display.clearDisplay();
}
///////////////////////////////////detectFall Start////////////////////////////////////////////////
void detectFall() {
int16_t ax, ay, az;
mpu.getAcceleration(&ax, &ay, &az);
float accX = ax / 11334.0; //value for ±2g range
// Send to virtual pin V1
Blynk.virtualWrite(V1, accX);
if (accX > fallThreshold) {
sendMQTTAlert();
}
}
void sendMQTTAlert() {
Blynk.logEvent("incident_alert", "Fall detected!");
Serial.println(F("Fall detected! Alert sent to Blynk."));
// Display alert message
display.clearDisplay();
display.setTextSize(1); // Normal 1:1 pixel scale
display.setTextColor(SSD1306_WHITE); // Draw white text
display.setCursor(0, 0); // Start at top-left corner
display.println(F("Incident Alert Sent!"));
display.display(); // Show on OLED
delay(1000); // Reduced delay
display.clearDisplay(); // Clear the screen
display.display(); // Apply the changes
}
//////////////////////////detectFall end///////////////////////////////////////
void setup() {
Serial.begin(9600);
Wire.begin();
mpu.initialize();
if (!mpu.testConnection()) {
Serial.println(F("MPU6050 connection failed!"));
while (true); // Stop execution if sensor fails
}
Initializedisplay();
connectWiFi();
Blynk.begin(auth, ssid, pass);
timer.setInterval(1000L, detectFall);
}
void loop() {
Blynk.run();
timer.run();
if (WiFi.status() != WL_CONNECTED) {
Serial.println(F("WiFi disconnected! Trying to reconnect..."));
connectWiFi();
}
}