{"id":33293,"date":"2017-02-02T10:46:52","date_gmt":"2017-02-02T10:46:52","guid":{"rendered":"http:\/\/randomnerdtutorials.com\/?p=33293"},"modified":"2019-04-02T10:23:30","modified_gmt":"2019-04-02T10:23:30","slug":"raspberry-pi-publishing-mqtt-messages-to-esp8266","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/raspberry-pi-publishing-mqtt-messages-to-esp8266\/","title":{"rendered":"Raspberry Pi Publishing MQTT Messages to ESP8266"},"content":{"rendered":"<p>In this project you\u2019ll create a standalone web server with a Raspberry Pi that can toggle two LEDs from an ESP8266 using\u00a0MQTT protocol. You can replace those LEDs with any output (like a relay that controls a lamp).<!--more--><\/p>\n<p>In order to create the web server you will be using a Python microframework called Flask. Here&#8217;s the high level overview of the system:<\/p>\n<p><a href=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/Raspberry-Pi-Publishing-MQTT-Messages-to-ESP8266-explained.png?quality=100&#038;strip=all&#038;ssl=1\" target=\"_blank\" rel=\"noopener noreferrer\"><img data-recalc-dims=\"1\" fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter wp-image-33295 size-full\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/Raspberry-Pi-Publishing-MQTT-Messages-to-ESP8266-explained.png?resize=1032%2C268&#038;quality=100&#038;strip=all&#038;ssl=1\" width=\"1032\" height=\"268\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/Raspberry-Pi-Publishing-MQTT-Messages-to-ESP8266-explained.png?w=1032&amp;quality=100&amp;strip=all&amp;ssl=1 1032w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/Raspberry-Pi-Publishing-MQTT-Messages-to-ESP8266-explained.png?resize=150%2C39&amp;quality=100&amp;strip=all&amp;ssl=1 150w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/Raspberry-Pi-Publishing-MQTT-Messages-to-ESP8266-explained.png?resize=300%2C78&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/Raspberry-Pi-Publishing-MQTT-Messages-to-ESP8266-explained.png?resize=768%2C199&amp;quality=100&amp;strip=all&amp;ssl=1 768w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/Raspberry-Pi-Publishing-MQTT-Messages-to-ESP8266-explained.png?resize=1024%2C266&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/Raspberry-Pi-Publishing-MQTT-Messages-to-ESP8266-explained.png?resize=80%2C21&amp;quality=100&amp;strip=all&amp;ssl=1 80w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/Raspberry-Pi-Publishing-MQTT-Messages-to-ESP8266-explained.png?resize=220%2C57&amp;quality=100&amp;strip=all&amp;ssl=1 220w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/Raspberry-Pi-Publishing-MQTT-Messages-to-ESP8266-explained.png?resize=250%2C65&amp;quality=100&amp;strip=all&amp;ssl=1 250w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/Raspberry-Pi-Publishing-MQTT-Messages-to-ESP8266-explained.png?resize=280%2C73&amp;quality=100&amp;strip=all&amp;ssl=1 280w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/Raspberry-Pi-Publishing-MQTT-Messages-to-ESP8266-explained.png?resize=510%2C132&amp;quality=100&amp;strip=all&amp;ssl=1 510w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/Raspberry-Pi-Publishing-MQTT-Messages-to-ESP8266-explained.png?resize=750%2C195&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/Raspberry-Pi-Publishing-MQTT-Messages-to-ESP8266-explained.png?resize=975%2C253&amp;quality=100&amp;strip=all&amp;ssl=1 975w\" sizes=\"(max-width: 1032px) 100vw, 1032px\" \/><\/a><\/p>\n<h2>First, watch the video demonstration<\/h2>\n<p style=\"text-align:center\"><iframe width=\"720\" height=\"405\" src=\"https:\/\/www.youtube.com\/embed\/X04yaaydjFo?rel=0\" frameborder=\"0\" allowfullscreen><\/iframe><\/p>\n<p><strong>Recommended resources:<\/strong><\/p>\n<ul>\n<li>You need a\u00a0<a href=\"https:\/\/makeradvisor.com\/raspberry-pi-board\/\" target=\"_blank\" rel=\"noopener noreferrer\">Raspberry Pi board<\/a>\u00a0\u2013 read\u00a0<a href=\"https:\/\/makeradvisor.com\/best-raspberry-pi-3-starter-kits\/\" target=\"_blank\" rel=\"noopener noreferrer\">Best Raspberry Pi Starter Kits<\/a><\/li>\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-web-server-using-flask-to-control-gpios\/\">Raspberry Pi Web Server using Flask to Control GPIOs<\/a><\/li>\n<li><a href=\"https:\/\/randomnerdtutorials.com\/testing-mosquitto-broker-and-client-on-raspbbery-pi\/\">Testing Mosquitto Broker and Client on Raspbbery Pi<\/a><\/li>\n<li><a href=\"https:\/\/randomnerdtutorials.com\/how-to-install-mosquitto-broker-on-raspberry-pi\/\">How to Install Mosquitto Broker on Raspberry Pi<\/a><\/li>\n<li><a href=\"https:\/\/randomnerdtutorials.com\/what-is-mqtt-and-how-it-works\/\">What is MQTT and How It Works<\/a><\/li>\n<li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-with-node-red-on-raspberry-pi\/\">Getting Started with Node-RED on Raspberry Pi<\/a><\/li>\n<\/ul>\n<p>If you like home automation and you want to build a complete home automation system, I recommend downloading my <a href=\"https:\/\/randomnerdtutorials.com\/build-a-home-automation-system-for-100\/\">home automation course<\/a>.<\/p>\n<h2>Basic Raspberry Pi Setup<\/h2>\n<p>Before you continue reading this project, please\u00a0make sure you have Raspbian Operating System installed in your Raspberry Pi.<\/p>\n<p>You can read my <strong><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-with-raspberry-pi\/\">Getting Started with the Raspberry Pi Guide<\/a><\/strong>\u00a0to install Raspbian and complete the basic setup.<\/p>\n<h2>Run and install Mosquitto broker<\/h2>\n<p>The Raspberry Pi is going to interact with the ESP8266 with the MQTT protocol. Having <a href=\"https:\/\/randomnerdtutorials.com\/how-to-install-mosquitto-broker-on-raspberry-pi\/\">Mosquitto broker installed<\/a>, you need to have Mosquitto broker running on the background:<\/p>\n<pre>pi@raspberry:~ $\u00a0<strong>mosquitto -d\r\n<\/strong><\/pre>\n<h2 class=\"the-title\">Python web server with Flask<\/h2>\n<p>We\u2019re going to use a Python microframework called <a href=\"http:\/\/flask.pocoo.org\/\" target=\"_blank\" rel=\"noopener noreferrer\">Flask<\/a> to turn the Raspberry Pi into web server.<\/p>\n<p>To\u00a0install Flask, you\u2019ll need to have pip installed. Run the following commands to update your Pi and install pip:<\/p>\n<pre class=\"\">pi@raspberrypi ~ $ <strong>sudo apt-get update<\/strong>\r\npi@raspberrypi ~ $ <strong>sudo apt-get upgrade<\/strong>\r\npi@raspberrypi ~ $ <strong>sudo apt-get install python-pip python-flask<\/strong><\/pre>\n<p>Then, you use pip to install Flask and its dependencies:<\/p>\n<pre><code>pi@raspberrypi ~ $ <strong>sudo pip install flask<\/strong><\/code><\/pre>\n<h2>Installing Python Paho-MQTT<\/h2>\n<p>The <a href=\"https:\/\/pypi.python.org\/pypi\/paho-mqtt\/1.1\" target=\"_blank\" rel=\"noopener noreferrer\">Paho-MQTT<\/a> package provides a client class which enable applications to connect to an MQTT broker to publish messages, and to subscribe to topics and receive published messages. In this example, the Python web server is going to publish messages to the ESP8266 to turn the GPIOs on and off.<\/p>\n<p>To install paho-mqtt run the following command:<\/p>\n<pre>pi@raspberrypi ~ $ <strong>sudo pip install paho-mqtt<\/strong><\/pre>\n<h2>Creating the Python\u00a0Script<\/h2>\n<p>This is the core script of our application. It sets up the web server and when these buttons are pressed it publishes an MQTT message to the ESP8266.<\/p>\n<p>To keep everything organized, start by creating a new folder:<\/p>\n<pre><code>pi@raspberrypi ~ $ <strong>mkdir web-server<\/strong>\r\npi@raspberrypi ~ $ <strong>cd web-server<\/strong>\r\npi@raspberrypi:~\/web-server $\r\n<\/code><\/pre>\n<p>Create a new file called <em>app.py<\/em>.<\/p>\n<pre><code>pi@raspberrypi:~\/web-server $ <strong>nano app.py<\/strong><\/code><\/pre>\n<p>Copy and paste\u00a0the following script to your Raspberry Pi<\/p>\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-c\">#\n# Created by Rui Santos\n# Complete project details: http:\/\/randomnerdtutorials.com\n#\n\nimport paho.mqtt.client as mqtt\nfrom flask import Flask, render_template, request\napp = Flask(__name__)\n\nmqttc=mqtt.Client()\nmqttc.connect(&quot;localhost&quot;,1883,60)\nmqttc.loop_start()\n\n# Create a dictionary called pins to store the pin number, name, and pin state:\npins = {\n   4 : {'name' : 'GPIO 4', 'board' : 'esp8266', 'topic' : 'esp8266\/4', 'state' : 'False'},\n   5 : {'name' : 'GPIO 5', 'board' : 'esp8266', 'topic' : 'esp8266\/5', 'state' : 'False'}\n   }\n\n# Put the pin dictionary into the template data dictionary:\ntemplateData = {\n   'pins' : pins\n   }\n\n@app.route(&quot;\/&quot;)\ndef main():\n   # Pass the template data into the template main.html and return it to the user\n   return render_template('main.html', **templateData)\n\n# The function below is executed when someone requests a URL with the pin number and action in it:\n@app.route(&quot;\/&lt;board&gt;\/&lt;changePin&gt;\/&lt;action&gt;&quot;)\n\ndef action(board, changePin, action):\n   # Convert the pin from the URL into an integer:\n   changePin = int(changePin)\n   # Get the device name for the pin being changed:\n   devicePin = pins[changePin]['name']\n   # If the action part of the URL is &quot;on,&quot; execute the code indented below:\n   if action == &quot;1&quot; and board == 'esp8266':\n      mqttc.publish(pins[changePin]['topic'],&quot;1&quot;)\n      pins[changePin]['state'] = 'True'\n\n   if action == &quot;0&quot; and board == 'esp8266':\n      mqttc.publish(pins[changePin]['topic'],&quot;0&quot;)\n      pins[changePin]['state'] = 'False'\n\n   # Along with the pin dictionary, put the message into the template data dictionary:\n   templateData = {\n      'pins' : pins\n   }\n\n   return render_template('main.html', **templateData)\n\nif __name__ == &quot;__main__&quot;:\n   app.run(host='0.0.0.0', port=8181, debug=True)\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/RPi-ESP-Outputs\/app.py\" target=\"_blank\">View raw code<\/a><\/p>\n<h2>Creating the HTML File<\/h2>\n<p>Keeping HTML tags separated from your\u00a0Python script is how you\u00a0keep your project organized.<\/p>\n<p>Flask uses a template engine called <a href=\"http:\/\/jinja.pocoo.org\/docs\/templates\/\" target=\"_blank\" rel=\"noopener noreferrer\">Jinja2<\/a>\u00a0that you can use to send dynamic data from your Python script to your HTML file.<\/p>\n<p>Create a new folder called templates:<\/p>\n<pre class=\"\">pi@raspberrypi:~\/web-server $ <strong>mkdir templates<\/strong>\r\npi@raspberrypi:~\/web-server $ <strong>cd templates<\/strong>\r\npi@raspberrypi:~\/web-server\/templates $<\/pre>\n<p>Create a new file called <em>main.html<\/em>.<\/p>\n<pre class=\"\">pi@raspberrypi:~\/web-server\/templates $ <strong>nano main.html<\/strong><\/pre>\n<p>Copy and paste\u00a0the following template\u00a0to your Pi:<\/p>\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-c\">&lt;!DOCTYPE html&gt;\n&lt;head&gt;\n   &lt;title&gt;RPi Web Server&lt;\/title&gt;\n   &lt;!-- Latest compiled and minified CSS --&gt;\n   &lt;link rel=&quot;stylesheet&quot; href=&quot;https:\/\/maxcdn.bootstrapcdn.com\/bootstrap\/3.3.6\/css\/bootstrap.min.css&quot; integrity=&quot;sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7&quot; crossorigin=&quot;anonymous&quot;&gt;\n   &lt;!-- Optional theme --&gt;\n   &lt;link rel=&quot;stylesheet&quot; href=&quot;https:\/\/maxcdn.bootstrapcdn.com\/bootstrap\/3.3.6\/css\/bootstrap-theme.min.css&quot; integrity=&quot;sha384-fLW2N01lMqjakBkx3l\/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r&quot; crossorigin=&quot;anonymous&quot;&gt;\n   &lt;!-- Latest compiled and minified JavaScript --&gt;\n   &lt;script src=&quot;https:\/\/maxcdn.bootstrapcdn.com\/bootstrap\/3.3.6\/js\/bootstrap.min.js&quot; integrity=&quot;sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;\/script&gt;\n   &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;\n&lt;\/head&gt;\n\n&lt;body&gt;\n   &lt;h1&gt;RPi Web Server - ESP8266 MQTT&lt;\/h1&gt;\n   {% for pin in pins %}\n   &lt;h2&gt;{{ pins[pin].name }}\n   {% if pins[pin].state == 'True' %}\n      is currently &lt;strong&gt;on&lt;\/strong&gt;&lt;\/h2&gt;&lt;div class=&quot;row&quot;&gt;&lt;div class=&quot;col-md-2&quot;&gt;\n      &lt;a href=&quot;\/esp8266\/{{pin}}\/0&quot; class=&quot;btn btn-block btn-lg btn-default&quot; role=&quot;button&quot;&gt;Turn off&lt;\/a&gt;&lt;\/div&gt;&lt;\/div&gt;\n   {% else %}\n      is currently &lt;strong&gt;off&lt;\/strong&gt;&lt;\/h2&gt;&lt;div class=&quot;row&quot;&gt;&lt;div class=&quot;col-md-2&quot;&gt;\n      &lt;a href=&quot;\/esp8266\/{{pin}}\/1&quot; class=&quot;btn btn-block btn-lg btn-primary&quot; role=&quot;button&quot;&gt;Turn on&lt;\/a&gt;&lt;\/div&gt;&lt;\/div&gt;\n   {% endif %}\n   {% endfor %}\n&lt;\/body&gt;\n&lt;\/html&gt;\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/RPi-ESP-Outputs\/templates\/main.html\" target=\"_blank\">View raw code<\/a><\/p>\n<h2 class=\"the-title\">Programming the ESP8266<\/h2>\n<p>For the ESP8266 to interact with the Raspberry Pi web server, you need to install\u00a0<a href=\"https:\/\/github.com\/knolleary\/pubsubclient\" target=\"_blank\" rel=\"noopener noreferrer\">PubSubClient library<\/a>. This library provides a client for doing simple publish\/subscribe messaging with a server that supports MQTT (basically allows your ESP8266 to talk with Python web server).<\/p>\n<div class=\"single-post-content cf\">\n<h3>Installing the Library<\/h3>\n<p><strong>1)<\/strong> <a href=\"https:\/\/github.com\/knolleary\/pubsubclient\/archive\/master.zip\" target=\"_blank\" rel=\"noopener noreferrer\">Click here to download the PubSubClient library<\/a>. You should have a <em>.zip<\/em> folder in your Downloads folder<\/p>\n<p><strong>2)<\/strong> Unzip the <em>.zip<\/em> folder and you should get <strong>pubsubclient-master <\/strong>folder<\/p>\n<p><strong>3)<\/strong> Rename your folder from\u00a0<del><strong>pubsubclient-master<\/strong><\/del>\u00a0to<strong>\u00a0pubsubclient<\/strong><\/p>\n<p><strong>4)<\/strong> Move the <strong>pubsubclient<\/strong> folder to your Arduino IDE installation <strong>libraries<\/strong> folder<\/p>\n<p><strong>5)<\/strong>\u00a0Then, re-open your Arduino IDE<\/p>\n<p>The library comes with a number of example sketches. See <strong>File<\/strong> &gt; <strong>Examples<\/strong> &gt; <strong>PubSubClient<\/strong> within the Arduino IDE software.<\/p>\n<\/div>\n<h3>Uploading sketch<\/h3>\n<p>Finally, you can upload the full sketch to your ESP8266 (replace with your SSID, password and RPi IP address):<\/p>\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-c\">\/*****\n \n All the resources for this project:\n https:\/\/randomnerdtutorials.com\/\n \n*****\/\n\n\/\/ Loading the ESP8266WiFi library and the PubSubClient library\n#include &lt;ESP8266WiFi.h&gt;\n#include &lt;PubSubClient.h&gt;\n\n\/\/ Change the credentials below, so your ESP8266 connects to your router\nconst char* ssid = &quot;YOUR_SSID&quot;;\nconst char* password = &quot;YOUR_PASSWORD&quot;;\n\n\/\/ Change the variable to your Raspberry Pi IP address, so it connects to your MQTT broker\nconst char* mqtt_server = &quot;YOUR_RPi_IP_Address&quot;;\n\n\/\/ Initializes the espClient\nWiFiClient espClient;\nPubSubClient client(espClient);\n\n\/\/ Connect an LED to each GPIO of your ESP8266\nconst int ledGPIO5 = 5;\nconst int ledGPIO4 = 4;\n\n\/\/ Don't change the function below. This functions connects your ESP8266 to your router\nvoid setup_wifi() {\n  delay(10);\n  \/\/ We start by connecting to a WiFi network\n  Serial.println();\n  Serial.print(&quot;Connecting to &quot;);\n  Serial.println(ssid);\n  WiFi.begin(ssid, password);\n  while (WiFi.status() != WL_CONNECTED) {\n    delay(500);\n    Serial.print(&quot;.&quot;);\n  }\n  Serial.println(&quot;&quot;);\n  Serial.print(&quot;WiFi connected - ESP IP address: &quot;);\n  Serial.println(WiFi.localIP());\n}\n\n\/\/ This functions is executed when some device publishes a message to a topic that your ESP8266 is subscribed to\n\/\/ Change the function below to add logic to your program, so when a device publishes a message to a topic that \n\/\/ your ESP8266 is subscribed you can actually do something\nvoid callback(String topic, byte* message, unsigned int length) {\n  Serial.print(&quot;Message arrived on topic: &quot;);\n  Serial.print(topic);\n  Serial.print(&quot;. Message: &quot;);\n  String messageTemp;\n  \n  for (int i = 0; i &lt; length; i++) {\n    Serial.print((char)message[i]);\n    messageTemp += (char)message[i];\n  }\n  Serial.println();\n\n  \/\/ Feel free to add more if statements to control more GPIOs with MQTT\n\n  \/\/ If a message is received on the topic home\/office\/esp1\/gpio2, you check if the message is either 1 or 0. Turns the ESP GPIO according to the message\n  if(topic==&quot;esp8266\/4&quot;){\n      Serial.print(&quot;Changing GPIO 4 to &quot;);\n      if(messageTemp == &quot;1&quot;){\n        digitalWrite(ledGPIO4, HIGH);\n        Serial.print(&quot;On&quot;);\n      }\n      else if(messageTemp == &quot;0&quot;){\n        digitalWrite(ledGPIO4, LOW);\n        Serial.print(&quot;Off&quot;);\n      }\n  }\n  if(topic==&quot;esp8266\/5&quot;){\n      Serial.print(&quot;Changing GPIO 5 to &quot;);\n      if(messageTemp == &quot;1&quot;){\n        digitalWrite(ledGPIO5, HIGH);\n        Serial.print(&quot;On&quot;);\n      }\n      else if(messageTemp == &quot;0&quot;){\n        digitalWrite(ledGPIO5, LOW);\n        Serial.print(&quot;Off&quot;);\n      }\n  }\n  Serial.println();\n}\n\n\/\/ This functions reconnects your ESP8266 to your MQTT broker\n\/\/ Change the function below if you want to subscribe to more topics with your ESP8266 \nvoid reconnect() {\n  \/\/ Loop until we're reconnected\n  while (!client.connected()) {\n    Serial.print(&quot;Attempting MQTT connection...&quot;);\n    \/\/ Attempt to connect\n     \/*\n     YOU  NEED TO CHANGE THIS NEXT LINE, IF YOU'RE HAVING PROBLEMS WITH MQTT MULTIPLE CONNECTIONS\n     To change the ESP device ID, you will have to give a unique name to the ESP8266.\n     Here's how it looks like now:\n       if (client.connect(&quot;ESP8266Client&quot;)) {\n     If you want more devices connected to the MQTT broker, you can do it like this:\n       if (client.connect(&quot;ESPOffice&quot;)) {\n     Then, for the other ESP:\n       if (client.connect(&quot;ESPGarage&quot;)) {\n      That should solve your MQTT multiple connections problem\n\n     THE SECTION IN loop() function should match your device name\n    *\/\n    if (client.connect(&quot;ESP8266Client&quot;)) {\n      Serial.println(&quot;connected&quot;);  \n      \/\/ Subscribe or resubscribe to a topic\n      \/\/ You can subscribe to more topics (to control more LEDs in this example)\n      client.subscribe(&quot;esp8266\/4&quot;);\n      client.subscribe(&quot;esp8266\/5&quot;);\n    } else {\n      Serial.print(&quot;failed, rc=&quot;);\n      Serial.print(client.state());\n      Serial.println(&quot; try again in 5 seconds&quot;);\n      \/\/ Wait 5 seconds before retrying\n      delay(5000);\n    }\n  }\n}\n\n\/\/ The setup function sets your ESP GPIOs to Outputs, starts the serial communication at a baud rate of 115200\n\/\/ Sets your mqtt broker and sets the callback function\n\/\/ The callback function is what receives messages and actually controls the LEDs\nvoid setup() {\n  pinMode(ledGPIO4, OUTPUT);\n  pinMode(ledGPIO5, OUTPUT);\n  \n  Serial.begin(115200);\n  setup_wifi();\n  client.setServer(mqtt_server, 1883);\n  client.setCallback(callback);\n}\n\n\/\/ For this project, you don't need to change anything in the loop function. \n\/\/ Basically it ensures that you ESP is connected to your broker\nvoid loop() {\n  if (!client.connected()) {\n    reconnect();\n  }\n  if(!client.loop())\n     \/*\n     YOU  NEED TO CHANGE THIS NEXT LINE, IF YOU'RE HAVING PROBLEMS WITH MQTT MULTIPLE CONNECTIONS\n     To change the ESP device ID, you will have to give a unique name to the ESP8266.\n     Here's how it looks like now:\n       client.connect(&quot;ESP8266Client&quot;);\n     If you want more devices connected to the MQTT broker, you can do it like this:\n       client.connect(&quot;ESPOffice&quot;);\n     Then, for the other ESP:\n       client.connect(&quot;ESPGarage&quot;);\n      That should solve your MQTT multiple connections problem\n\n     THE SECTION IN recionnect() function should match your device name\n    *\/\n    client.connect(&quot;ESP8266Client&quot;);\n}\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/RPi-ESP-Outputs\/esp8266_outputs.ino\" target=\"_blank\">View raw code<\/a><\/p>\n<h3>Schematics<\/h3>\n<p>The schematics for this project are very straightforward. Simply connect two <a href=\"https:\/\/makeradvisor.com\/tools\/3mm-5mm-leds-kit-storage-box\/\" target=\"_blank\" rel=\"noopener noreferrer\">LEDs<\/a> with two <a href=\"https:\/\/makeradvisor.com\/tools\/resistors-kits\/\" target=\"_blank\" rel=\"noopener noreferrer\">resistors<\/a> to your <a href=\"https:\/\/makeradvisor.com\/tools\/esp8266-esp-12e-nodemcu-wi-fi-development-board\/\" target=\"_blank\" rel=\"noopener noreferrer\">ESP8266<\/a> as shown in the figure below.<\/p>\n<p><img data-recalc-dims=\"1\" decoding=\"async\" class=\"aligncenter wp-image-33296\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/ESP8266_schematics_LEDs.png?resize=348%2C454&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" width=\"348\" height=\"454\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/ESP8266_schematics_LEDs.png?w=659&amp;quality=100&amp;strip=all&amp;ssl=1 659w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/ESP8266_schematics_LEDs.png?resize=115%2C150&amp;quality=100&amp;strip=all&amp;ssl=1 115w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/ESP8266_schematics_LEDs.png?resize=230%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 230w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/ESP8266_schematics_LEDs.png?resize=61%2C80&amp;quality=100&amp;strip=all&amp;ssl=1 61w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/ESP8266_schematics_LEDs.png?resize=168%2C220&amp;quality=100&amp;strip=all&amp;ssl=1 168w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/ESP8266_schematics_LEDs.png?resize=77%2C100&amp;quality=100&amp;strip=all&amp;ssl=1 77w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/ESP8266_schematics_LEDs.png?resize=182%2C238&amp;quality=100&amp;strip=all&amp;ssl=1 182w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/ESP8266_schematics_LEDs.png?resize=318%2C415&amp;quality=100&amp;strip=all&amp;ssl=1 318w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/ESP8266_schematics_LEDs.png?resize=373%2C487&amp;quality=100&amp;strip=all&amp;ssl=1 373w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/ESP8266_schematics_LEDs.png?resize=455%2C595&amp;quality=100&amp;strip=all&amp;ssl=1 455w\" sizes=\"(max-width: 348px) 100vw, 348px\" \/><\/p>\n<p>You can use the preceding links or go directly to <a href=\"https:\/\/makeradvisor.com\/tools\/?utm_source=rnt&utm_medium=post&utm_campaign=post\" target=\"_blank\">MakerAdvisor.com\/tools<\/a> to find all the parts for your projects at the best price!<\/p><p style=\"text-align:center;\"><a href=\"https:\/\/makeradvisor.com\/tools\/?utm_source=rnt&utm_medium=post&utm_campaign=post\" target=\"_blank\"><img data-recalc-dims=\"1\" decoding=\"async\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/10\/header-200.png?w=1200&#038;quality=100&#038;strip=all&#038;ssl=1\"><\/a><\/p>\n<h2>Launching the Web Server<\/h2>\n<p>To launch your Raspberry Pi web server move to the folder that contains the file <em>app.py<\/em>:<\/p>\n<pre class=\"\">pi@raspberrypi:~\/web-server\/templates $ <strong>cd ..<\/strong><\/pre>\n<p>Then, run the following command:<\/p>\n<pre class=\"\">pi@raspberrypi:~\/web-server $ <strong>sudo python app.py<\/strong><\/pre>\n<p>Your web server should start immediately on port :8181!<\/p>\n<p><img decoding=\"async\" class=\"aligncenter wp-image-18537\" src=\"https:\/\/i2.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2016\/03\/python-launch-web-server.png?resize=668%2C281\" sizes=\"(max-width: 668px) 100vw, 668px\" srcset=\"https:\/\/i2.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2016\/03\/python-launch-web-server.png?w=737 737w, https:\/\/i2.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2016\/03\/python-launch-web-server.png?resize=300%2C126 300w\" alt=\"python launch web server\" width=\"668\" height=\"281\" \/><\/p>\n<h2>Demonstration<\/h2>\n<p>Open your Raspberry Pi address in your browser by entering its IP address, in my case:\u00a0http:\/\/192.168.1.98:8181<\/p>\n<p><span style=\"color: #ff0000;\"><strong>Note: you must enter your IP\u00a0address followed by :8181<\/strong><\/span><\/p>\n<p><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-33301\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/web_server_python_esp8266.png?resize=519%2C334&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" width=\"519\" height=\"334\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/web_server_python_esp8266.png?w=556&amp;quality=100&amp;strip=all&amp;ssl=1 556w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/web_server_python_esp8266.png?resize=150%2C97&amp;quality=100&amp;strip=all&amp;ssl=1 150w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/web_server_python_esp8266.png?resize=300%2C193&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/web_server_python_esp8266.png?resize=80%2C52&amp;quality=100&amp;strip=all&amp;ssl=1 80w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/web_server_python_esp8266.png?resize=220%2C142&amp;quality=100&amp;strip=all&amp;ssl=1 220w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/web_server_python_esp8266.png?resize=155%2C100&amp;quality=100&amp;strip=all&amp;ssl=1 155w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/web_server_python_esp8266.png?resize=233%2C150&amp;quality=100&amp;strip=all&amp;ssl=1 233w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/web_server_python_esp8266.png?resize=370%2C238&amp;quality=100&amp;strip=all&amp;ssl=1 370w\" sizes=\"(max-width: 519px) 100vw, 519px\" \/><\/p>\n<p>Here\u2019s a video demo of the web server in action:<\/p>\n<p style=\"text-align:center\"><iframe width=\"720\" height=\"405\" src=\"https:\/\/www.youtube.com\/embed\/X04yaaydjFo?rel=0\" frameborder=\"0\" allowfullscreen><\/iframe><\/p>\n<h2>Wrapping up<\/h2>\n<p>In the next blog post, we will <a href=\"https:\/\/randomnerdtutorials.com\/esp8266-publishing-dht22-readings-with-mqtt-to-raspberry-pi\/\">publish sensor readings with the ESP8266 to the Python web server<\/a>.<\/p>\n<p>Like home automation? Learn more about Node-RED, Raspberry Pi, ESP8266 and Arduino\u00a0with\u00a0my course:\u00a0<a href=\"https:\/\/randomnerdtutorials.com\/build-a-home-automation-system-for-100\/\" target=\"_blank\" rel=\"noopener noreferrer\">Build a Home Automation System for $100<\/a>.<\/p>\n<p><strong>Do you have any questions?\u00a0<\/strong><strong>Leave a comment down below!<\/strong><\/p>\n<p>Thanks for reading. If you like this post probably you might like my next ones, so please support me by <a href=\"https:\/\/randomnerdtutorials.com\/download\">subscribing my blog<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this project you\u2019ll create a standalone web server with a Raspberry Pi that can toggle two LEDs from an ESP8266 using\u00a0MQTT protocol. You can replace those LEDs with any &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"Raspberry Pi Publishing MQTT Messages to ESP8266\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-publishing-mqtt-messages-to-esp8266\/#more-33293\" aria-label=\"Read more about Raspberry Pi Publishing MQTT Messages to ESP8266\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":1,"featured_media":33294,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":true,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[214,300,240,282,283,284,190,192],"tags":[],"class_list":["post-33293","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-esp8266","category-0-esp8266","category-esp8266-projects","category-mqtt","category-mqtt-broker","category-mqtt-client","category-raspberry-pi","category-r-tutorials"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/02\/featured-image-raspberry-pi-esp8266-mqtt-output.jpg?fit=1280%2C720&quality=100&strip=all&ssl=1","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/33293","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/comments?post=33293"}],"version-history":[{"count":0,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/33293\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/33294"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=33293"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=33293"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=33293"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}