#include <Wire.h>
#include <MPU6050.h>
#include <SoftwareSerial.h> // For GSM and GPS communication
#include <TinyGPS++.h> // For GPS processing
MPU6050 mpu;
TinyGPSPlus gps;
SoftwareSerial gsm(7, 8); // RX, TX for GSM module
SoftwareSerial gpsSerial(3, 4); // RX, TX for GPS module
const int BUZZER_PIN = 2;
const int ALCOHOL_SENSOR_PIN = A0;
const float TILT_THRESHOLD_X = 20.0; // 20-degree tilt threshold
const int ALCOHOL_THRESHOLD = 300; // Adjust based on calibration
void setup() {
Serial.begin(9600); // Initialize Serial for debugging
gsm.begin(9600); // Initialize GSM serial communication
gpsSerial.begin(9600); // Initialize GPS serial communication
Wire.begin();
mpu.initialize();
pinMode(BUZZER_PIN, OUTPUT);
if (!mpu.testConnection()) {
Serial.println("MPU6050 connection failed");
while (1); // Halt program if MPU6050 is not detected
}
gsm.println("AT+CMGF=1"); // Set GSM module to text mode
}
void loop() {
int16_t ax, ay, az;
mpu.getAcceleration(&ax, &ay, &az);
// Convert raw accelerometer data to g's
float x = ax / 16384.0;
float y = ay / 16384.0;
float z = az / 16384.0;
// Calculate the forward/backward tilt angle in degrees
float angle_x = atan2(x, sqrt(y * y + z * z)) * (180.0 / M_PI);
// Read alcohol level from the sensor
int alcohol_level = analogRead(ALCOHOL_SENSOR_PIN);
// Check if the tilt angle or alcohol level exceeds the threshold
if (angle_x > TILT_THRESHOLD_X || alcohol_level > ALCOHOL_THRESHOLD) {
digitalWrite(BUZZER_PIN, HIGH); // Activate buzzer
// Wait for a valid GPS location
while (gpsSerial.available() > 0) {
gps.encode(gpsSerial.read());
if (gps.location.isUpdated()) {
// Prepare the SMS message
String latitude = String(gps.location.lat(), 6);
String longitude = String(gps.location.lng(), 6);
String message = "ALERT! Driver in danger. Location: " + latitude + ", " + longitude;
// Send SMS with GPS location
gsm.println("AT+CMGS=\"+91XXXXXXXXXX\""); // Replace with recipient's phone number
gsm.print(message);
gsm.write(26); // ASCII code for Ctrl+Z to send the SMS
}
}
} else {
digitalWrite(BUZZER_PIN, LOW); // Deactivate buzzer if conditions are normal
}
delay(100); // Short delay for sensor reading stability
}