◈ CLASS VIII SCIENCE PROJECT — SMART CITIES & IoT ◈

MARG
RAKSHAK

जहाँ नियम है, वहाँ मार्गरक्षक है

An IoT-based Smart Traffic Violation Detection System using ESP32 microcontroller with Cloudflare cloud backend, Telegram photo alerts, and a live global dashboard. Built on a budget of under ₹6,000. Real-world deployable.

🚀 8+ Violations Detected
Live Cloud Dashboard
📸 Telegram Photo Alerts
🌙 Day / Night Smart Mode
☀️ Solar Powered Off-Grid
▶ LIVE DEMO ⬇ Explore Project
8+
Violation Types
₹6K
Total Cost
3
Weeks to Build
2
ESP32 Boards
24/7
Uptime Capable
100%
Off-Grid Ready

Built By a Class VIII Student

With curiosity, code, and determination — a 13-year-old proved that age is no barrier to building real-world IoT solutions.

TS
Tripti Sinha
Class VIII · Ram Kishan Institute, CBSE · Delhi
A passionate student with a deep interest in technology and problem-solving. Tripti built MargRakshak entirely from scratch — learning IoT concepts, C++ programming for ESP32, and cloud backend integration from zero. This project is her answer to a real national problem: road safety in India.
🧑‍💻 Mentor: Shivanshu Rai
B.Tech Final Year Student (CSE) — Tripti's elder brother who guided the technical architecture, helped debug the Cloudflare Workers code, and encouraged her every step of the way. All hardware, sensors, soldering, and final deployment was done by Tripti herself.
TOOLS USED
Arduino IDE Cloudflare Workers Telegram Bot API Google Gemini Claude AI Cloudflare D1 (SQLite)
THE 3-WEEK JOURNEY
WEEK 1 — DAYS 1–5
Idea → Hardware Setup
Tripti identified the problem from a school newspaper article about road accident deaths. She researched ESP32, ordered components, and assembled the basic breadboard circuit with IR sensors, LED traffic light, and OLED display. First speed detection test successful on Day 4.
WEEK 2 — DAYS 6–13
Violations + Camera + Telegram
Added ESP32-CAM, integrated wrong-way detection, tailgating logic, red light detection, gas sensor, and sound sensor. Biggest challenge: JPEG upload from ESP32-CAM to Telegram via WiFiClientSecure. Took 3 days to debug the multipart boundary format with Shivanshu's help.
WEEK 3 — DAYS 14–21
Cloud Migration + Solar Power + Final Polish
Migrated from local WiFi hotspot dashboard to Cloudflare D1 cloud backend — now accessible from anywhere globally at margrakshak.pages.dev. Added solar power system with 6 panels + 18650 battery. Added Demo Mode for exhibitions. Tripti wrote the complete project report herself.
AI ASSISTANCE
Gemini + Claude as Learning Partners
Used Google Gemini and Anthropic Claude to understand concepts like HTTP multipart encoding, Cloudflare Worker syntax, and D1 SQL queries — not as code generators, but as teachers who explained concepts in simple Hindi/English. All code was written, tested, and understood by Tripti herself.

India's Road Safety Crisis

1.5 lakh lives lost every year. Most of it preventable. Existing solutions are either too expensive or don't exist at all.

💀

1.5 Lakh Deaths Per Year

India accounts for the highest number of road accident fatalities in the world. Overspeeding, signal jumping, and wrong-way driving are the top three causes — all detectable by sensors.

💸

₹40 Crore for 100 Cameras

The government spends approximately ₹40 lakh per speed camera installation. At this rate, covering even 1% of India's 63 lakh km road network is economically impossible.

🚫

No Integrated Multi-Violation System

Existing systems detect only one violation type per device. Speed camera, red light camera, and emission sensor are all separate — requiring separate infrastructure investment.

👮

Manual Monitoring Fails

Traffic police cannot be present at every junction 24×7. Human monitoring is inconsistent, prone to bias, and completely absent in rural and remote areas where most accidents occur.

⚡ The MargRakshak Solution

One pocket-sized circuit board costing under ₹6,000 that monitors a road 24 hours a day, automatically detects 8 categories of violations, photographs offenders, maintains a digital challan log, streams live data to a global cloud dashboard, and runs completely off-grid on solar power — all simultaneously, without any human intervention.

Two-Board Architecture

Two ESP32 microcontrollers working in tandem — one as the intelligent brain, one as the eyes connected to the cloud.

BOARD 01

ESP32 Dev Module

The main brain of the system. Handles all sensing, decision-making, traffic logic, and cloud data push. Runs the full embedded C++ firmware at 240MHz.

  • IR speed detection & direction analysis
  • Traffic light control (Indian sequence)
  • Challan generation & numbering
  • Noise pollution monitoring
  • Vehicle emission (MQ sensor) reading
  • Smart streetlight via LDR
  • OLED live display update
  • Cloudflare D1 data push every 2s via HTTPS
BOARD 02

ESP32-CAM (AI Thinker)

Dedicated camera and cloud uplink board. Communicates with Board 01 via Serial (UART). Handles photography with intelligent flash control.

  • Listens for CLICK_AND_SEND commands via Serial
  • Captures UXGA JPEG photo on vehicle detection
  • Holds photo in RAM (Prepare → Send/Discard logic)
  • Auto flash for night-time captures (50ms burst)
  • Sends photo to Telegram Bot API via HTTPS
  • Cloudflare Worker saves photo URL to D1 database
  • Last 5 violation photos visible on live dashboard

Step-by-Step Detection Logic

01

Vehicle Approaches

IR Beam 1 is broken. ESP32 records timestamp t1 and immediately commands ESP32-CAM to capture a photo and hold it in RAM.

02

Speed Calculation

When IR Beam 2 is broken, Speed = (0.175m ÷ elapsed time) × 3.6 = km/h. If speed exceeds limit, overspeed challan issued.

03

Direction Check

If Beam 2 breaks before Beam 1, vehicle is travelling in reverse (wrong way). A wrong-way violation and photo alert are triggered instantly.

04

Tailgating Detection

If a second vehicle passes within 1 second of the previous one, a tailgating challan is automatically generated for unsafe following distance.

05

Red Light Check

The system always knows the exact signal state. If a vehicle passes while trafficState == RED, a Red Light Jump challan is generated.

06

Photo Decision

Violation found → ESP32-CAM sends the RAM-held photo to Telegram with violation label. No violation detected → photo silently discarded, no spam.

07

Cloud Update

Every 2 seconds, all live data is pushed to Cloudflare D1 database via HTTPS. Dashboard at margrakshak.pages.dev updates automatically.

08

Continuous Monitoring

Noise (sound sensor), air quality (MQ gas sensor), and ambient light (LDR for streetlight) are sampled every 20ms regardless of vehicle detection.

Powered by Cloudflare

A global edge computing backend that makes the dashboard accessible from anywhere in the world — not just on a local WiFi.

Cloudflare D1 + Workers

The system uses a Cloudflare Worker deployed at the network edge. The ESP32 pushes JSON sensor data every 2 seconds. The Worker stores it in a Cloudflare D1 SQLite database. The live dashboard fetches this data from anywhere in the world.

Photo uploads from ESP32-CAM go through the same Worker as multipart/form-data. The Worker forwards photos to Telegram, extracts the direct URL, and stores it in D1 — making violation photos visible on the dashboard from anywhere.

  • ESP32 offline detection via seconds_offline calculation
  • Last 50 violation photos stored with reasons
  • Dashboard polls every 2.5s — smooth real-time UX
  • CORS-enabled — works from any browser, any device
  • Zero cost deployment on Cloudflare Free tier
  • Smart sync timer that compensates for data transmission delay
cloudflare-worker.js — live data flow
// ESP32 POST → Cloudflare Worker
POST https://margrakshak.workers.dev
Content-Type: application/json

{"speed":12.4, "tl":"g",
"tr":8, "vos":2, "vrl":1,
"np":45, "ai":120}

// Worker saves to D1 SQLite
INSERT OR REPLACE INTO NodeState
(id, json_data) VALUES (1, ?)

// Dashboard GET → fetches + calculates
seconds_offline = floor((now - last_seen) / 1000)

✓ HTTP 200 — Dashboard updated globally

17 Core Features

From the moment a vehicle enters the sensor zone to the challan appearing on the cloud dashboard — everything is automated.

01

Speed Detection & Challan

Two IR beam sensors placed exactly 17.5 cm apart measure precise crossing time. Speed = distance ÷ time × 3.6 km/h. Automatic challan + buzzer alert + Telegram photo on violation.

⬅️
02

Wrong-Way Driving Detection

Direction is identified by which IR sensor triggers first. If a vehicle travels in reverse (illegal) direction, a wrong-way violation is logged with a Telegram photo alert instantly.

🚦
03

Red Light Jump Detection

The system knows the exact signal state at all times. Any vehicle crossing the IR sensors during RED phase automatically generates a Red Light Jump challan with photo evidence.

🚗
04

Tailgating Detection

If a second vehicle passes the sensor point within 1 second of the previous vehicle, it is flagged for dangerously small following distance — a challan is generated automatically.

🇮🇳
05

Authentic Indian Traffic Sequence

Green (15s) → Yellow (3s) → Red (10s) → Yellow (3s) → Green. A live countdown timer is shown on the dashboard, with smart sync to compensate for network transmission delay.

📢
06

Noise / Horn Pollution Detection

A sound sensor continuously monitors ambient noise. When loud horns or excessive noise above 85 dB equivalent are detected in a 500ms window, an alert triggers on the dashboard.

💨
07

Vehicle Emission / AQI Monitoring

MQ-series gas sensor measures pollutant concentration with 3-minute warm-up calibration. Dashboard shows AQI as GOOD / MODERATE / POOR with colour-coded badge and live bar graph.

💡
08

Smart Streetlight (LDR)

An LDR constantly checks ambient light levels. When darkness is detected (night-time), the streetlight LED switches on automatically. Turns off at dawn — zero manual intervention.

🌙
09

Night-Mode Camera Flash

When LDR detects night conditions, ESP32-CAM activates its built-in flash LED for exactly 50 milliseconds during photo capture — ensuring clear, usable evidence images in darkness.

📱
10

Telegram Violation Alerts with Photo

Every challan-worthy violation triggers the ESP32-CAM to send a photo message to a Telegram bot with a labelled caption (e.g., "VIOLATION: OVERSPEED"). Reaches officer's phone in seconds.

🧠
11

Prepare → Send → Discard Logic

Camera captures photo at vehicle detection, holds in RAM. Decision: violation found → send via Telegram. No violation → silently discard. No false alerts, no photo spam to Telegram.

🌐
12

Live Cloud Dashboard (Global)

Full mobile-responsive dashboard at margrakshak.pages.dev/live — accessible from any device anywhere in the world. Updates every 2.5 seconds via Cloudflare D1 polling.

📋
13

Automatic Challan Log

Every violation receives a unique challan number (starting at #1001) with violation description. Last 5 challans always visible on cloud dashboard. Full log accessible via full-screen modal.

🔔
14

3-Beep Buzzer Alerts

Non-blocking 3-beep buzzer pattern sounds immediately on every challan-worthy violation. Uses state-machine buzzer logic so vehicle detection is never interrupted during beeping.

📺
15

OLED Live Display

A 128×64 OLED screen (I2C) shows live speed, signal state, vehicle count, active alert message, latest challan number, and Cloudflare connection status — updated every loop cycle.

🎭
16

8-Step Demo Mode

Pressing a dedicated button triggers a built-in demo that cycles through all 8 violation types automatically — ideal for science exhibitions, STEM fairs, and classroom demonstrations.

☀️
17

Solar Off-Grid Power System NEW

6 solar panels (6V/900mAh total) + 18650 Li-ion battery (2600mAh) + power bank module provide 5V regulated output. Granular power control via 3 switches. Completely off-grid capable.

Components & Estimated Cost

Every component under ₹6,000 total. Designed to be replicable by any school, panchayat, or municipality at scale.

Component Qty Function
ESP32 Dev Module 1 Main brain — reads all sensors, controls traffic light, pushes data to Cloudflare D1 every 2 seconds
ESP32-CAM (AI Thinker) 1 Camera module — captures violation photos, sends to Telegram Bot API via WiFiClientSecure
IR Obstacle Sensor 2 Speed detection (17.5cm apart) and direction detection for wrong-way identification
MQ Gas Sensor (MQ-2/135) 1 Vehicle emission monitoring, AQI classification (Good / Moderate / Poor)
Sound Sensor Module 1 Noise / horn pollution detection — triggers alert above 85 dB equivalent threshold
LDR (Light Sensor) 1 Ambient light detection — auto-controls smart streetlight and triggers night mode for camera
OLED Display 128×64 (I2C) 1 On-device live display of speed, signal state, violations, alerts, and cloud status
Red LED 1 Traffic light — RED signal
Yellow LED 1 Traffic light — YELLOW signal (transition state)
Green LED 1 Traffic light — GREEN signal
White LED (Street) 1 Smart streetlight — auto-activates at night via LDR reading
Active Buzzer 1 Audio alert — 3-beep non-blocking pattern on every challan-worthy violation
Push Button 1 Triggers 8-step automated Demo Mode for science exhibitions and STEM fairs
Breadboard + Jumper Wires Set Prototyping connections between all components
Miniature Road Model (Foam Board) 1 Physical road prototype base with road markings, plants, and miniature vehicles for demo
Solar Panel (6V / 150mAh)★ NEW 6 Power generation — 6 panels in parallel = 6V / 900mAh total. Charges 18650 battery via power bank module
18650 Li-Ion Battery (3.7V, 2600mAh)★ NEW 1 Energy storage — stores solar energy, powers entire node for extended hours without sunlight
Power Bank Module (No Display)★ NEW 1 Power management — accepts 6V solar input, charges 18650 cell, boosts output to clean 5V DC
Toggle Switch★ NEW 3 SW1=Master (all power), SW2=Gas Sensor branch, SW3=ESP32-CAM branch (for power management)
ESTIMATED TOTAL COST
₹5,000–6,000
vs ₹40 lakh for a government speed camera
COST SAVINGS vs GOVERNMENT
99.99%
cheaper than existing infrastructure

Solar Off-Grid Power Architecture

A fully self-sustaining three-tier power system — generate, store, distribute. No electrical infrastructure required anywhere.

☀️

SOLAR ARRAY

Panels: 6 × (6V / 150mAh)
Wiring: All 6 in Parallel
Output: 6V / 900mAh
Purpose: Charge 18650 via module
🔋

18650 Li-Ion CELL

Type: 18650 Li-Ion
Voltage: 3.7V nominal / 4.2V max
Capacity: 2600 mAh
Mode: Pass-through charging

POWER BANK MODULE

Input: 6V solar array
Output: 5V DC regulated (boost)
Function: Charge + Discharge simultaneously
Type: No display (saves power)

⚡ POWER FLOW DIAGRAM

☀️ Solar Array
6V × 6 panels = 900mAh
⚡ Power Bank Module
Charge + Boost to 5V
🔋 18650 Cell
3.7V / 2600mAh Storage
5V Output
SW1 MASTER SWITCH
Cuts entire system
SW2 → Gas Sensor
SW3 → ESP32-CAM
ESP32 Main + All Modules
SW1 — Master Switch First after power bank output. Cuts ALL power to the entire system.
SW2 — Gas Sensor Independent branch. Disable MQ sensor to save power in clean-air deployments.
SW3 — ESP32-CAM Independent branch. Disable camera when Telegram alerts are not needed.

Unique Selling Points

What makes MargRakshak genuinely different from everything else out there.

COST

₹6,000 vs ₹40 Lakh

Government speed cameras cost ~₹40 lakh each. MargRakshak delivers more features at 0.015% of that cost. Scalable to thousands of units.

INTEGRATION

8-in-1 Violation Detection

Overspeed, wrong way, red light jump, tailgating, noise, emission, streetlight, photo evidence — all in a single unit. No other system matches this integration.

CONNECTIVITY

Global Cloud Dashboard

No more "local WiFi only" limitation. Live data accessible from any phone, anywhere in the world via margrakshak.pages.dev — powered by Cloudflare's global edge network.

EVIDENCE

Tamper-Proof Photo Proof

Every challan is backed by an automatic timestamped photo sent directly to Telegram. Reduces disputes, eliminates corruption, creates an auditable digital trail.

INTELLIGENCE

Smart Photo Memory

Prepare → Send → Discard logic means zero false Telegram alerts. The camera only fires when a violation is confirmed — not on every vehicle passing.

★ NEW — OFF-GRID

Solar Powered, Zero Infrastructure

6 solar panels + 18650 battery + power bank module. Deploy anywhere — highway, rural junction, remote area — with absolutely no electrical infrastructure required.

What Comes Next

MargRakshak is a proof-of-concept today. Here is the roadmap for a full-scale national deployment.

☀️

Expanded Solar System

Upgrade to a larger panel and 10,000mAh battery pack for 72-hour autonomous operation even on cloudy days.

🔢

AI Number Plate Recognition

Upgrade to higher-resolution camera + TensorFlow Lite model for automatic reading of vehicle registration plates — enabling direct digital challans.

📡

LoRa / 4G City Network

Link multiple nodes using LoRa radio modules or 4G SIM, creating a city-wide sensor mesh reporting to a central police dashboard.

🕳️

Pothole Detection

Add ultrasonic or vibration sensor to detect road surface damage and automatically alert municipal corporations for repair.

🚶

Pedestrian Safety Module

A second IR beam across the footpath detects jaywalking and warns pedestrians before they step onto the road.

🚑

Emergency Vehicle Priority

A sound frequency analyser detects ambulance sirens and automatically switches the traffic light to green — clearing the path for emergency vehicles.

Watch MargRakshak in Action

Connect to the live cloud dashboard and see real-time data from the physical prototype — speed readings, traffic signal timer, violation counts, and Telegram photo alerts all streaming live.

▶ OPEN LIVE DASHBOARD
🌐 margrakshak.pages.dev/live
Or scan the QR code on the project board for instant access
PROJECT HOME
margrakshak.pages.dev
LIVE DASHBOARD
margrakshak.pages.dev/live
TELEGRAM ALERTS
@ShivaverseNode Bot
// CONCLUSION

Proof That Affordable Tech
Can Save Lives

MargRakshak proves that affordable, open-source hardware can solve a real national problem. Every year, thousands of lives are lost on Indian roads due to violations that a small sensor node can detect in milliseconds. With the addition of a solar power system, Li-ion battery storage, modular switch control, and a Cloudflare cloud backend, MargRakshak is now fully off-grid capable and globally accessible — ready for real-world deployment on highways, rural roads, and remote junctions with zero infrastructure required.

With government support and manufacturing at scale, thousands of MargRakshak nodes could be deployed across India at a fraction of the current cost — saving lives and reducing traffic chaos simultaneously.

SUBMITTED BY
Tripti Sinha
Class VIII · Ram Kishan Institute, CBSE
Science & Technology | Smart Cities & IoT