# Dynamic Car Speed Controller (DSC) & Danger Zone Detection System

An embedded vehicular speed regulation and geospatial accident prevention system integrating an ESP32 vehicle controller with an Android supervisory navigation client.

**Academic Affiliation**: School of Electrical & Electronics Engineering (SEEE), VIT Bhopal University  
**Supervision**: Dr. Thiyagu Priyadharsan (Assistant Professor, SEEE)  
**Authors**: Sandeepan (23BAC10024), Omkar Ajitkumar Phadatare (23BAC10005), Yug Pareek (23BAC10022)  

---

## Quick Navigation

- [Abstract & Project Summary](#abstract--project-summary)
- [Research Problem & Objectives](#research-problem--objectives)
- [Hardware Prototype & Circuit Schematics](#hardware-prototype--circuit-schematics)
- [Mobile Supervisory Application & User Interface](#mobile-supervisory-application--user-interface)
- [System Architecture](#system-architecture)
- [Research Methodology](#research-methodology)
- [Repository Structure](#repository-structure)
- [Jupyter Research Notebooks](#jupyter-research-notebooks)
- [Geospatial Hotspot Dataset](#geospatial-hotspot-dataset)
- [Experimental Results & Key Findings](#experimental-results--key-findings)
- [Additional Experimental Figures](#additional-experimental-figures)
- [How to Reproduce the Research](#how-to-reproduce-the-research)
- [Running the Mobile Application](#running-the-mobile-application)
- [Hardware Setup & Firmware Flashing](#hardware-setup--firmware-flashing)
- [Technology Stack](#technology-stack)
- [Limitations & Future Research](#limitations--future-research)
- [Academic References](#academic-references)
- [Citation & Contact Information](#citation--contact-information)

---

## Abstract & Project Summary

Vehicular overspeeding remains one of the primary contributors to fatal traffic collisions worldwide. Conventional speed-limiting devices and passive roadside signage rely heavily on driver attention and compliance, offering little adaptability to localized road hazards, blind curves, or abrupt obstacles.

This research presents the **Dynamic Car Speed Controller (DSC)**, a cyber-physical vehicular safety framework combining **real-time geospatial geofencing**, **closed-loop electronic motor throttling**, and **multi-modal driver alerts**. The system comprises:
1. **Vehicle Hardware Prototype**: An ESP32 dual-core microcontroller interfaced with a U-blox NEO-6M GPS receiver, an HC-SR04 ultrasonic obstacle sensor, an L298N dual H-bridge motor driver, and an active piezo horn.
2. **Mobile Supervisory Client**: A native Android application built with Kotlin and Jetpack Compose that communicates with the vehicle over Bluetooth Serial (SPP) and local Wi-Fi, providing Google Maps navigation, dynamic route calculation, real-time speed monitoring, and native Text-to-Speech (TTS) auditory warnings.

Experimental evaluations conducted across simulated highway and urban scenarios demonstrated an average geofence boundary detection latency of **$42.5\text{ ms}$**, an autonomous speed reduction of **$63.2\%$** in high-risk accident hotspots, and immediate collision avoidance stopping within **$28\text{ ms}$** upon detecting front obstacles.

---

## Research Problem & Objectives

### The Problem
* **Human-Factor Speed Violations**: Drivers frequently fail to observe speed limits due to inattention, fatigue, or deliberate non-compliance.
* **Static Infrastructure Limitations**: Traditional speed limit signs and radar traps are static and fail to adjust dynamically to road geometry hazards, weather, or real-time obstacle occurrences.
* **Lack of Direct Vehicle Intervention**: Commercial navigation systems alert drivers passively via visual notifications, but lack bidirectional coupling with vehicle actuators to physically enforce safe operating speeds when a driver fails to react.

### Research Objectives
1. **Geofenced Danger Zone Enforcement**: Establish a high-accuracy geofencing model ($500\text{m}$ radius) cross-referencing live vehicle coordinates against documented accident hotspots across major transport corridors.
2. **Autonomous Speed Regulation**: Modulate motor Pulse Width Modulation (PWM) duty cycles ($100\% \to 31\% \to 0\%$) to automatically decelerate the vehicle when overspeeding occurs within high-hazard zones.
3. **Multi-Modal Alert Synchronization**: Provide simultaneous on-screen visual banners, high-frequency audible piezo beeps, and natural-language Text-to-Speech (TTS) warnings through device speakers to eliminate driver visual distraction.
4. **Collision Avoidance Redundancy**: Implement independent onboard ultrasonic proximity detection capable of triggering zero-power emergency stops ($<35\text{cm}$) independent of mobile connectivity.

---

## Hardware Prototype & Circuit Schematics

The physical implementation couples digital microcontroller logic with high-current motor drive rails, sensor telemetry interfaces, and multi-modal audio alarms.

### Physical Vehicle Prototype
![Working Model of Vehicle Prototype](hardware/car.jpg)
*Figure 1: Fully assembled four-wheel robotic test vehicle featuring the elevated NEO-6M GPS patch antenna, ESP32 microcontroller, L298N motor driver, HC-SR04 ultrasonic transducer, and dual-cell lithium-ion battery pack.*

### Circuit Wiring Schematic & Pinout
![Circuit Pinout and Hardware Interconnects](hardware/pin_diagram.jpg)
*Figure 2: Complete hardware interconnect schematic showing signal isolation between the ESP32 DevKit, U-blox NEO-6M GPS UART pins, L298N dual H-bridge motor driver, HC-SR04 ultrasonic sensor, and 5V active piezo buzzer.*

---

## Mobile Supervisory Application & User Interface

The supervisory mobile application provides the driver interface, real-time telemetry processing, geospatial geofencing evaluation, and auditory voice synthesis.

| Application Screen | Interface Description | Technical Function |
|---|---|---|
| ![Welcome Screen](screen_images/welcome_screen.jpg) | **Figure 3: Startup & Authentication** | User authentication via Firebase, device permission checks (Location, Bluetooth, Network), and initial hardware pairing wizard. |
| ![Home Dashboard](screen_images/home_screen.jpg) | **Figure 4: Main Supervisory Dashboard** | Real-time vehicle speed HUD (km/h), active telemetry source indicator (Bluetooth SPP / Wi-Fi), and trip metrics summary. |
| ![Navigation Route](screen_images/nav_route.jpg) | **Figure 5: Route Planning & Hotspot Overlay** | Dynamic turn-by-turn routing via OpenRouteService API with color-coded 500-meter circular geofences overlaid across the planned route. |
| ![Danger Zone Alert](screen_images/danger_zone.jpg) | **Figure 6: High-Risk Geofence Proximity Warning** | Active emergency warning card triggered within 500m of an accident hotspot, showing safe speed thresholds and triggering concurrent voice synthesis. |
| ![Active Navigation](screen_images/navigration.jpg) | **Figure 7: Live Turn-by-Turn Navigation Map** | Full-screen interactive Google Map tracking real-time vehicle position, heading azimuth, remaining distance, and proximity to upcoming hazard clusters. |

---

## System Architecture

The DSC system operates as a distributed cyber-physical architecture divided between the **Vehicle Embedded Subsystem** and the **Mobile Supervisory Application**:

```mermaid
flowchart TD
    subgraph Hardware["Onboard Vehicle Hardware Subsystem (ESP32)"]
        GPS["NEO-6M GPS Receiver"] -->|"UART2 (Pins 16/17)"| ESP32["ESP32 Dual-Core MCU (240 MHz)"]
        US["HC-SR04 Ultrasonic Sensor"] -->|"GPIO (Echo 12 / Trig 13)"| ESP32
        ESP32 -->|"PWM Speed Control (Pins 14/32)"| L298N["L298N Dual H-Bridge Driver"]
        ESP32 -->|"Digital Out (Pin 18)"| Buzzer["5V Active Piezo Buzzer"]
        L298N -->|"Dual H-Bridge Power Rails"| Motors["4x DC Geared Motors"]
    end

    subgraph Comm["Wireless Telemetry Link"]
        ESP32 <-->|"Bluetooth SPP / Wi-Fi AP (JSON Telemetry 500ms)"| MobileComm["BluetoothCarManager / WifiCarManager"]
    end

    subgraph Mobile["Mobile Supervisory System (Android)"]
        MobileComm --> LiveSpeed["Real-Time Speed & Telemetry State"]
        Hotspots[("DangerZonesData (61 Hotspots)")] --> Geofence["Haversine Geofencing Engine"]
        LiveSpeed --> Geofence
        Geofence -->|"Target Speed / Alert Flag"| MobileComm
        Geofence -->|"Hazard Overlay (500m Circles)"| UI["GoogleMap & Speed HUD (Compose UI)"]
        Geofence -->|"Queue Flush Emergency Alert"| TTS["VoiceAlertManager (Android TTS)"]
    end
```

For complete electrical schematics, pin mappings, and firmware architecture, see [`docs/architecture.md`](docs/architecture.md).

---

## Research Methodology

The operational pipeline follows a deterministic four-stage sequence:

```mermaid
flowchart LR
    GPS["1. GPS Coordinates & Speed"] --> Geofence["2. Haversine Distance Calculation"]
    Hotspots[("Accident Registry")] --> Geofence
    Geofence --> Threshold{"3. Speed > Safe Limit?"}
    Threshold -->|"Yes"| Throttle["4. PWM Throttling (31% - 65%)"]
    Threshold -->|"Yes"| Warning["4. Multi-Modal Audio & Voice Alerts"]
    Threshold -->|"No"| Cruising["Normal Cruising (100% PWM)"]
    US["Ultrasonic Sensor (< 35cm)"] -->|"Emergency Override"| Stop["Emergency Stop (0% PWM)"]
```

### 1. Data Ingestion & Geocoding
Vehicle coordinates $(\phi_{\text{car}}, \lambda_{\text{car}})$ and ground velocity $v_{\text{car}}$ are acquired at $2\text{ Hz}$ from the NEO-6M GPS module and parsed using `TinyGPS++`.

### 2. Haversine Distance Geofencing
The spherical separation $d$ between the vehicle and each accident hotspot $(\phi_i, \lambda_i)$ is evaluated using the Haversine formula:
$$\Delta \phi = \phi_i - \phi_{\text{car}}, \quad \Delta \lambda = \lambda_i - \lambda_{\text{car}}$$
$$a = \sin^2\left(\frac{\Delta \phi}{2}\right) + \cos(\phi_{\text{car}})\cos(\phi_i)\sin^2\left(\frac{\Delta \lambda}{2}\right)$$
$$d = 2R \cdot \text{atan2}\left(\sqrt{a}, \sqrt{1 - a}\right) \quad (R = 6,371,000\text{ m})$$

A geofence activation condition triggers when $d \le 500.0\text{ meters}$.

### 3. Closed-Loop Throttle Modulation
When inside an active geofence, vehicle speed is compared against the localized regulatory threshold ($40\text{ km/h}$ for High Risk, $50\text{ km/h}$ for Medium Risk). Actuation commands are dispatched to the L298N motor driver:

$$D_{\text{PWM}} = \begin{cases} 0, & \text{if } d_{\text{obstacle}} < 35\text{ cm} \quad (\text{Collision Override}) \\ 80\ (31.4\%), & \text{if } \text{InHighZone} \land v_{\text{current}} \ge 45\text{ km/h} \\ 166\ (65.1\%), & \text{if } \text{InMediumZone} \land v_{\text{current}} \ge 50\text{ km/h} \\ 255\ (100.0\%), & \text{otherwise (Normal Cruising)} \end{cases}$$

### 4. Multi-Modal Feedback
Simultaneously, the mobile client issues auditory alerts using Android's native Text-to-Speech queue (`QUEUE_FLUSH` for emergency alerts) while the ESP32 pulses an $85\text{dB}$ onboard piezo horn.

For mathematical derivations and latency proofs, see [`docs/methodology.md`](docs/methodology.md).

---

## Repository Structure

```
.
├── Project_Report.docx                     # Complete academic project exhibition report
├── README.md                               # Root comprehensive research overview
├── CITATION.cff                            # Academic citation metadata
├── CONTRIBUTING.md                         # Development and contribution guidelines
├── LICENSE                                 # Project license (MIT)
├── .env.example                            # Configuration environment template
├── requirements.txt                        # Python dependencies for research reproduction
├── .gitignore                              # Git ignore rules for Android, Python, and build artifacts
│
├── hardware/                               # Embedded Hardware Subsystem
│   ├── README.md                           # Hardware bill of materials, circuit wiring & pinouts
│   ├── car.jpg                             # High-resolution vehicle prototype photograph
│   ├── pin_diagram.jpg                     # Detailed circuit wiring and pinout schematic
│   └── esp32_car_tracker/
│       └── esp32_car_tracker.ino           # ESP32 C++ firmware (GPS, Motor Driver, BT/Wi-Fi)
│
├── screen_images/                          # Mobile Application Interface Artifacts
│   ├── welcome_screen.jpg                  # App onboarding and authentication screen
│   ├── home_screen.jpg                     # Main dashboard and speed HUD interface
│   ├── nav_route.jpg                       # Route selection with geofenced accident hotspots
│   ├── danger_zone.jpg                     # Proximity alert card and active warning banner
│   └── navigration.jpg                     # Live turn-by-turn navigation map
│
├── app/                                    # Android Mobile Application (Kotlin + Jetpack Compose)
│   ├── build.gradle.kts                    # App-level Gradle build configuration
│   └── src/main/
│       ├── AndroidManifest.xml             # Permissions (Location, Bluetooth, Network)
│       └── java/np/com/bimalkafle/firebaseauthdemoapp/
│           ├── MainActivity.kt             # Single activity entry point
│           ├── data/
│           │   ├── hardware/               # Hardware telemetry managers (Bluetooth SPP, Wi-Fi)
│           │   │   ├── BluetoothCarManager.kt
│           │   │   ├── CarTelemetry.kt
│           │   │   └── WifiCarManager.kt
│           │   ├── model/                  # Data models (DangerZone, RiskLevel, RouteModels)
│           │   │   ├── DangerZone.kt
│           │   │   └── RouteModels.kt
│           │   └── repository/             # Centralized hotspot repository & route client
│           │       ├── DangerZonesData.kt
│           │       └── RouteRepository.kt
│           ├── util/
│           │   └── VoiceAlertManager.kt    # Text-to-Speech speaker audio alert manager
│           └── ui/
│               ├── navigation/             # Type-safe screen routing & NavHost
│               │   ├── MyAppNavigation.kt
│               │   └── Screen.kt
│               ├── screens/                # Composable screens (Auth, Home, Profile, Startup)
│               │   ├── auth/
│               │   ├── home/
│               │   ├── profile/
│               │   └── startup/
│               └── theme/                  # Material 3 colors, typography, and themes
│
├── data/                                   # Research Datasets
│   ├── README.md                           # Dataset documentation, schema, and provenance
│   ├── raw/
│   │   └── raw_accident_hotspots_registry.csv # Baseline accident coordinates (61 hotspots)
│   ├── processed/
│   │   └── accident_danger_zones.csv       # Geocoded danger zones with localized speed limits
│   └── sample/
│       └── sample_danger_zones.csv         # 10-zone subset for lightweight verification
│
├── notebooks/                              # Jupyter Research Notebooks
│   ├── README.md                           # Notebook index, dependencies, and execution guide
│   ├── 01_danger_zone_geospatial_analysis.ipynb
│   └── 02_dynamic_speed_controller_simulation.ipynb
│
├── results/                                # Research Findings & Empirical Results
│   ├── README.md                           # Results summary and quantitative evaluation
│   ├── figures/                            # Photographic evidence and architectural diagrams
│   │   ├── README.md                       # Figure catalog and technical captions
│   │   ├── fig1_dsc_system_architecture.jpeg
│   │   ├── fig2_working_model_car.jpeg
│   │   ├── fig3_car_chassis_hardware.jpeg
│   │   ├── fig4_car_model_assembly.jpeg
│   │   ├── fig5_sensor_ultrasonic_operation.jpeg
│   │   ├── fig6_sensor_telemetry_serial_logs.jpeg
│   │   ├── fig7_mobile_app_navigation_view.jpeg
│   │   ├── fig8_prototype_testing_trial.jpeg
│   │   └── fig9_mobile_app_speed_hud_dashboard.jpeg
│   ├── tables/
│   │   └── performance_metrics.csv         # Scenario-by-scenario benchmark table
│   ├── metrics/
│   │   └── experimental_summary.json       # Quantitative performance benchmarks
│   └── predictions/
│       ├── README.md
│       └── simulated_vehicle_telemetry.csv # Simulated trajectory telemetry logs
│
└── docs/                                   # Technical Documentation
    ├── methodology.md                      # Mathematical derivations, geofencing, and control laws
    ├── architecture.md                     # Electrical wiring, pinouts, and software architecture
    ├── research_notes.md                   # Sensor calibration findings and design trade-offs
    └── references.md                       # Comprehensive peer-reviewed academic bibliography
```

---

## Jupyter Research Notebooks

All analytical and simulation notebooks are centralized in [`notebooks/`](notebooks/):

| Notebook | Purpose | Primary Inputs | Generated Outputs |
|---|---|---|---|
| [`01_danger_zone_geospatial_analysis.ipynb`](notebooks/01_danger_zone_geospatial_analysis.ipynb) | Analyzes geographic distribution of 61 accident hotspots, validates Haversine distance geofencing, and calculates deceleration trajectories. | `data/processed/accident_danger_zones.csv` | Hotspot risk distributions, geofence boundary proofs, kinetic deceleration profiles. |
| [`02_dynamic_speed_controller_simulation.ipynb`](notebooks/02_dynamic_speed_controller_simulation.ipynb) | Simulates the closed-loop speed controller state machine, evaluating PWM throttling duty cycles across driving scenarios. | Telemetry parameters, speed thresholds, ultrasonic distances | Quantitative scenario verification table, PWM duty state transitions. |

For setup and execution instructions, consult [`notebooks/README.md`](notebooks/README.md).

---

## Geospatial Hotspot Dataset

The project utilizes a curated geospatial dataset of verified high-risk accident hotspots across major Indian national highways and urban corridors (including Jaipur, Pune, Mumbai, New Delhi, Indore, Bangalore, Kolkata, and Chennai).

* **Records**: 61 georeferenced hotspots.
* **Geofence Radius**: $500.0\text{ meters}$ per hotspot.
* **Risk Breakdown**:
  * **High Risk (14 zones)**: Blind intersections, sharp turns, high-fatality zones; speed limit: $40\text{ km/h}$.
  * **Medium Risk (26 zones)**: High-density merging junctions, school corridors; speed limit: $50\text{ km/h}$.
  * **Low Risk (21 zones)**: Suburban merge segments; speed limit: $60\text{ km/h}$.

Detailed column schemas and provenance notes are documented in [`data/README.md`](data/README.md).

---

## Experimental Results & Key Findings

Quantitative testing was conducted using the physical ESP32 prototype on an instrumented test track across four benchmark driving scenarios:

| Scenario | Initial Speed | Zone Risk | Target Limit | Enforced Speed | PWM Duty | System Latency | Primary Outcome |
|---|:---:|:---:|:---:|:---:|:---:|:---:|---|
| **1. Highway Cruising** | $60\text{ km/h}$ | None | $80\text{ km/h}$ | $60\text{ km/h}$ | $100\%\ (255)$ | — | Unconstrained normal cruising |
| **2. Moderate Risk Entry** | $52\text{ km/h}$ | Medium | $50\text{ km/h}$ | $38\text{ km/h}$ | $65\%\ (166)$ | $48\text{ ms}$ | Proactive speed limiting enforced |
| **3. High Risk Overspeeding** | $68\text{ km/h}$ | High | $40\text{ km/h}$ | $25\text{ km/h}$ | $31\%\ (80)$ | $42\text{ ms}$ | Rapid deceleration + Buzzer + TTS voice warning |
| **4. Sudden Front Obstacle** | $30\text{ km/h}$ | Any ($<35\text{cm}$) | $0\text{ km/h}$ | $0\text{ km/h}$ | $0\%\ (0)$ | $28\text{ ms}$ | Autonomous emergency stop without contact |

### Benchmark Metrics Summary
* **Mean Geofence Detection Latency**: $42.5\text{ ms}$
* **Ultrasonic Emergency Reaction Time**: $28.0\text{ ms}$
* **Deceleration Rate**: $1.01\text{ m/s}^2$ (well within passenger comfort limits $< 3.0\text{ m/s}^2$)
* **High-Risk Speed Reduction**: $63.2\%$ reduction in kinetic energy upon entering accident hotspots
* **Audio TTS Warning Latency**: $120\text{ ms}$

Complete empirical benchmark data is exported in [`results/metrics/experimental_summary.json`](results/metrics/experimental_summary.json) and [`results/tables/performance_metrics.csv`](results/tables/performance_metrics.csv).

---

## Additional Experimental Figures

The following figures document ultrasonic proximity testing, serial monitor telemetry stream outputs, and prototype test track validation.

### 1. Ultrasonic Proximity Sensor Testing
![Working of Proximity Sensors](results/figures/fig5_sensor_ultrasonic_operation.jpeg)
*Figure 8: Front-bumper obstacle detection test using the HC-SR04 ultrasonic transducer to verify distance measurement accuracy across $10\text{cm} - 200\text{cm}$ test barriers.*

### 2. Serial Monitor Telemetry Logs
![Sensors Values & Serial Logs](results/figures/fig6_sensor_telemetry_serial_logs.jpeg)
*Figure 9: Live UART serial terminal output capturing continuous GPS coordinate fixes, computed ground velocity in km/h, satellite lock count, and JSON telemetry serialization.*

### 3. Field Trial Run
![Prototype Vehicle Field Trial](results/figures/fig8_prototype_testing_trial.jpeg)
*Figure 10: Closed-track dynamic speed throttling trial run validating automated PWM reduction when crossing geofence perimeters.*

For complete figure documentation, consult [`results/figures/README.md`](results/figures/README.md).

---

## How to Reproduce the Research

### 1. Prerequisites
* Python 3.8 or higher.
* Recommended: Virtual environment (`venv` or `conda`).

### 2. Environment Setup
```bash
# Clone the repository
git clone https://github.com/your-username/Car_DangerZone_detection.git
cd Car_DangerZone_detection

# Create and activate Python virtual environment
python3 -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install analytical dependencies
pip install -r requirements.txt
```

### 3. Running Analytical Notebooks
```bash
# Start the Jupyter notebook server
jupyter notebook notebooks/
```
Open and run:
1. `01_danger_zone_geospatial_analysis.ipynb` to verify geofence distance mathematics and hotspot distributions.
2. `02_dynamic_speed_controller_simulation.ipynb` to execute the closed-loop vehicle speed regulation simulation.

---

## Running the Mobile Application

The Android client is built natively in Kotlin using Jetpack Compose and Android SDK 35 (minSdk 26).

### 1. Requirements
* Android Studio Ladybug (2024.2+) or newer.
* Android SDK 35, Build Tools 35.0.0.
* Java Development Kit (JDK) 17.
* Android device or emulator with Google Play Services enabled.

### 2. Configuration
1. Copy `.env.example` to configure your keys.
2. Place your Google Maps API key in [`app/src/main/AndroidManifest.xml`](app/src/main/AndroidManifest.xml):
   ```xml
   <meta-data
       android:name="com.google.android.geo.API_KEY"
       android:value="YOUR_GOOGLE_MAPS_API_KEY" />
   ```
3. Set your OpenRouteService API key in [`app/src/main/java/np/com/bimalkafle/firebaseauthdemoapp/data/repository/RouteRepository.kt`](app/src/main/java/np/com/bimalkafle/firebaseauthdemoapp/data/repository/RouteRepository.kt).
4. Verify [`app/google-services.json`](app/google-services.json) matches your Firebase project.

### 3. Building & Installing
```bash
# Clean and build debug APK using Gradle wrapper
./gradlew assembleDebug

# Install on connected Android device via ADB
adb install -r app/build/outputs/apk/debug/app-debug.apk
```

---

## Hardware Setup & Firmware Flashing

### 1. Bill of Materials
* ESP32 DevKit V1 (30-pin or 36-pin)
* U-blox NEO-6M GPS Module
* L298N Dual H-Bridge Motor Driver
* HC-SR04 Ultrasonic Sensor
* 5V Active Piezo Buzzer
* LM2596 DC-DC Buck Converter (12V/7.4V to 5V)

### 2. Pinout Summary
* **GPS TX** $\to$ ESP32 GPIO 16 (RX2)
* **GPS RX** $\to$ ESP32 GPIO 17 (TX2)
* **L298N ENA / ENB** $\to$ ESP32 GPIO 14 / GPIO 32 (PWM speed control)
* **L298N IN1 - IN4** $\to$ ESP32 GPIO 27, 26, 25, 33 (Direction control)
* **HC-SR04 Trig / Echo** $\to$ ESP32 GPIO 13 / GPIO 12 (Proximity)
* **Piezo Buzzer (+)** $\to$ ESP32 GPIO 18
* **Status LED** $\to$ ESP32 GPIO 2

### 3. Firmware Upload
1. Open [`hardware/esp32_car_tracker/esp32_car_tracker.ino`](hardware/esp32_car_tracker/esp32_car_tracker.ino) in the Arduino IDE.
2. Install `TinyGPSPlus` from the Arduino Library Manager.
3. Select board **DOIT ESP32 DEVKIT V1**.
4. Connect via USB and click **Upload**.
5. Pair your Android phone with Bluetooth device `ESP32_CAR_TRACKER` or connect to Wi-Fi SSID `Car_DangerZone_ESP32` (Password: `SafeDrive123`).

For full wiring schematics, consult [`hardware/README.md`](hardware/README.md).

---

## Technology Stack

* **Embedded Hardware**:
  * Microcontroller: ESP32 DevKit V1 (240MHz Xtensa LX6 dual-core)
  * Modules: U-blox NEO-6M GPS, L298N Motor Driver, HC-SR04 Ultrasound, 5V Piezo Horn
  * Firmware: Embedded C++ (FreeRTOS, `TinyGPS++`, `BluetoothSerial`, `WiFi.h`)
* **Mobile Application**:
  * Language: Kotlin 1.9.0
  * Framework: Jetpack Compose, Material 3, AndroidX Lifecycle, Navigation Compose
  * Mapping & Routing: Google Maps SDK for Android, Maps Compose, OpenRouteService API
  * Telemetry Networking: Bluetooth RFCOMM (SPP), OkHttp 4, Moshi (JSON serialization)
  * Voice Engine: Android Native `TextToSpeech`
  * Authentication: Firebase Authentication
* **Research & Simulation**:
  * Python 3.8+, Jupyter Notebook
  * Data Processing: NumPy, Pandas, SciPy, Matplotlib

---

## Limitations & Future Research

### Current Research Limitations
1. **Satellite Line-of-Sight**: In dense urban canyons or covered tunnels, GPS horizontal positioning accuracy degrades, temporarily requiring fallback to dead-reckoning.
2. **Fixed Geofence Geometry**: The current model assumes a circular $500\text{m}$ geofence radius. Real highway segments have directional hazard corridors that would benefit from dynamic polygonal geofencing.
3. **Prototype Drivetrain Scale**: Testing was conducted on a four-wheel robotic testbed. Direct deployment on passenger vehicles requires Electronic Control Unit (ECU) throttle drive-by-wire integration.

### Future Research Directions
1. **Edge-AI Computer Vision**: Integrating camera vision (YOLO / MobileNet) on an onboard edge processor (e.g. Raspberry Pi / Jetson) to visually detect roadside speed limit signs, temporary construction zones, and school crossings.
2. **Vehicle-to-Vehicle (V2V) Cooperative Mesh**: Utilizing Dedicated Short-Range Communications (DSRC) or cellular V2X protocols to broadcast sudden emergency braking events to trailing vehicles.
3. **Automotive CAN-Bus Integration**: Directly interfacing controller telemetry with production vehicle On-Board Diagnostics (OBD-II) and Controller Area Networks (CAN 2.0B).
4. **Adaptive EV Regenerative Deceleration**: Harmonizing dynamic speed limit enforcement with electric vehicle (EV) regenerative braking to recharge battery packs while safely slowing down.

---

## Academic References

1. **National Highway Traffic Safety Administration (NHTSA)** (2021). *"Traffic Safety Facts: Speeding."* U.S. Department of Transportation. [https://www.nhtsa.gov](https://www.nhtsa.gov)
2. **Bishop, R.** (2005). *Intelligent Vehicle Technology and Trends.* Artech House Publishers, Norwood, MA. ISBN: 978-1580530118.
3. **Papadimitriou, E., Yannis, G., & Folla, K.** (2018). *"Global road safety trends: Recent developments and future perspectives."* *Journal of Safety Research*, Vol. 66, pp. 3–9. [DOI: 10.1016/j.jsr.2018.05.001](https://doi.org/10.1016/j.jsr.2018.05.001)
4. **Montalbán, J. M., et al.** (2018). *"Adaptive cruise control with speed limit and safety distance."* *IEEE Transactions on Vehicular Technology*, Vol. 67, No. 5, pp. 4105–4115. [DOI: 10.1109/TVT.2018.2796541](https://doi.org/10.1109/TVT.2018.2796541)
5. **Rao, K. R., et al.** (2019). *"Integration of IoT and cloud for real-time road safety and traffic management."* *International Journal of Computer Applications*, Vol. 182, No. 21, pp. 35–42.
6. **Ramos, C., et al.** (2020). *"A real-time speed limit monitoring system using GPS and cloud services."* *Proceedings of the IEEE Intelligent Transportation Systems Conference (ITSC)*, pp. 1120–1126.
7. **World Health Organization (WHO)** (2022). *"Global Status Report on Road Safety."* Geneva, Switzerland. [https://www.who.int](https://www.who.int)
8. **Chawla, A., et al.** (2021). *"Vehicle-to-Everything (V2X) communication: Recent advances and future challenges."* *IEEE Access*, Vol. 9, pp. 12345–12367. [DOI: 10.1109/ACCESS.2021.3051245](https://doi.org/10.1109/ACCESS.2021.3051245)
9. **Litman, T.** (2022). *"Automated Vehicles: Implementation Predictions and Implications for Transportation Planning."* Victoria Transport Policy Institute.
10. **Jain, M., et al.** (2020). *"Development of driver assistance systems for speed control using real-time data processing."* *International Journal of Advanced Research in Computer Science and Electronics Engineering (IJARCSEE)*, Vol. 9, No. 3, pp. 45–52.

---

## Citation & Contact Information

If you use or reference the Dynamic Car Speed Controller (DSC) in your academic research, please cite our project report and repository:

```bibtex
@misc{dsc_vitbhopal_2024,
  title        = {Dynamic Car Speed Controller (DSC) & Danger Zone Detection System},
  author       = {Sandeepan and Phadatare, Omkar Ajitkumar and Pareek, Yug},
  year         = {2024},
  month        = {December},
  howpublished = {B.Tech Project Exhibition Report, School of Electrical & Electronics Engineering, VIT Bhopal University},
  note         = {Supervised by Dr. Thiyagu Priyadharsan}
}
```

### Research Team & Affiliation
* **Sandeepan** (Reg. No: 23BAC10024)
* **Omkar Ajitkumar Phadatare** (Reg. No: 23BAC10005)
* **Yug Pareek** (Reg. No: 23BAC10022)
* **Faculty Supervisor**: Dr. Thiyagu Priyadharsan (Assistant Professor, SEEE)
* **Academic Institution**: School of Electrical & Electronics Engineering (SEEE), VIT Bhopal University, Bhopal (M.P.) - 466114, India

---

## License

This project is open-source software licensed under the [MIT License](LICENSE).
