WEB MQTT – NodeMCU / ESP8266

The following video will shows how to control nodeMCU / ESP8266 with MQTT messages. In this first example I will control the builtin LED of the module with mqtt messages. The messages ar sent from the dashboard with buttons and a switch with pre-defined “on” and “off” messages.

https://rundebugrepeat.com/webmqtt/

WEB MQTT- control NodeMCU / ESP8266

source code for the arduino code:

/*
  Basic ESP8266 / NodeMCU MQTT example using the pubsub client library
  In this example the nodemcu /esp8266 connect to an mqtt server broker
  After the client connected the client subscribe to a topic
  If an ON message is arrive to the topic, the module turn on it's built in LED
  if an off message is arrived the LED turn off
  the digitalWrite method of the builtin led is reversed, because the ligh is turned on, if the output is set to low state.

 To install the ESP8266 board, (using Arduino 1.6.4+):
  - Add the following 3rd party board manager under "File -> Preferences -> Additional Boards Manager URLs":
       http://arduino.esp8266.com/stable/package_esp8266com_index.json
  - Open the "Tools -> Board -> Board Manager" and click install for the ESP8266"
  - Select your ESP8266 in "Tools -> Board"

*/

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

// Update these with values suitable for your network.

const char* ssid = "................."; //Wifi SSID
const char* password = "............."; //WIFI password
const char* mqtt_server = "mqtt.eclipse.org"; //MQTT Broker address
const int mqtt_port = 1883; //MQTT broker port

WiFiClient espClient;
PubSubClient client(espClient);

void setup_wifi() {

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

  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("]: ");
  char message[length];
  for (int i=0; i< length; i++){
    message[i] = (char)payload[i];
  }
  Serial.println(message);

  //Use strcmp to compare the payload with the desired strings to controll the builtin led of nodemcu
  //for more information about strcmp fucntion:
  //http://www.cplusplus.com/reference/cstring/strcmp/
  if(!strncmp((char *) payload, "ON", length)){
    digitalWrite(BUILTIN_LED, LOW);
  }
  if(!strncmp((char *) payload, "OFF", length)){
    digitalWrite(BUILTIN_LED, 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!");
      //subscribe to the test topic to control the builtin LED of the nodemcu
      client.subscribe("rundebugrepeat/test/LED1");
    } 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, mqtt_port);
  client.setCallback(callback);
}

void loop() {

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

}

Leave a Reply

Your email address will not be published. Required fields are marked *