#include <ESP8266WiFi.
h>
#include <PubSubClient.h>
// WiFi credentials
const char* ssid = "YOUR WIFI ID";
const char* password = "YOUR WIFI PASSWORD";
// MQTT Broker details
const char* mqtt_server = "[Link]"; // public broker
const int mqtt_port = 1883;
const char* mqtt_topic_sub = "nttf/led"; // topic to subscribe
const char* mqtt_topic_pub = "nttf/status"; // topic to publish
WiFiClient espClient;
PubSubClient client(espClient);
// Built-in LED on NodeMCU (D0 is not real LED, use LED_BUILTIN which is GPIO2)
const int ledPin = LED_BUILTIN;
void setup_wifi() {
delay(10);
[Link]();
[Link]("Connecting to ");
[Link](ssid);
[Link](ssid, password);
while ([Link]() != WL_CONNECTED) {
delay(1000);
[Link](".");
}
[Link]("");
[Link]("WiFi connected");
[Link]("IP address: ");
[Link]([Link]());
void callback(char* topic, byte* payload, unsigned int length) {
[Link]("Message arrived [");
[Link](topic);
[Link]("] ");
String message;
for (unsigned int i = 0; i < length; i++) {
message += (char)payload[i];
[Link](message);
// Control LED based on message
if (message == "ON") {
digitalWrite(ledPin, LOW); // Active LOW LED
[Link](mqtt_topic_pub, "LED is ON");
} else if (message == "OFF") {
digitalWrite(ledPin, HIGH); // Active LOW LED
[Link](mqtt_topic_pub, "LED is OFF");
void reconnect() {
// Loop until reconnected
while (![Link]()) {
[Link]("Attempting MQTT connection...");
// Create a random client ID
String clientId = "NodeMCUClient-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if ([Link](clientId.c_str())) {
[Link]("connected");
[Link](mqtt_topic_sub); // subscribe to topic
} else {
[Link]("failed, rc=");
[Link]([Link]());
[Link](" try again in 5 seconds");
delay(5000);
void setup() {
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, HIGH); // OFF at start (because built-in LED is active LOW)
[Link](115200);
setup_wifi();
[Link](mqtt_server, mqtt_port);
[Link](callback);
void loop() {
if (![Link]()) {
reconnect();
}
[Link]();