#include <Wire.h>
#include <MPU6050.h>
#include <SoftwareSerial.h> // For GPS
// Pins
const int buttonPin = A2; // Panic button
const int ledPin = 5; // LED (vibration substitute)
const int hrPotPin = A1; // Potentiometer for heart rate simulation
// GPS Setup
SoftwareSerial gpsSerial(3, 4); // RX, TX (connect to GPS TX/RX)
// IMU
MPU6050 mpu;
void setup() {
Serial.begin(9600);
Wire.begin();
// Initialize components
mpu.initialize();
gpsSerial.begin(9600); // GPS baud rate
// Configure pins
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
pinMode(hrPotPin, INPUT);
}
void loop() {
// 1. Read sensors
int16_t ax, ay, az;
mpu.getAcceleration(&ax, &ay, &az);
bool buttonPressed = (digitalRead(buttonPin) == LOW);
int heartRate = map(analogRead(hrPotPin), 0, 1023, 40, 180);
// 2. Detect anomalies
if (abs(ax) > 15000 || abs(ay) > 15000) {
triggerAlert("MOTION ALERT!");
}
if (buttonPressed) {
triggerAlert("PANIC BUTTON PRESSED!");
}
if (heartRate > 120) {
triggerAlert("HIGH HEART RATE: " + String(heartRate) + " BPM!");
}
// 3. Check GPS (non-blocking)
if (gpsSerial.available()) {
String gpsData = gpsSerial.readStringUntil('\n');
if (gpsData.startsWith("$GPRMC")) {
Serial.println("GPS: " + gpsData);
}
}
delay(100);
}
void triggerAlert(String msg) {
Serial.println(msg);
// GPS fix
if (gpsSerial.available()) {
String gpsData = gpsSerial.readStringUntil('\n');
if (gpsData.startsWith("$GPRMC")) {
Serial.println("LOCATION: " + gpsData);
}
} else {
Serial.println("LOCATION: 37.7749°N, 122.4194°W"); // Fallback mock
}
// Vibration/LED Feedback
for (int i = 0; i < 3; i++) {
digitalWrite(ledPin, HIGH);
delay(300);
digitalWrite(ledPin, LOW);
delay(300);
}
}