IoT-Based Accident Detection and Health Monitoring System Using Raspberry Pi with GSM, GPS and Camera Integration
Accident Detection & Health Monitoring System
A complete IoT-based smart vehicle safety platform using Raspberry Pi — integrating motion sensing, biometric monitoring, GPS tracking, GSM SMS alerts, and camera surveillance.
Project Overview
Complete Smart Vehicle Safety System
This project is a life-saving IoT platform that fuses data from multiple sensors to detect accidents and health anomalies in real time. When triggered, it automatically captures image evidence, fetches GPS coordinates, sends SMS alerts via GSM, and logs all incident data — all running on a Raspberry Pi.
System Architecture
Core Subsystems
Core Controller
Raspberry Pi acts as the central processing unit, orchestrating all sensors, communication, and display interfaces.
GPS Location Tracking
UART-based GPS module provides real-time latitude/longitude coordinates for emergency alert messages.
GSM Emergency Alerts
AT command-based SMS dispatch sends a clickable Google Maps link directly to emergency contacts.
Camera Surveillance
Picamera2 captures incident images for insurance verification, emergency assessment, and documentation.
Health Monitoring
Heart pulse sensor + BMP388 monitor heart rate, body temperature, pressure, and SpO2 continuously.
Motion Detection
MPU6050 6-axis IMU detects sudden acceleration, tilt angle, and rapid deceleration events.
OLED Display
SSD1306 I2C OLED shows live health readings, GPS signal status, and emergency confirmations.
Solar + LiPo Power
3S LiPo battery with solar panel charging and DC-DC buck converter ensures continuous autonomous operation.
Circuit Diagram
System Block Diagram
Full architecture from power supply through sensors, Raspberry Pi, and output modules to the cloud.
Working Logic
How the System Works
Continuous Sensor Monitoring Loop
- MPU6050 reads acceleration (X/Y/Z) and gyroscope tilt data every cycle
- Heart pulse sensor checks for irregular heartbeat via GPIO 4
- BMP388 reads ambient temperature and pressure
- GPS module streams real-time latitude/longitude via UART
Accident Detection Algorithm
- Computes 3D acceleration magnitude: √(x² + y² + z²)
- If magnitude exceeds threshold (~20 m/s²) → accident flagged
- Roll angle > 60° or sudden deceleration spike also triggers alert
- 3-reading confirmation debounce prevents false positives
Emergency Event Execution
- Camera captures JPEG image evidence instantly
- GPS coordinates fetched with timeout handling
- GSM sends SMS with Google Maps link to emergency contacts
- OLED displays "EMERGENCY ALERT" confirmation message
Data Logging & Cloud Sync
- Incident written to local
incident_log.txtwith timestamp - Optional MQTT publish to Firebase, ThingsBoard, or AWS IoT Core
- All sensor data available for post-event forensic analysis
Vehicle ID: V102 | Time: 14:32:10
Location: https://maps.google.com/?q=12.9716,77.5946
Heart Status: Abnormal — Immediate assistance required.
Bill of Materials
Hardware Components
Python Source Code
Main Application Script
Upload and run this script on your Raspberry Pi. Ensure all libraries are installed via pip: picamera2, gps3, smbus2, bmp388, mpu6050, luma.oled.
import time import RPi.GPIO as GPIO import serial import picamera2 from gps3 import gps3 from smbus2 import SMBus from bmp388 import BMP388 from mpu6050 import mpu6050 from luma.core.interface.serial import i2c from luma.oled.device import ssd1306 from luma.core.render import canvas from PIL import ImageFont # ── GPIO Setup ────────────────────────────── GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) HEART_PULSE_PIN = 4 GPIO.setup(HEART_PULSE_PIN, GPIO.IN) # Set once, outside loop # ── GPS ───────────────────────────────────── gps_socket = gps3.GPSDSocket() data_stream = gps3.DataStream() gps_socket.connect() gps_socket.watch() # ── GSM Serial ────────────────────────────── gsm_serial = serial.Serial("/dev/ttyS0", baudrate=9600, timeout=1) # ── Camera ────────────────────────────────── camera = picamera2.Picamera2() camera.configure(camera.create_still_configuration()) # ── I2C Sensors ───────────────────────────── i2c_bus = SMBus(1) bmp388 = BMP388(i2c_bus) mpu = mpu6050(0x68) # ── OLED Display ──────────────────────────── serial_if = i2c(port=1, address=0x3C) oled = ssd1306(serial_if) font = ImageFont.load_default() # ── Helpers ───────────────────────────────── def get_gps_data(timeout=5): start = time.time() try: for new_data in gps_socket: if time.time() - start > timeout: return None, None if new_data: data_stream.unpack(new_data) lat = data_stream.TPV['lat'] lon = data_stream.TPV['lon'] if lat != 'n/a': return lat, lon except Exception as e: print(f"GPS error: {e}") return None, None def send_sms(message, phone_number): try: gsm_serial.write(b'AT+CMGF=1\r') time.sleep(1) gsm_serial.write(f'AT+CMGS="{phone_number}"\r'.encode()) time.sleep(1) gsm_serial.write(f"{message}\x1A".encode()) time.sleep(3) except Exception as e: print(f"GSM error: {e}") def log_incident(lat, lon, accel_mag): with open("incident_log.txt", "a") as f: f.write(f"{time.ctime()} | {lat}, {lon} | accel={accel_mag:.2f}\n") # ── Main Loop ─────────────────────────────── if __name__ == "__main__": confirm_count = 0 try: while True: # Read sensors accel_data = mpu.get_accel_data() gyro_data = mpu.get_gyro_data() temperature, pressure = bmp388.read_temperature_and_pressure() heart_pulse = GPIO.input(HEART_PULSE_PIN) lat, lon = get_gps_data() # Accident detection — 3D magnitude accel_mag = (accel_data['x']**2 + accel_data['y']**2 + accel_data['z']**2) ** 0.5 accident_detected = accel_mag > 20 or heart_pulse == 1 if accident_detected: confirm_count += 1 else: confirm_count = 0 # 3-reading confirmation debounce if confirm_count >= 3: camera.start_and_capture_file("incident.jpg") msg = (f"🚨 ACCIDENT ALERT 🚨\n" f"Time: {time.ctime()}\n" f"Location: https://maps.google.com/?q={lat},{lon}\n" f"Heart: {'Abnormal' if heart_pulse else 'OK'}\n" f"Immediate assistance required.") send_sms(msg, "+1234567890") log_incident(lat, lon, accel_mag) confirm_count = 0 # OLED Display with canvas(oled) as draw: draw.text((0, 0), f"Temp: {temperature:.1f} C", font=font, fill=255) draw.text((0, 12), f"Pres: {pressure:.0f} Pa", font=font, fill=255) draw.text((0, 24), f"Lat: {lat}", font=font, fill=255) draw.text((0, 36), f"Lon: {lon}", font=font, fill=255) draw.text((0, 48), f"Pulse: {heart_pulse}", font=font, fill=255) time.sleep(5) except KeyboardInterrupt: print("Exiting…") finally: GPIO.cleanup()
Professional Upgrades
Code Improvement Suggestions
Fix GPS Timeout Handling
The original get_gps_data() can block indefinitely. The improved version adds a configurable timeout (default 5s) so the main loop never stalls.
Fix GPIO Init Outside Loop
Move GPIO.setup(HEART_PULSE_PIN, GPIO.IN) outside the while loop to avoid re-initialization overhead every cycle.
Fix Debounce Confirmation
Use a confirm_count counter requiring 3 consecutive positive readings before dispatching an SMS — eliminates false alarms from vibration spikes.
Add Local Incident Log
Append each event to incident_log.txt with timestamp, GPS coords, and acceleration magnitude for offline forensic analysis.
Add Roll Angle Detection
Supplement magnitude threshold with roll angle > 60° check using gyroscope data — catches vehicle rollovers that may not spike linear acceleration.
Add Google Maps SMS Link
Format GPS coordinates as a clickable URL: maps.google.com/?q=lat,lon — responders can navigate directly from the SMS message.
Future Enhancements
Cloud-Based Data Logging
Upgrade to real-time cloud dashboards for remote fleet monitoring, incident replay, and predictive analytics.
🔥 Firebase
- Install firebase-admin SDK
- Push JSON incident data
- Real-time web dashboard
📊 ThingsBoard
- MQTT protocol integration
- Live vehicle dashboard
- Alert rule engine
☁️ AWS IoT Core
- MQTT topic publishing
- Lambda alert triggers
- S3 image archiving
📱 Mobile App
- Flutter app with Firebase
- Real-time GPS tracking
- Push notifications
Real-World Use Cases
Applications
More Projects
Comments
Post a Comment