#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>
Adafruit_MPU6050 mpu;
// Pin Definitions based on your wiring
const int BUZZER_PIN = 25;
const int LED_PIN = 26;
const int BUTTON_PIN = 4;
// Threshold for accident detection (G-force magnitude)
// In simulation, you might need to move sliders quickly to trigger this
const float ACCEL_THRESHOLD = 25.0;
void setup() {
Serial.begin(115200);
// Initialize Pins
pinMode(BUZZER_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP); // Button connects to GND when pressed
// Initialize MPU6050
if (!mpu.begin()) {
Serial.println("Failed to find MPU6050 chip - Check your SDA/SCL wiring!");
while (1) { delay(10); }
}
Serial.println("MPU6050 Found! Smart Helmet System is ACTIVE.");
}
void loop() {
sensors_event_t a, g, temp;
mpu.getEvent(&a, &g, &temp);
// Calculate the Resultant Vector (Magnitude) of Acceleration
// Formula: sqrt(ax^2 + ay^2 + az^2)
float magnitude = sqrt(a.acceleration.x * a.acceleration.x +
a.acceleration.y * a.acceleration.y +
a.acceleration.z * a.acceleration.z);
// Check if force exceeds the threshold
if (magnitude > ACCEL_THRESHOLD) {
handleAccident();
}
delay(100); // Small delay for stability
}
void handleAccident() {
Serial.println("\n--- ALERT: SUDDEN IMPACT DETECTED! ---");
bool cancelled = false;
// 10-second grace period (100 cycles of 100ms)
for (int i = 0; i < 100; i++) {
// Blink LED and Beep Buzzer
digitalWrite(BUZZER_PIN, HIGH);
digitalWrite(LED_PIN, HIGH);
delay(50);
digitalWrite(BUZZER_PIN, LOW);
digitalWrite(LED_PIN, LOW);
delay(50);
// If rider presses the button (D4 goes LOW), cancel the alert
if (digitalRead(BUTTON_PIN) == LOW) {
cancelled = true;
break;
}
}
if (cancelled) {
Serial.println("SAFE: Rider cancelled the alert.");
digitalWrite(BUZZER_PIN, LOW);
digitalWrite(LED_PIN, LOW);
} else {
sendEmergencyAlert();
}
}
void sendEmergencyAlert() {
Serial.println("CRITICAL: NO RESPONSE FROM RIDER.");
Serial.println("GSM: Initializing SIM800L...");
Serial.println("GSM: Sending Location Data & SMS to Emergency Contact...");
Serial.println("GSM: Placing Call to +91XXXXXXXXXX...");
// Solid alert to help rescuers find the helmet
digitalWrite(BUZZER_PIN, HIGH);
digitalWrite(LED_PIN, HIGH);
}