//AIM- Display current time in HH:MM (written in python) on seven seg- display on wokwi
//IMP- In Library Manager, add PubSubClient and Sevseg library too
#include "WiFi.h"
#include "PubSubClient.h" //to connect to MQTT server
#include "SevSeg.h" //library to display on seven segment display unit
char clientId[50]; // random id with storage of 50
int t; //time variable
SevSeg sevseg;
WiFiClient espClient;
PubSubClient client(espClient); //function to make client
void setup()
{
Serial.begin(115200); //starts communication with ESP32 with transfer rate(speed- 115200),
byte numDigits = 4;
byte digitPins[] = {14, 15, 2, 5}; // help us to control the 4 digits seven-segment display
byte segmentPins[] = {12, 4, 19, 26, 27, 13, 18, 25}; //will help us to control all seven LEDs and the Decimal Point of seven-segment display.
byte hardwareConfig = COMMON_ANODE; // used to set the pins of display in positive mode of ESP32
sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins);
WiFi.mode(WIFI_STA); //search a WiFi station where ESP32 connects
WiFi.begin("Wokwi-GUEST", "");
client.setServer("broker.emqx.io", 1883);
client.setCallback(callback); //function written below
}
void loop()
{
if (!client.connected())
{
mqttReconnect();
}
client.loop();
sevseg.setNumber(t); //set time received from python file to display om sevSeg Display
sevseg.refreshDisplay();
delay(1);
}
void mqttReconnect()
{
while (!client.connected())
{
Serial.print("Attempting MQTT connection...");
if (client.connect(clientId))
{
Serial.println("Connected");
client.subscribe("topicName/time"); //receive message
}
else
{
Serial.println("Connection failed trying again in 10 seconds");
delay(5000);
}
}
}
void callback(char* topic, byte* message, unsigned int length)
{
String stMessage; //variable
for (int i = 0; i < length; i++)
{
stMessage += (char)message[i]; //holds whole message or time (HH:MM)
}
Serial.println(stMessage);
t = stMessage.toInt(); //converts time
}
//OUTPUT- Run Python Then Run wokwi file to see output