Attempting Mqtt Connection failed Rc 2 Try Again in 5 Seconds Ethernet Shield Arduino

In this postal service nosotros're going to show you how to command ESP8266 outputs and display sensor data from the ESP8266 on Node-RED. The Node-RED software is running on a Raspberry Pi, and the communication between the ESP8266 and the Node-Reddish software is achieved with the MQTT advice protocol.

The following figure shows an overview of what we're going to do in this tutorial.

First, watch the video demonstration below

Node-RED and Node-RED Dashboard

You need to have Node-Reddish and Node-Scarlet Dashboard installed in your Raspberry Pi. The post-obit weblog posts are useful for getting started with Node-RED and Node-RED dashboard:

  • Getting started with Node-Red on Raspberry Pi
  • Getting Started with Node-Cherry Dashboard

MQTT Protocol

In this tutorial nosotros're going to plant a communication between a Raspberry Pi running the Node-Scarlet software and an ESP8266 using MQTT.

MQTT stands forMQ TelemetryTransport and it is a prissy lightweight publish and subscribe system where y'all can publish and receive letters as a client. Information technology is a simple messaging protocol, designed for constrained devices and with low-bandwidth. So, information technology's the perfect solution for Internet of Things applications.

If you want to learn more about MQTT, watch the video below.

For a written version of this video and additional resources, read this blog post What is MQTT and How It Works.

Installing Mosquitto Broker

In MQTT, the banker is primarily responsible forreceiving all messages,filtering the messages,decide who is interested in information technology and and sopublishing the message to all subscribed clients.

There are several brokers you can use. In this tutorial nosotros're going to use theMosquitto Banker which needs to exist installed on Raspberry Pi.

To install the Mosquitto banker on Raspberry Pi follow this tutorial: How to Install Mosquitto Banker on Raspberry Pi.

Testing

To come across if Mosquitto broker was successfully installed, run the next command:

[electronic mail protected]:~ $          mosquitto -v        

This returns the Mosquitto version that is currently running in your Raspberry Pi. It should be ane.4 or higher up.

Note: the Mosquitto command returns the Mosquitto version that is currently installed, merely it as well tries to initialize Mosquitto again. Since Mosquitto is already running it prompts an error bulletin. Don't worry Mosquitto is properly installed and running if you meet a similar message.

Establishing an MQTT communication with Node-RED

In this section we're going to establish an MQTT communication using the Node-Red nodes.

Dashboard Layout

The first step is to create the dashboard layout. In this example, we'll have a button to control an ESP8266 output; a chart and a guess to brandish temperature and humidity readings from the DHT11 sensor.

On the superlative right corner of the Node-Red window, select theLayout tab under thedashboardtab. Create a tab calledRoom and inside the Room tab, create two groups: Lamp andSensor as shown in figure below.

Creating the Menstruation

Drag the following nodes to the flow – meet figure below:

  • switch – this volition control the ESP8266 output
  • mqtt output node – this will publish a message to the ESP8266 accordingly to the switch state
  • 2xmqtt input nodes – this nodes volition be subscribed to the temperature and humidity topics to receive sensor data from the ESP
  • nautical chart – volition display the temperature sensor readings
  • gauge – will brandish the humidity sensor readings

Node-Cherry-red and the MQTT broker need to exist continued. To connect the MQTT broker to Node-REd, double-click the MQTT output node. A new window pops up – as shown in figure below.

  1. Click the Add new mqtt-broker pick.
  2. Type localhost in the server field
  3. All the other settings are configured properly by default.
  4. Press Add together and the MQTT output node automatically connects to your broker.

Edit all the other nodes properties as shown in the post-obit figures:

Wire your nodes as shown in the figure below.

Your Node-Scarlet application is fix. Click theDeploy button on the top right corner.

The Node-RED application is fix. To come across how your dashboard looks go to http://your-pi-ip-address/ui .

Now, follow the next sections to set your ESP8266.

Preparing your Arduino IDE

We'll programme the ESP8266 using the Arduino IDE. In gild to upload code to your ESP8266 using the Arduino IDE, y'all need to install the ESP8266 add-on (How to Install the ESP8266 Lath in Arduino IDE). You'll also demand to install two boosted libraries to have everything ready for your ESP8266.

Installing the PubSubClient Library

The PubSubClient library provides a client for doing simple publish/subscribe messaging with a server that supports MQTT (basically allows your ESP8266 to talk with Node-Scarlet).

i) Click here to download the PubSubClient library. You should accept a .zip folder in your Downloads binder

2) Unzip the .zip binder and you should go pubsubclient-primary folder

3) Rename your folder from pubsubclient-master to pubsubclient

4) Move the pubsubclient folder to your Arduino IDE installation libraries folder

v) And then, re-open your Arduino IDE

The library comes with a number of example sketches. Meet File >Examples > PubSubClient within the Arduino IDE software.

Installing the DHT Sensor Library

The DHT sensor library provides an easy mode of using any DHT sensor to read temperature and humidity with your ESP8266 or Arduino boards.

ane) Click here to download the DHT sensor library. Yous should have a.goose egg binder in your Downloads

2) Unzip the.zip folder and y'all should getDHT-sensor-library-mainfolder

3) Rename your folder from DHT-sensor-library-main  to DHT

4) Move theDHTfolder to your Arduino IDE installationlibrariesbinder

5) And so re-open up your Arduino IDE

For more than information almost the DHT11 sensor and the ESP8266, read ESP8266 DHT11/DHT22 Temperature and Humidity Spider web Server with Arduino IDE.

Selecting the right lath on Arduino IDE

Yous also need to select the correct board on Arduino IDE:

i) Go to Tools and select "NodeMCU 1.0 (ESP-12E Module)".

2) Select your ESP port number under the Tools > Port > COM4 (in my case)

Uploading code

At present, y'all tin upload the following code to your ESP8266. This lawmaking publishes messages of the temperature and humidity from the DHT11 sensor on the room/temperature and room/humidity topics trough MQTT protocol.

The ESP is subscribed to the room/lamp topic to receive the messages published on that topic by the Node-RED awarding, to plow the lamp on or off.

The code is well commented on where you need to make changes. Yous need to edit the code with your ain SSID, password and RPi IP address.

This code is also compatible with other DHT sensors – you merely need to uncomment and comment the right lines of lawmaking to chose your sensor.

          /*****    All the resources for this project:  https://randomnerdtutorials.com/   *****/  #include <ESP8266WiFi.h> #include <PubSubClient.h> #include "DHT.h"  // Uncomment ane of the lines blare for whatever DHT sensor type you're using! #define DHTTYPE DHT11   // DHT xi //#ascertain DHTTYPE DHT21   // DHT 21 (AM2301) //#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321  // Change the credentials below, so your ESP8266 connects to your router const char* ssid = "REPLACE_WITH_YOUR_SSID"; const char* password = "REPLACE_WITH_YOUR_PASSWORD";  // Change the variable to your Raspberry Pi IP address, so it connects to your MQTT broker const char* mqtt_server = "REPLACE_WITH_YOUR_RPI_IP_ADDRESS";  // Initializes the espClient. Y'all should change the espClient proper noun if you accept multiple ESPs running in your home automation system WiFiClient espClient; PubSubClient client(espClient);  // DHT Sensor - GPIO 5 = D1 on ESP-12E NodeMCU board const int DHTPin = 5;  // Lamp - LED - GPIO 4 = D2 on ESP-12E NodeMCU board const int lamp = 4;  // Initialize DHT sensor. DHT dht(DHTPin, DHTTYPE);  // Timers auxiliar variables long now = millis(); long lastMeasure = 0;  // Don't change the function below. This functions connects your ESP8266 to your router void setup_wifi() {   delay(10);   // We offset by connecting to a WiFi network   Serial.println();   Serial.print("Connecting to ");   Serial.println(ssid);   WiFi.begin(ssid, countersign);   while (WiFi.status() != WL_CONNECTED) {     filibuster(500);     Series.print(".");   }   Serial.println("");   Serial.print("WiFi connected - ESP IP address: ");   Serial.println(WiFi.localIP()); }  // This functions is executed when some device publishes a message to a topic that your ESP8266 is subscribed to // Change the part below to add together logic to your programme, and then when a device publishes a message to a topic that  // your ESP8266 is subscribed y'all tin can really practise something void callback(Cord topic, byte* message, unsigned int length) {   Serial.print("Message arrived on topic: ");   Serial.print(topic);   Serial.print(". Message: ");   String messageTemp;      for (int i = 0; i < length; i++) {     Serial.print((char)bulletin[i]);     messageTemp += (char)bulletin[i];   }   Serial.println();    // Feel free to add more than if statements to control more GPIOs with MQTT    // If a message is received on the topic room/lamp, yous check if the bulletin is either on or off. Turns the lamp GPIO according to the message   if(topic=="room/lamp"){       Serial.impress("Irresolute Room lamp to ");       if(messageTemp == "on"){         digitalWrite(lamp, Loftier);         Serial.print("On");       }       else if(messageTemp == "off"){         digitalWrite(lamp, Depression);         Serial.print("Off");       }   }   Series.println(); }  // This functions reconnects your ESP8266 to your MQTT broker // Change the part below if you want to subscribe to more topics with your ESP8266  void reconnect() {   // Loop until we're reconnected   while (!customer.connected()) {     Serial.impress("Attempting MQTT connection...");     // Attempt to connect     /*      YOU MIGHT NEED TO Alter THIS LINE, IF YOU'RE HAVING Problems WITH MQTT MULTIPLE CONNECTIONS      To change the ESP device ID, yous will have to give a new name to the ESP8266.      Here's how information technology looks:        if (client.connect("ESP8266Client")) {      Y'all can do it similar this:        if (customer.connect("ESP1_Office")) {      Then, for the other ESP:        if (customer.connect("ESP2_Garage")) {       That should solve your MQTT multiple connections problem     */     if (client.connect("ESP8266Client")) {       Serial.println("connected");         // Subscribe or resubscribe to a topic       // You can subscribe to more than topics (to control more LEDs in this case)       client.subscribe("room/lamp");     } else {       Series.print("failed, rc=");       Serial.print(client.state());       Serial.println(" endeavor again in 5 seconds");       // Wait v seconds before retrying       delay(5000);     }   } }  // The setup function sets your ESP GPIOs to Outputs, starts the serial communication at a baud charge per unit of 115200 // Sets your mqtt banker and sets the callback function // The callback office is what receives messages and actually controls the LEDs void setup() {   pinMode(lamp, OUTPUT);      dht.begin();      Series.brainstorm(115200);   setup_wifi();   customer.setServer(mqtt_server, 1883);   client.setCallback(callback);  }  // For this projection, you don't demand to modify anything in the loop function. Basically it ensures that you ESP is connected to your broker void loop() {    if (!client.continued()) {     reconnect();   }   if(!client.loop())     client.connect("ESP8266Client");    now = millis();   // Publishes new temperature and humidity every 30 seconds   if (now - lastMeasure > 30000) {     lastMeasure = now;     // Sensor readings may also be upwards to 2 seconds 'old' (its a very slow sensor)     float h = dht.readHumidity();     // Read temperature equally Celsius (the default)     bladder t = dht.readTemperature();     // Read temperature equally Fahrenheit (isFahrenheit = truthful)     bladder f = dht.readTemperature(true);      // Check if whatever reads failed and exit early (to try again).     if (isnan(h) || isnan(t) || isnan(f)) {       Series.println("Failed to read from DHT sensor!");       return;     }      // Computes temperature values in Celsius     bladder hic = dht.computeHeatIndex(t, h, false);     static char temperatureTemp[seven];     dtostrf(hic, 6, 2, temperatureTemp);          // Uncomment to compute temperature values in Fahrenheit      // bladder hif = dht.computeHeatIndex(f, h);     // static char temperatureTemp[7];     // dtostrf(hif, six, two, temperatureTemp);          static char humidityTemp[seven];     dtostrf(h, 6, 2, humidityTemp);      // Publishes Temperature and Humidity values     client.publish("room/temperature", temperatureTemp);     client.publish("room/humidity", humidityTemp);          Series.print("Humidity: ");     Series.print(h);     Serial.impress(" %\t Temperature: ");     Series.print(t);     Serial.print(" *C ");     Serial.impress(f);     Series.impress(" *F\t Heat index: ");     Serial.print(hic);     Series.println(" *C ");     // Serial.print(hif);     // Serial.println(" *F");   } }                  

View raw code

After uploading the code, and with the Raspberry Pi running your Node-Red application and the Mosquitto broker, you tin open the Arduino IDE serial monitor at a baud rate of 115200 and meet what's happening in real fourth dimension.

This is helpful to check if the ESP has established a successful connection to your router and to the Mosquitto broker. You can also see the messages the ESP is receiving and publishing.

Building the Circuit

The following sections testify y'all the needed parts and schematics to build the circuit for this project.

Parts required

These are the parts required to build the circuit (click the links below to detect the best price at Maker Counselor):

  • Raspberry Pi – read Best Raspberry Pi iii Starter Kits
  • ESP8266 (ESP-12E nodemcu) – read All-time ESP8266 Wi-Fi Development Boards
  • DHT11 temperature and humidity sensor
  • Breadboard
  • 330 Ω resistor
  • LED
  • 4700 Ω resistor

You can apply the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best cost!

Schematics

Here are the schematics for this projection's circuit.

Sit-in

Congratulations! You projection is now completed.

Become to http://your-pi-ip-address/ui to command the ESP with the  Node-Blood-red awarding. You can access your application in any browser on the same network that your Pi (watch the video demonstration below).

The application should look something the figure below.

Wrapping upward

In this tutorial we've shown y'all the bones concepts that volition let you lot to plow on lights and monitor sensors on your ESP using Node-Reddish and the MQTT advice protocol. You can follow these basic steps to build more advanced projects.

Nosotros hope you've plant this tutorial useful.

If you liked this projection and Home Automation make sure you cheque our class: Build a Abode Automation System for $100.

slagleungazintonat.blogspot.com

Source: https://randomnerdtutorials.com/esp8266-and-node-red-with-mqtt/

0 Response to "Attempting Mqtt Connection failed Rc 2 Try Again in 5 Seconds Ethernet Shield Arduino"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel