// Create an MQTT Connection
// TCP Connection
// import the WiFi and PubSubClient libraries
//The WiFi library allows ESP32 to establish connections with Wi-Fi networks
//The PubSubClient library enables ESP32 to connect to an MQTT broker for publishing messages and subscribing to topics.
#include <WiFi.h>
#include "PubSubClient.h"
// WiFi
char ssid[]="Wokwi-GUEST";
char pass[]="";
// MQTT Broker
const char *mqtt_broker = "mqtt-dashboard.com";//Public Broker
const char *mqtt_username = "taha.toplu";
const char *mqtt_password = "tahayunus123";
const int mqtt_port = 1883;
// App Protcol ---> Port
const char *topic_publish = "traffic/light";//Topic ESP32 Pusblish
const char *topic_subsrcibe = "traffic/light";//Topic ESp32 Subs
WiFiClient espClient;//WIFI Opject
PubSubClient client(espClient);
const int red_pin = 2;
const int yellow_pin = 4;
const int green_pin = 5;
const int red_pin_two = 14;
const int yellow_pin_two = 13;
const int green_pin_two = 12;
int state = 0;
// Timing variables
unsigned long previousMillis = 0;
const long interval = 2000; // 2 seconds for each light
enum TrafficLightState {
RED,
YELLOW,
GREEN
};
TrafficLightState currentState = RED;
void callback(char *topic, byte *payload, unsigned int length);
void setTrafficLight(TrafficLightState state);
void switchTrafficLight();
void setup(){
// Setting LED pin as output
set_pins();
//Open a serial connection to display program results and establish a connection to the Wi-Fi network.
// Set software serial baud to 115200;
Serial.begin(115200);
// Connecting to a Wi-Fi network
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the Wi-Fi network");
// Utilize PubSubClient to establish a connection with the MQTT broker.
//connecting to a mqtt broker
Serial.println("Before Connect MQTT");
//Broker Configuration
client.setServer(mqtt_broker, mqtt_port);
client.setCallback(callback);
while (!client.connected()) {
String client_id = "esp32-client-";
client_id += String(WiFi.macAddress());
//ESP32-ID -----> esp32-client-macaddress
//variable.c_str()--->char [] , String
Serial.printf("The client %s connects to the public MQTT broker\n", client_id.c_str());
if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
Serial.println("Public MQTT broker connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
Serial.println("After Connect MQTT");
client.publish(topic_publish, "Hi, I'm ESP32 ^^");
client.subscribe(topic_subsrcibe);
}
void set_pins(){
// Set pin modes and initialize the LEDs to be off for the first traffic light
pinMode(red_pin, OUTPUT);
pinMode(yellow_pin, OUTPUT);
pinMode(green_pin, OUTPUT);
digitalWrite(red_pin, HIGH);
digitalWrite(yellow_pin, LOW);
digitalWrite(green_pin, LOW);
// Set pin modes and initialize the LEDs to be off for the fourth traffic light
pinMode(red_pin_two, OUTPUT);
pinMode(yellow_pin_two, OUTPUT);
pinMode(green_pin_two, OUTPUT);
digitalWrite(red_pin_two, HIGH);
digitalWrite(yellow_pin_two, LOW);
digitalWrite(green_pin_two, LOW);
}
void loop() {
if (!client.connected()) {
reconnectMQTT();
}
client.loop();
static unsigned long lastSwitchTime = 0;
if (millis() - lastSwitchTime >= interval) { // Switch every 2 seconds
lastSwitchTime = millis();
switch (state) {
case 0:
setTrafficLights(red_pin, yellow_pin, green_pin, HIGH, LOW, LOW); // Red
setTrafficLights(red_pin_two, yellow_pin_two, green_pin_two, LOW, HIGH, LOW); // Yellow
state = 1;
break;
case 1:
setTrafficLights(red_pin, yellow_pin, green_pin, HIGH, LOW, LOW); // Red
setTrafficLights(red_pin_two, yellow_pin_two, green_pin_two, LOW, LOW, HIGH); // Green
state = 2;
break;
case 2:
setTrafficLights(red_pin, yellow_pin, green_pin, HIGH, LOW, LOW); // RED
setTrafficLights(red_pin_two, yellow_pin_two, green_pin_two, LOW, HIGH, LOW); // Yellow
state = 3;
break;
case 3:
setTrafficLights(red_pin, yellow_pin, green_pin, LOW, HIGH, LOW); // YELLOW
setTrafficLights(red_pin_two, yellow_pin_two, green_pin_two, HIGH, LOW, LOW); // RED
state = 4;
break;
case 4:
setTrafficLights(red_pin, yellow_pin, green_pin, LOW, LOW, HIGH); // Green
setTrafficLights(red_pin_two, yellow_pin_two, green_pin_two, HIGH, LOW, LOW); // Red
state = 5;
break;
case 5:
setTrafficLights(red_pin, yellow_pin, green_pin, LOW, HIGH, LOW); // YELLOW
setTrafficLights(red_pin_two, yellow_pin_two, green_pin_two, HIGH, LOW, LOW); // Red
state = 0;
break;
}
}
}
void reconnectMQTT() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
String client_id = "esp32-client-";
client_id += String(WiFi.macAddress());
if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
Serial.println("connected");
// Subscribe to topic
client.subscribe(topic_subsrcibe);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void callback(char *topic, byte *payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
String message = "";
for (int i = 0; i < length; i++) {
message += (char)payload[i];
}
if (message == "FIRST") {
state = 1;
setTrafficLights(red_pin, yellow_pin, green_pin, HIGH, LOW, LOW); // Red
setTrafficLights(red_pin_two, yellow_pin_two, green_pin_two, LOW, LOW, HIGH); // GREEN
} else if (message == "SECOND") {
state = 4;
setTrafficLights(red_pin, yellow_pin, green_pin, LOW, LOW, HIGH); // Green
setTrafficLights(red_pin_two, yellow_pin_two, green_pin_two, HIGH, LOW, LOW); // Red
}
Serial.println();
Serial.println("-----------------------");
}
void setTrafficLights(int redPin, int yellowPin, int greenPin, bool redState, bool yellowState, bool greenState) {
digitalWrite(redPin, redState);
digitalWrite(yellowPin, yellowState);
digitalWrite(greenPin, greenState);
}