How to Control LED with Publish/Subscribe MQTT IoT: 7 Step-by-Step Guide with Arduino IDE

How to Control LED with Publish/Subscribe MQTT IoT
2
0

Introduction

In this digital era, the Internet of Things (IoT) has become a powerful tool for connecting and controlling devices remotely. MQTT (Message Queuing Telemetry Transport) is a lightweight messaging protocol commonly used in IoT applications. In this blog post, we will explore how to control an LED using the publish/subscribe pattern with MQTT, using the Arduino IDE. Let’s get started!

Requirements

To follow along with this tutorial, you will need the following:

  1. NodeMCU
  2. LED and a resistor
  3. Breadboard and jumper wires
  4. MQTT broker (for this tutorial, we will use the public broker provided by mosquitto)
  5. Arduino IDE installed on your computer

Step 1: Set up the Arduino IDE

Ensure that you have the Arduino IDE installed on your computer. If not, download and install it from the official Arduino website (https://www.arduino.cc/en/software).

Step 2: Connect the Circuit

Connect the LED to your NodeMCU as follows:

  • Connect the long leg (anode) of the LED to digital BUILTIN_LED of the NodeMCU.
  • Connect the short leg (cathode) of the LED to a current-limiting resistor (around 220-470 ohms).
  • Connect the other end of the resistor to the ground (GND) pin on the NodeMCU.

Step 3: Install Required Libraries

To work with MQTT in Arduino IDE, we need to install the “PubSubClient” library. Open the Arduino IDE, navigate to “Sketch” -> “Include Library” -> “Manage Libraries.” In the Library Manager, search for “PubSubClient” and install the library.

Step 4: Write the Arduino Code

Now, let’s write the Arduino code that controls the LED using MQTT. Open a new sketch in the Arduino IDE and enter the following code:

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.

const char* ssid = "YOUR_WIFI_SSID";
const char* password = "YOUR_WIFI_PASSWORD";
const char* mqtt_server = "test.mosquitto.org";

WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE	(50)
char msg[MSG_BUFFER_SIZE];
int value = 0;

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {
    digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is active low on the ESP-01)
  } else {
    digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
  }

}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("toMQTT", "hello world");
      // ... and resubscribe
      client.subscribe("fromMQTT");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void loop() {

  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  unsigned long now = millis();
  if (now - lastMsg > 2000) {
    lastMsg = now;
    ++value;
    snprintf (msg, MSG_BUFFER_SIZE, "hello world #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("toMQTT", msg);
  }
}

Make sure to replace “YOUR_WIFI_SSID” and “YOUR_WIFI_PASSWORD” with your Wi-Fi credentials.

Step 5: Upload the Code

Connect your Arduino board to your computer using a USB cable. Select the appropriate board and port from the “Tools” menu in the Arduino IDE. Then, click the “Upload” button to upload the code to your Arduino board.

Step 6: Testing

Open the Serial Monitor in the Arduino IDE (Tools -> Serial Monitor). Make sure the baud rate is set to 115200. You should see the messages indicating the connection to Wi-Fi and the MQTT broker. If everything is successful, you are ready to control the LED using MQTT.

Step 7: Publish MQTT Messages

To control the LED, you can use any MQTT client or a smartphone app that supports MQTT. Publish the messages “ON” or “OFF” to the topic “ledControl” on the MQTT broker. When you publish “ON”, the LED connected to the Arduino will turn on, and when you publish “OFF”, the LED will turn off.

How to Control LED with Publish/Subscribe MQTT IoT

Conclusion

Congratulations! You have successfully learned how to control an LED using the publish/subscribe pattern with MQTT and NodeMCU. This opens up endless possibilities for remote control and automation in your IoT projects. Feel free to explore more MQTT features and integrate additional sensors or actuators into your projects.

Remember to experiment safely and have fun exploring the world of IoT with MQTT and Arduino!

Note: It’s important to ensure proper safety precautions when working with electronic components. Double-check your connections and use appropriate resistors and power sources to avoid any damage or hazards.

Also, check out our other playlist Rasa ChatbotInternet of thingsDockerPython Programming, MQTT, etc.
Become a member of our social family on youtube here.

Stay tuned and Happy Learning. ✌🏻😃

Leave a Reply