#define BLYNK_TEMPLATE_ID "TMPL3JywpzyVv"
#define BLYNK_TEMPLATE_NAME "Smart traffic management"
#define BLYNK_AUTH_TOKEN "2EW5dVhaTYylOJZsgcc6jN8zA_wrKvL-"
#include <NewPing.h>
#include <WiFi.h>
#include <BlynkSimpleEsp32.h>
// Define pins for Traffic Lights
const int redLight1 = 13;
const int yellowLight1 = 12;
const int greenLight1 = 14;
const int redLight2 = 27;
const int yellowLight2 = 26;
const int greenLight2 = 25;
// Define pins for Ultrasonic Sensors
const int trigPin1 = 2;
const int echoPin1 = 33;
const int trigPin2 = 16;
const int echoPin2 = 32;
// Define maximum distance for sensor
#define MAX_DISTANCE 400
NewPing sensor1(trigPin1, echoPin1, MAX_DISTANCE);
NewPing sensor2(trigPin2, echoPin2, MAX_DISTANCE);
// Blynk authentication token
char auth[] = "2EW5dVhaTYylOJZsgcc6jN8zA_wrKvL-";
// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "Wokwi-GUEST";
char pass[] = "";
void setup() {
Serial.begin(115200);
// Initialize traffic light pins as outputs
pinMode(redLight1, OUTPUT);
pinMode(yellowLight1, OUTPUT);
pinMode(greenLight1, OUTPUT);
pinMode(redLight2, OUTPUT);
pinMode(yellowLight2, OUTPUT);
pinMode(greenLight2, OUTPUT);
// Turn off all lights initially
allLightsOff();
// Initialize Blynk
Serial.println("Connecting to WiFi...");
Blynk.begin(auth, ssid, pass);
Serial.println("Connected to WiFi");
}
void loop() {
Blynk.run();
// Read distance from sensors
int distance1 = sensor1.ping_cm();
int distance2 = sensor2.ping_cm();
// Print sensor values to the Serial Monitor (for debugging)
Serial.print("Distance1: "); Serial.print(distance1); Serial.print(" cm, ");
Serial.print("Distance2: "); Serial.print(distance2); Serial.print(" cm, ");
// Send sensor values to Blynk
Blynk.virtualWrite(V2, distance1);
Blynk.virtualWrite(V16, distance2);
// Implement your logic here based on the sensor values
controlTrafficLights(distance1, distance2);
// Wait before repeating the loop
delay(1000);
}
void controlTrafficLights(int d1, int d2) {
// Example logic for controlling traffic lights based on sensor distance
// This is a very basic example, you can enhance it further as needed
// Reset all lights
allLightsOff();
// Simple logic to turn on green light if distance is less than threshold
if (d1 > 0 && d1 < 20) {
digitalWrite(greenLight1, HIGH);
} else {
digitalWrite(redLight1, HIGH);
}
if (d2 > 0 && d2 < 20) {
digitalWrite(greenLight2, HIGH);
} else {
digitalWrite(redLight2, HIGH);
}
}
void allLightsOff() {
digitalWrite(redLight1,LOW);
digitalWrite(yellowLight1,LOW);
digitalWrite(greenLight1,LOW);
digitalWrite(redLight2,LOW);
digitalWrite(yellowLight2,LOW);
digitalWrite(greenLight2,LOW);
}