#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <WiFi.h>
#include <PubSubClient.h>
#define LDR_PIN 12
#define LED 2
const char *ssid = "Wokwi-GUEST";
const char *password = "";
const char *mqtt_server = "broker.emqx.io";
const int mqtt_port = 1883;
const char *mqtt_topic = "ldr_status";
WiFiClient espClient;
PubSubClient client(espClient);
LiquidCrystal_I2C lcd(0x27, 20, 4);
void setup() {
pinMode(LDR_PIN, INPUT);
pinMode(LED, OUTPUT);
Serial.begin(115200);
setup_wifi();
lcd.init();
lcd.backlight();
client.setServer(mqtt_server, mqtt_port);
}
void loop() {
lcd.setCursor(0, 0);
lcd.print("Continer: ");
if (digitalRead(LDR_PIN) == LOW) {
digitalWrite(LED, HIGH);
delay(1000);
lcd.print("Light!");
sendMqttMessage("Warning...! Sunlight Detected..");
} else {
lcd.print("Dark ");
sendMqttMessage("No SunLight Detected");
digitalWrite(LED, LOW);
delay(1000);
}
delay(100);
}
void setup_wifi() {
delay(10);
// Connect to Wi-Fi
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
}
void sendMqttMessage(const char *message) {
if (!client.connected()) {
reconnect();
}
client.loop();
client.publish(mqtt_topic, message);
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP32Client")) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
// #include <LiquidCrystal_I2C.h>
// #define LDR_PIN 12
// LiquidCrystal_I2C lcd(0x27, 16, 2);
// void setup() {
// pinMode(LDR_PIN, INPUT);
// lcd.init();
// lcd.backlight();
// }
// void loop() {
// lcd.setCursor(2, 0);
// lcd.print("Room: ");
// if (digitalRead(LDR_PIN) == LOW) {
// lcd.print("Light!");
// } else {
// lcd.print("Dark ");
// }
// delay(100);
// }