Smart Light Control with ESP32 and MQTT
11.12.2024 - Engine: Gemini

Smart Light Control with ESP32 and MQTT
Components
- ESP32 module
- LED strip
- Relay
- MOSFET
- MQTT broker (e.g., Mosquitto)
Programming
Step 1: Set up ESP32
Connect the ESP32 to your computer and download the Arduino IDE. Install the ESP32 library from the Arduino IDE manager.
Step 2: Add MQTT Library
Add the MQTT library to the project, such as the PubSubClient library.
Step 3: Connect to MQTT Broker
Establish a connection to the MQTT broker and configure the topics to be used.
Step 4: Control LEDs
Use the digitalWrite()
function to control the LEDs via the relay and MOSFET.
Step 5: Subscribe to MQTT Messages
Subscribe to the MQTT topics which will be used to control the LEDs.
Step 6: Process Messages
Process the received MQTT messages and control the LEDs accordingly.
Sample Code
#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "Your_WiFi_Name";
const char* password = "Your_WiFi_Password";
const char* mqtt_broker = "mqtt.example.com";
const int mqtt_port = 1883;
const char* topic = "home/lights";
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("WiFi connected");
client.setServer(mqtt_broker, mqtt_port);
}
void loop() {
if (!client.connected()) {
Serial.print("Connecting to MQTT broker...");
while (!client.connected()) {
if (client.connect("ESP32-Light")) {
Serial.println("connected");
client.subscribe(topic);
} else {
Serial.print(".");
delay(1000);
}
}
}
client.loop();
}
void callback(char* topic, byte* payload, unsigned int length) {
String message = String((char*)payload);
if (message == "ON") {
digitalWrite(LED_PIN, HIGH);
} else if (message == "OFF") {
digitalWrite(LED_PIN, LOW);
}
}