#include <PubSubClient.h>
// WiFi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// MQTT broker settings
const char* mqtt_server = "your-mqtt-broker-ip"; // Ganti dengan alamat IP broker MQTT Anda
const int mqtt_port = 1883;
// MQTT topics for controlling LEDs
const char* topic_led1 = "home/led1";
const char* topic_led2 = "home/led2";
const char* topic_led3 = "home/led3";
// Pins for LEDs
const int led1_pin = 15;
const int led2_pin = 18;
const int led3_pin = 19;
// WiFi client and MQTT client
WiFiClient espClient;
PubSubClient client(espClient);
// Callback function for receiving MQTT messages
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message received on topic: ");
Serial.println(topic);
// Convert the payload to a string
String message = "";
for (int i = 0; i < length; i++) {
message += (char)payload[i];
}
// Check which LED to control based on the received topic
if (strcmp(topic, topic_led1) == 0) {
if (message.equals("ON")) {
digitalWrite(led1_pin, HIGH);
} else if (message.equals("OFF")) {
digitalWrite(led1_pin, LOW);
}
} else if (strcmp(topic, topic_led2) == 0) {
if (message.equals("ON")) {
digitalWrite(led2_pin, HIGH);
} else if (message.equals("OFF")) {
digitalWrite(led2_pin, LOW);
}
} else if (strcmp(topic, topic_led3) == 0) {
if (message.equals("ON")) {
digitalWrite(led3_pin, HIGH);
} else if (message.equals("OFF")) {
digitalWrite(led3_pin, LOW);
}
}
}
void setup() {
Serial.begin(115200);
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Connect to MQTT broker
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
// Configure LED pins as outputs
pinMode(15, OUTPUT);
pinMode(18, OUTPUT);
pinMode(19, OUTPUT);
}
void loop() {
// Reconnect to MQTT broker if connection is lost
if (!client.connected()) {
Serial.println("Reconnecting to MQTT broker...");
while (!client.connected()) {
if (client.connect("ESP8266Client")) {
Serial.println("Connected to MQTT broker");
client.subscribe(home/led1);
client.subscribe(home/led2);
client.subscribe(home/led3);
} else {
delay(500);
}
}
}
// Handle MQTT messages
client.loop();
}
}