Wednesday, 27 May 2026

AI Smart Traffic Signal Control Using Real-Time Vehicle Density Analysis

AI Smart Traffic Signal Control Using Real-Time Vehicle Density Analysis Agentic IoT System using ESP32 + AI + n8n + Telegram Voice Alerts + Google Sheets + ThingSpeak
AI Smart Traffic Signal Control Using Real-Time Vehicle Density Analysis Agentic IoT System using ESP32 + AI + n8n + Telegram Voice Alerts + Google Sheets + ThingSpeak 1. Project Overview This project is an AI-powered smart traffic management system that dynamically controls traffic lights based on real-time vehicle density using an ESP32 microcontroller, IoT cloud services, and automation workflows. The system: Detects vehicle density using sensors/camera logic Uses AI logic to optimize signal timing Sends data to cloud dashboards Stores traffic logs in Google Sheets Generates Telegram alerts and voice notifications Uses n8n workflows for automation Predicts congestion and power consumption trends 2. Objectives Reduce traffic congestion Minimize waiting time Optimize signal timing automatically Enable remote monitoring Provide real-time traffic analytics Generate AI-based predictions Enable smart city integration 3. System Architecture Vehicle Sensors / Camera ↓ ESP32 ↓ WiFi / Internet Connection ↓ ┌────────────────────────────┐ │ Cloud Services │ │----------------------------│ │ ThingSpeak Dashboard │ │ Google Sheets Logging │ │ Telegram Alerts │ │ n8n Automation │ └────────────────────────────┘ ↓ AI Decision Engine ↓ Smart Traffic Signal Control 4. Hardware Components List Component Quantity Purpose ESP32 Dev Board 1 Main controller Ultrasonic Sensors HC-SR04 4 Vehicle density detection Traffic LEDs (Red/Yellow/Green) 12 Traffic lights Resistors 220Ω 12 LED protection Breadboard 1 Prototyping Jumper Wires Multiple Connections Buzzer 1 Alert indication 5V Power Supply 1 System power WiFi Router 1 Internet connectivity Optional Camera Module 1 AI vision enhancement 5. Working Principle Each road lane contains an ultrasonic sensor. The ESP32: Measures vehicle queue length Calculates density score Assigns green signal duration dynamically Uploads data to cloud Triggers alerts during congestion AI Logic High density → longer green signal Low density → shorter green signal Emergency override supported Predictive congestion analysis possible 6. Traffic Density Logic Example density ranges: Distance Measured Traffic Density > 80 cm Low 40–80 cm Medium < 40 cm High Signal timing: Density Green Time Low 10 sec Medium 20 sec High 35 sec 7. Circuit Schematic Diagram +------------------+ | ESP32 | | | HC-SR04_1 --> GPIO 4,5 HC-SR04_2 --> GPIO 18,19 HC-SR04_3 --> GPIO 21,22 HC-SR04_4 --> GPIO 23,25 RED LEDs --> GPIO 12,13,14,15 YELLOW LEDs --> GPIO 26,27,32,33 GREEN LEDs --> GPIO 2,16,17,18 BUZZER --> GPIO 5 WiFi --> Cloud Services +------------------+ 8. Flowchart START ↓ Initialize ESP32 ↓ Connect WiFi ↓ Read Sensor Data ↓ Calculate Vehicle Density ↓ AI Decision Engine ↓ Set Traffic Signal Timing ↓ Upload Data to ThingSpeak ↓ Store Data in Google Sheets ↓ Trigger Telegram Alerts ↓ Repeat Loop 9. ESP32 Source Code (Arduino IDE) #include #include const char* ssid = "YOUR_WIFI_NAME"; const char* password = "YOUR_WIFI_PASSWORD"; String apiKey = "THINGSPEAK_API_KEY"; #define RED1 12 #define YELLOW1 26 #define GREEN1 2 #define TRIG1 4 #define ECHO1 5 long duration; int distance; WiFiClient client; void setup() { Serial.begin(115200); pinMode(TRIG1, OUTPUT); pinMode(ECHO1, INPUT); pinMode(RED1, OUTPUT); pinMode(YELLOW1, OUTPUT); pinMode(GREEN1, OUTPUT); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting..."); } Serial.println("WiFi Connected"); } int getDistance() { digitalWrite(TRIG1, LOW); delayMicroseconds(2); digitalWrite(TRIG1, HIGH); delayMicroseconds(10); digitalWrite(TRIG1, LOW); duration = pulseIn(ECHO1, HIGH); distance = duration * 0.034 / 2; return distance; } void loop() { int density = getDistance(); int greenTime = 10; if (density < 40) { greenTime = 35; } else if (density < 80) { greenTime = 20; } digitalWrite(GREEN1, HIGH); delay(greenTime * 1000); digitalWrite(GREEN1, LOW); digitalWrite(YELLOW1, HIGH); delay(3000); digitalWrite(YELLOW1, LOW); digitalWrite(RED1, HIGH); delay(5000); sendToThingSpeak(density, greenTime); } void sendToThingSpeak(int density, int greenTime) { if(WiFi.status()== WL_CONNECTED){ HTTPClient http; String url = "http://api.thingspeak.com/update?api_key=" + apiKey + "&field1=" + String(density) + "&field2=" + String(greenTime); http.begin(url); int httpCode = http.GET(); Serial.println(httpCode); http.end(); } } 10. ThingSpeak Cloud Dashboard Setup Using ThingSpeak Steps Create account Create new channel Add fields: Vehicle Density Green Signal Time Congestion Score Copy Write API Key Add API key into ESP32 code Dashboard features: Real-time graphs Traffic analytics Historical trends AI prediction visualization 11. Google Sheets Integration Using: Google Apps Script Webhook API n8n automation Data Stored Time Density Green Time Alert Google Apps Script function doPost(e) { var sheet = SpreadsheetApp.getActiveSheet(); var data = JSON.parse(e.postData.contents); sheet.appendRow([ new Date(), data.density, data.greenTime, data.alert ]); return ContentService .createTextOutput("Success"); } Deploy as: Web App Access: Anyone 12. Telegram Bot Setup Using Telegram BotFather Steps Open Telegram Search “BotFather” Create bot using: /newbot Copy bot token Get Chat ID Use HTTP API in n8n 13. Telegram Voice Notification Alerts Example alert: ⚠ Heavy Traffic Detected at Junction 2 Green Signal Extended to 35 Seconds Voice generation options: Google TTS ElevenLabs gTTS Python API 14. n8n Automation Workflow Using n8n Automation Platform Workflow Functions Receive ESP32 webhook data Analyze congestion Store records Trigger Telegram notifications Generate voice alerts Predict traffic trends n8n Workflow Structure Webhook Trigger ↓ Data Parser ↓ IF Density > Threshold ↓ ┌──────────────┬───────────────┐ ↓ ↓ Telegram Msg Google Sheets ↓ Voice Alert ↓ ThingSpeak Update 15. Sample n8n Workflow JSON { "nodes": [ { "name": "Webhook", "type": "n8n-nodes-base.webhook", "position": [250, 300] }, { "name": "IF Traffic High", "type": "n8n-nodes-base.if", "position": [500, 300] }, { "name": "Telegram Alert", "type": "n8n-nodes-base.telegram", "position": [750, 200] }, { "name": "Google Sheets", "type": "n8n-nodes-base.googleSheets", "position": [750, 400] } ] } 16. AI Power Consumption Prediction Logic The AI module predicts: Power usage Peak traffic hours Congestion patterns Energy optimization Simple Prediction Formula P=V×I Where: P = Power V = Voltage I = Current AI Prediction Parameters Parameter Usage Vehicle Count Congestion estimate Signal Duration Energy usage Peak Time Traffic prediction Historical Data ML training 17. AI Enhancement Possibilities Machine Learning Features Vehicle classification Emergency vehicle detection Accident detection Adaptive traffic prediction Smart rerouting Possible AI frameworks: TensorFlow Lite Edge Impulse OpenCV YOLO object detection 18. Cloud Dashboard Features Dashboard Includes Live traffic density Signal status Historical analytics Congestion heatmaps AI prediction charts Alert logs 19. Future Enhancements Advanced Features Smart City Integration Connect multiple junctions Centralized monitoring AI Camera Vision Vehicle counting Lane analysis Emergency Vehicle Priority Ambulance detection Automatic signal clearance Solar Power System Renewable energy support GSM Backup SMS alerts during internet failure 20. Deployment Guide Step-by-Step Deployment Hardware Assemble circuit Connect sensors Verify LED operation Software Install Arduino IDE Install ESP32 board package Upload source code Cloud Configure ThingSpeak Configure Google Sheets Configure Telegram Bot Import n8n workflow Testing Simulate traffic Verify signal timing Check dashboard updates Confirm Telegram alerts 21. Expected Results Scenario Output Low Traffic Short signal duration Heavy Traffic Extended green signal Congestion Telegram alert Peak Hours AI prediction generated 22. Advantages Reduces traffic congestion Saves fuel Low-cost implementation Real-time monitoring Scalable architecture Supports smart cities 23. Applications Smart city infrastructure Highways Urban intersections Industrial traffic control Campus traffic systems 24. Technologies Used Technology Purpose ESP32 IoT controller n8n Workflow automation Telegram Bot Notifications ThingSpeak Cloud analytics Google Sheets Data logging AI/ML Prediction logic 25. Conclusion This project demonstrates a modern AI-powered intelligent traffic management system using ESP32, IoT cloud platforms, and automation tools. By combining: Real-time vehicle density analysis AI-based adaptive signal control Cloud dashboards Telegram voice notifications Automation workflows …the system provides a scalable foundation for future smart-city traffic infrastructure.

No comments:

Post a Comment

AI Smart Traffic Signal Control Using Real-Time Vehicle Density Analysis

AI Smart Traffic Signal Control Using Real-Time Vehicle Density Analysis Agentic IoT System using ESP32 + AI + n8n + Telegram Voice Alerts +...