IoT-Based Accident Detection and Health Monitoring System Using Raspberry Pi with GSM, GPS and Camera Integration

IoT Accident Detection & Health Monitoring – Raspberry Pi | GPS + GSM + Camera
🚨 IoT Safety System

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.

Raspberry Pi MPU6050 GPS + GSM BMP388 Picamera2 OLED SSD1306 Solar Powered

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.

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.

System Block Diagram

Full architecture from power supply through sensors, Raspberry Pi, and output modules to the cloud.

IoT Accident Detection & Health Monitoring — System Architecture
☀️ Solar Panel Charging Source Buck Converter DC-DC · 5V 10A 🔋 3S LiPo 11.1V Battery 5V Power Raspberry Pi Central Processing Unit GPIO 4 → Heart Pulse I2C → MPU6050 I2C → BMP388 I2C → OLED UART → GPS / GSM MPU6050 Accel + Gyro (I2C) BMP388 Temp + Pressure (I2C) ❤️ Heart Pulse Digital GPIO 4 📍 GPS Module UART Real-Time Coords 📱 GSM Module AT Commands · SMS 📷 Pi Camera Picamera2 · Evidence 🖨️ OLED SSD1306 I2C · 128×64 Display ☁️ Cloud / Local Log Firebase · ThingsBoard · AWS IoT · incident_log.txt MQTT / HTTP LEGEND I2C / UART Signal GPIO / GSM Signal Power Supply Cloud / Log (Optional)

How the System Works

1

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
2

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
3

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
4

Data Logging & Cloud Sync

  • Incident written to local incident_log.txt with timestamp
  • Optional MQTT publish to Firebase, ThingsBoard, or AWS IoT Core
  • All sensor data available for post-event forensic analysis
📩 Professional SMS Format 🚨 ACCIDENT ALERT 🚨
Vehicle ID: V102 | Time: 14:32:10
Location: https://maps.google.com/?q=12.9716,77.5946
Heart Status: Abnormal — Immediate assistance required.

Hardware Components

🖥️
Raspberry Pi
Main controller (any model)
🧭
MPU6050
6-axis IMU, I2C 0x68
🌡️
BMP388
Temperature + pressure
❤️
Heart Pulse Sensor
GPIO 4 digital input
📍
GPS Module
UART real-time coords
📱
GSM Module
AT commands, /dev/ttyS0
📷
Pi Camera Module
Picamera2 library
🖨️
OLED SSD1306
I2C 0x3C, 128×64
🔋
3S LiPo Battery
11.1V backup power
☀️
Solar Panel
Primary charging source
DC-DC Buck Converter
5V 10A regulated output
🔌
Capacitors
Power stabilization

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.

accident_monitor.py
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()

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.

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

Applications

🚗 Smart car accident detection
🏍️ Two-wheeler safety monitoring
🚛 Fleet vehicle tracking
🚑 Ambulance smart automation
👴 Elderly travel health monitoring
🏭 Industrial vehicle safety
💊 IoT medical emergency systems
🔒 Smart transportation security

Built with ❤️ for safer roads · MakeMindz · Raspberry Pi & IoT Project Guides

Comments

try for free