#include <WiFi.h>
#include <PubSubClient.h>
const char *mqttServer = "broker.hivemq.com";
const int mqttPort = 1883;
WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);
// Change "std1" to your unique student ID
const char *topicLWT = "np/std1/device/lwt";
const char *topicLed1 = "np/std1/led1";
const char *topicLed2 = "np/std1/led2";
const char *topicAll = "np/std1/all";
void reconnect() {
while (!mqttClient.connected()) {
Serial.printf("Attempting MQTT connection %s...",
mqttServer);
String clientID = "np25" + String(random(0xffff), HEX);
if (mqttClient.connect(clientID.c_str(),
topicLWT, 1, true, "offline")) {
Serial.printf("connected\n");
mqttClient.publish(topicLWT, "online", true);
mqttClient.subscribe(topicLed1);
mqttClient.subscribe(topicLed2);
mqttClient.subscribe(topicAll);
Serial.println("Subscribed to LED control topics");
}
else {
Serial.printf("failed, rc=%d. Retring again in 5s ...\n",
mqttClient.state());
delay(5000);
}
}
}
void callback(char *topic, byte *payload, unsigned int length) {
// Debug
Serial.print("Received: [");
Serial.print(topic);
Serial.print("]: ");
Serial.write(payload, length);
Serial.println();
if (strcmp(topic, topicLed1) == 0) {
if (length == 2 && memcmp(payload, "ON", 2) == 0) {
digitalWrite(13, HIGH);
}
else if (length == 3 && memcmp(payload, "OFF", 3) == 0) {
digitalWrite(13, LOW);
}
}
else if (strcmp(topic, topicLed2) == 0) {
if (length == 2 && memcmp(payload, "ON", 2) == 0) {
digitalWrite(12, HIGH);
}
else if (length == 3 && memcmp(payload, "OFF", 3) == 0) {
digitalWrite(12, LOW);
}
}
else if (strcmp(topic, topicAll) == 0) {
if (length == 2 && memcmp(payload, "ON", 2) == 0) {
digitalWrite(13, HIGH);
digitalWrite(12, HIGH);
}
else if (length == 3 && memcmp(payload, "OFF", 3) == 0) {
digitalWrite(13, LOW);
digitalWrite(12, LOW);
}
}
}
void setup() {
Serial.begin(115200);
Serial.println("7.3 LED Control via Subscription");
pinMode(13, OUTPUT); // LED1
pinMode(12, OUTPUT); // LED2
digitalWrite(13, LOW); // Preset LOW
digitalWrite(12, LOW); // Preset LOW
WiFi.mode(WIFI_STA);
WiFi.begin("Wokwi-GUEST", "");
WiFi.setAutoReconnect(true);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.printf("\nConnected! IP: %s\n",
WiFi.localIP().toString().c_str());
mqttClient.setServer(mqttServer, mqttPort);
mqttClient.setCallback(callback);
}
void loop() {
if (!mqttClient.connected()) {
reconnect();
}
mqttClient.loop(); // Needed for keep-alive
// delay(10);
}
LED1
LED2