Accident Detection And Alert System

Hardware and Software Required ESP32 GPS Module MPU6050 Crash Sensor Vibration Sensor Database : MYSQL Block Diagram Algorithms This algorit...




Hardware and Software Required

  1. ESP32
  2. GPS Module
  3. MPU6050
  4. Crash Sensor
  5. Vibration Sensor
  6. Database : MYSQL

Block Diagram





Algorithms

This algorithm for the system is as follows:

Step 1: Start.

Step 2: Hardware initialization

Step 3: Read the data from sensor

Step 4: Make connection to internet network

Step 5: Send data to Database

Step 6: Display data in the web portal

Step 7: Repeat step 3

Step 8: End


Flow Charts









Arduino Code

#include <TinyGPS++.h>

#include <WiFi.h>

#include <HTTPClient.h>

#include "Wire.h"

#include <MPU6050_light.h>

MPU6050 mpu(Wire);

#define rxPin 16

#define txPin 17

long timer = 0;

int crash = 23;

int vib = 19;

int ledPin = 5;

int push_bottom = 15;

const char* ssid = "DESKTOP-5U0341V 2371"; //Wi-Fi SSID

const char* password = "11111111"; // your WiFi Password

const char* SERVER_NAME = "http://relfurn.com/gpsdata.php"; // your server 

String ESP32_API_KEY = "Ad5F10jkBM0"; // API key 

String vehicleno = "Ba1pa4887"; //user defined vehicle ID

HardwareSerial neogps(1);

TinyGPSPlus gps;

int val = digitalRead(crash);

int vibval = digitalRead(vib);

void setup()

{

  Serial.begin(115200);

  Serial.println("esp32 serial initialize");

  neogps.begin(9600, SERIAL_8N1, rxPin, txPin);

  Serial.println("neogps serial initialize");

  delay(1000);

  WiFi.begin(ssid, password);

  Serial.println("Connecting");

  while (WiFi.status() != WL_CONNECTED)

  {

    delay(500);

    Serial.print(".");

  }

  Serial.println("");

  Serial.print("Connected to WiFi network with IP Address: ");

  Serial.println(WiFi.localIP());

  Wire.begin();

  byte status = mpu.begin();

  Serial.print(F("MPU6050 status: "));

  Serial.println(status);

  while (status != 0) { }    // stop everything if could not connect to MPU6050

  Serial.println(F("Calculating offsets, do not move MPU6050"));

  delay(100);

  mpu.calcOffsets(true, true); // gyro and accelero

  Serial.println("Done!\n");

  pinMode(crash, INPUT);

  pinMode(vib, INPUT);

}

void loop()

{

  mpu.update();

  int val = digitalRead(crash);

  int vibval = digitalRead(vib);

  int Push_button_state = digitalRead(push_bottom);

  if (WiFi.status() == WL_CONNECTED)

  {

    if (millis() - timer > 1000) // print data every second

    {

      float x = mpu.getAccAngleX();

      float y = mpu.getAccAngleY();

// data should use by your own experiment. It's our raw data of MPU 6050

      if (x > 45.00 && y < 2.00 && vibval == 0 || x > 11.00 && y > 30.00 && vibval == 0 || x > 10.00 && y > -38.00 && vibval == 0)

      {

        Serial.println("accident detected by 1st condition");

        delay(30000);

        sendGpsToServer();

      }

      if (vibval == 0 && val == LOW)

      {

        Serial.println("accident detected by 2st condition");

        delay(30000);

        sendGpsToServer();

      }

    }

  }

}

//////////////////////////////////////////////////////////////////////////

int sendGpsToServer()

{

  while (neogps.available() > 0)

  {

    gps.encode(neogps.read());

    String latitude, longitude;

    latitude = String(gps.location.lat(), 6); // Latitude in degrees (double)

    longitude = String(gps.location.lng(), 6); // Longitude in degrees (double)

    HTTPClient http;

    //domain name with path

    http.begin(SERVER_NAME);

    if (latitude.toFloat() > 26 && longitude.toFloat() > 80)

    {

      //Specify content-type header

      http.addHeader("Content-Type", "application/x-www-form-urlencoded");

      //----------------------------------------------

      //HTTP POST request data

      String gps_data;

      gps_data = "api_key=" + ESP32_API_KEY;

      gps_data += "&latitude=" + latitude;

      gps_data += "&longitude=" + longitude;

      gps_data += "&vehicle_id=" + vehicleno;

      int httpResponseCode = http.POST(gps_data);

      String httpResponseString = http.getString();

      Serial.print("gps_data: ");

      Serial.println(gps_data);

      if (httpResponseCode > 0)

      {

        Serial.print("HTTP Response code: ");

        Serial.println(httpResponseCode);

        Serial.println(httpResponseString);

      }

      else

      {

        Serial.print("Error on HTTP request - Error code: ");

        Serial.println(httpResponseCode);

        Serial.println(httpResponseString);

      }

      Serial.println("accident detected ");

      for (;;); // used to terminate loop 

    }

    Serial.println(gps.satellites.value());

    http.end();

  }


Database Connection Code 

config.php

<?php 
define('DB_HOST', 'localhost'); 
define('DB_USERNAME', 'your database username'); 
define('DB_PASSWORD', 'your database password'); 
define('DB_NAME', 'your database name');

define('GOOGLE_MAP_API_KEY', 'ENTER_GOOGLE_MAP_API_KEY');
define('api key', 'api key');
define('http://mysite.com/gpsdata.php', 'api key');
date_default_timezone_set('Asia/Kathmandu'); $db = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME); if ($db->connect_errno) { echo "Connection to database is failed: ".$db->connect_error; exit(); } ?>
gpsdata.php
<?php 
require 'config.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
	$api_key = escape_data($_POST["api_key"]);
	if($api_key == 'Ad5F10jkBM0') {
		$latitude = escape_data($_POST["latitude"]);
		$longitude = escape_data($_POST["longitude"]);
		$vehicle_id = escape_data($_POST["vehicle_id"]);
		$sql = "INSERT INTO accident_location(vehicle_id,latitude,longitude,datetime) VALUES('".$vehicle_id."','".$latitude."','".$longitude."', current_timestamp())";
		if($db->query($sql) === FALSE)
			{ echo "Error: " . $sql . "<br>" . $db->error; }    
            function twopoints_on_earth($latitudeFrom, $longitudeFrom,
                                        $latitudeTo,  $longitudeTo)
          {
              $long1 = deg2rad($longitudeFrom);
              $long2 = deg2rad($longitudeTo);
              $lat1 = deg2rad($latitudeFrom);
              $lat2 = deg2rad($latitudeTo);
              //Haversine Formula
              $dlong = $long2 - $long1;
              $dlati = $lat2 - $lat1;
              $val = pow(sin($dlati/2),2)+cos($lat1)*cos($lat2)*pow(sin($dlong/2),2);
              $res = 2 * asin(sqrt($val));
              $radius = 3958.756;
              return ($res*$radius);
          }
	$distance = 999999999;
        $hospital = "";
        $hospital = "SELECT * FROM hospital_detail";
        $hresult = mysqli_query($db,$hospital);
        while($hrow = $hresult->fetch_assoc()) {
            $hlatitude = $hrow['latitude'];
            $hlongitude = $hrow['longitude'];
            $hospital_name = $hrow['name'];
            $update_distance = twopoints_on_earth( $latitude, $longitude,
                    $hlatitude,  $hlongitude);
            if($update_distance < $distance){
                $distance = $update_distance;
                $hospital = $hospital_name;
            }    
        }
        $hresult->free();
       	echo "Selected $hospital";
        date_default_timezone_set('Asia/Kathmandu');
        $date = date('m/d/Y h:i:s a', time());
		$user = "SELECT * FROM profile WHERE vehicle_id = '$vehicle_id'";
		$result = mysqli_query($db,$user);
        while($row = $result->fetch_assoc()) {
            $name = $row['name'];
            $family_email = $row['family_email'];
                $to = $family_email;
                 $subject = "Vehicle number '.$vehicle_id.' got accident.";
                 
                 $message = "<b>Hi sir/madam,</b><br></p>The vehicle no. $vehicle_id, registered with name $name accident at latitude $latitude and longitude $longitude.<br>
                 Accident date and time : $date<br> View map
                 <a href='https://www.google.com/maps/search/?api=1&query=".$latitude."%2C".$longitude."'>Accident Location</a></p><br>
                 <p>Nearest hospital from accident location is $hospital.</p></br><i>Thank You</i>";
                 $header = "From:your/organization email \r\n";
                 $header .= "MIME-Version: 1.0\r\n";
                 $header .= "Content-type: text/html\r\n";
                 $retval = mail ($to,$subject,$message,$header);
             if( $retval == true ) {
                echo "Message sent successfully...";
             }else {
                echo "Message could not be sent...";
             }
            }
            
		echo "OK. INSERT ID: ";
		echo $db->insert_id;
	}
	else
	{
		echo "Wrong API Key";
	}
}
else
{
	echo "No HTTP POST request found";
}

function escape_data($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
?>
Author: Sushil Bohaju 
Email : sb.bs014@gmail.com
for full document: https://www.docsity.com/en/accident-detection-and-rescue-management-using-esp32/7696888/
***For more inquiry you can direct email the author....***
https://www.researchgate.net/publication/353828146_Accident_Detection_and_Rescue_Management_System_NEPAL_COLLEGE_OF_INFORMATION_TECHNOLOGY

COMMENTS

BLOGGER: 1
Loading...
Name

Accident Alert,1,AI,2,Array,1,Aurdino,1,C,2,Computer Graphics,9,Data Science,3,Dataset,1,Decoratot,1,Django,1,ESP32,1,Fixed point/iteration method,1,Greater or smaller,1,html,1,Image Processing,1,JAVA,1,Javascript,22,Machine Learning,1,Matlab,3,Numerical Method,13,OOP,1,Other,3,PHP,1,Point operation,1,Python,11,Raspberry pi,1,Recommendation System,1,Regression,1,Reservation System,1,Robotics,1,Simulation,2,sine wave,1,String Handling Function,1,Web scrap,1,Webpage,1,
ltr
item
COMPUTER PROGRAMMING: Accident Detection And Alert System
Accident Detection And Alert System
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhyMaODIdgefMquFXHkOG2Q168jfTJgXYJ9ONOZw0CI-l9kolR_2QdWNxkr1cvFTEmaoOcD1VqMbfLJN0J0_kCFwXSv0zMGMj9hNzzPbBq8p5STucE_WjuPGTPekDvngmEz3XWqnNgUh4fG/w647-h516/ii.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhyMaODIdgefMquFXHkOG2Q168jfTJgXYJ9ONOZw0CI-l9kolR_2QdWNxkr1cvFTEmaoOcD1VqMbfLJN0J0_kCFwXSv0zMGMj9hNzzPbBq8p5STucE_WjuPGTPekDvngmEz3XWqnNgUh4fG/s72-w647-c-h516/ii.png
COMPUTER PROGRAMMING
https://computerprogram4ru.blogspot.com/2021/08/accident-detection-and-alert-system.html
https://computerprogram4ru.blogspot.com/
https://computerprogram4ru.blogspot.com/
https://computerprogram4ru.blogspot.com/2021/08/accident-detection-and-alert-system.html
true
8672391763020279633
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS CONTENT IS PREMIUM Please share to unlock Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy