#include <WiFi.h>
#include <MQTT.h>
// LDR and LED Pins
#define LDR_PIN 34 // ADC1 GPIO pin for LDR
#define LED_PIN 15 // GPIO pin for LED
bool ledState = LOW; // Tracks the current state of the LED
// WiFi Configuration
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// MQTT Configuration
const char* mqttServer = "mountainrat662.cloud.shiftr.io";
const char* mqttUser = "mountainrat662";
const char* mqttPassword = "b0X48fxDejD3HhdU";
const int mqttPort = 1883;
const char* topic = "esp32/ledStatus";
const char* willTopic = "esp32/status";
// Create MQTT client instance
WiFiClient net;
MQTTClient client(256);
void connectToWiFi() {
Serial.print("Connecting to WiFi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi connected!");
}
void connectToMQTT() {
Serial.print("Connecting to MQTT");
client.begin(mqttServer, mqttPort, net); // Set server and WiFi client
while (!client.connect("ESP32Client", mqttUser, mqttPassword)) { // Only pass clientID, user, and password
Serial.print(".");
delay(1000);
}
Serial.println("\nMQTT connected!");
client.publish(willTopic, "Online", true); // Publish online status with retain flag
}
void setup() {
pinMode(LED_PIN, OUTPUT); // Set LED pin as output
Serial.begin(115200); // Start Serial Monitor
connectToWiFi();
connectToMQTT();
}
void loop() {
if (!client.connected()) {
connectToMQTT(); // Reconnect to MQTT if disconnected
}
client.loop(); // Maintain MQTT connection
int ldrValue = analogRead(LDR_PIN); // Read LDR value from ADC1 pin
bool newLedState = (ldrValue <= 300) ? HIGH : LOW; // Determine new LED state
if (newLedState != ledState) { // Change the state only if it's different
ledState = newLedState; // Update the current state
digitalWrite(LED_PIN, ledState); // Apply the new state to the LED
// Print status to Serial Monitor
Serial.print("LDR Value: ");
Serial.print(ldrValue);
Serial.print(" | LED State: ");
Serial.println(ledState == HIGH ? "ON" : "OFF");
// Publish LED state to MQTT with retain flag
String ledStatus = ledState == HIGH ? "ON" : "OFF";
client.publish(topic, ledStatus.c_str(), true);
}
delay(100); // Small delay to avoid excessive polling
}