#include <WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// WiFi credentials
const char* ssid = "Wokwi-GUEST"; // Change this to your WiFi network name
const char* password = ""; // Change this to your WiFi network password
// MQTT Broker details
const char* mqtt_server = "broker.hivemq.com";
const int mqtt_port = 1883;
const char* mqtt_topic = "worker_temperature01";
// LCD I2C address and dimensions
LiquidCrystal_I2C lcd(0x27, 16, 2); // Change 0x27 to your LCD's I2C address
// LED Pin
const int ledPin = 2;
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
Serial.println("Connecting to WiFi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi Connected.");
}
void flashLED(int pin, int times, int delayTime) {
for (int i = 0; i < times; i++) {
digitalWrite(pin, HIGH);
delay(delayTime);
digitalWrite(pin, LOW);
delay(delayTime);
}
}
void mqtt_callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
char msg[length + 1];
for (unsigned int i = 0; i < length; i++) {
msg[i] = (char)payload[i];
}
msg[length] = '\0';
Serial.println(msg);
// Display on LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(msg);
lcd.print(" C");
// Check temperature and flash LED if higher than 40 degrees
float temperature = atof(msg);
if (temperature > 40.0) {
flashLED(ledPin, 5, 500); // Flash 5 times with 500ms interval
}
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("ESP32_LCD_Display")) {
Serial.println("connected");
client.subscribe(mqtt_topic);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, mqtt_port);
client.setCallback(mqtt_callback);
lcd.init(); // initialize the lcd
lcd.backlight();
pinMode(ledPin, OUTPUT); // Initialize the LED pin as an output
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}