{"id":31752,"date":"2017-03-16T07:20:11","date_gmt":"2017-03-16T07:20:11","guid":{"rendered":"http:\/\/randomnerdtutorials.com\/?p=31752"},"modified":"2019-04-02T10:23:29","modified_gmt":"2019-04-02T10:23:29","slug":"esp8266-publishing-dht22-readings-with-mqtt-to-raspberry-pi","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/esp8266-publishing-dht22-readings-with-mqtt-to-raspberry-pi\/","title":{"rendered":"ESP8266 Publishing DHT22 Readings with MQTT to Raspberry Pi"},"content":{"rendered":"<p>In this project you\u2019ll create a standalone web server with a Raspberry Pi that displays temperature and humidity readings with a DHT22 sensor. You can also control two outputs from an ESP8266 using MQTT protocol.<\/p>\n<p>In order to create the web server you will be using a Python microframework called Flask. Here\u2019s the high level overview of the system:<\/p>\n<p><a href=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/DHT22_RaspberryPi_ESP8266.jpg?quality=100&#038;strip=all&#038;ssl=1\"><img data-recalc-dims=\"1\" fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter size-full wp-image-35828\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/DHT22_RaspberryPi_ESP8266.jpg?resize=1065%2C224&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" width=\"1065\" height=\"224\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/DHT22_RaspberryPi_ESP8266.jpg?w=1065&amp;quality=100&amp;strip=all&amp;ssl=1 1065w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/DHT22_RaspberryPi_ESP8266.jpg?resize=150%2C32&amp;quality=100&amp;strip=all&amp;ssl=1 150w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/DHT22_RaspberryPi_ESP8266.jpg?resize=300%2C63&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/DHT22_RaspberryPi_ESP8266.jpg?resize=768%2C162&amp;quality=100&amp;strip=all&amp;ssl=1 768w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/DHT22_RaspberryPi_ESP8266.jpg?resize=1024%2C215&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/DHT22_RaspberryPi_ESP8266.jpg?resize=80%2C17&amp;quality=100&amp;strip=all&amp;ssl=1 80w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/DHT22_RaspberryPi_ESP8266.jpg?resize=220%2C46&amp;quality=100&amp;strip=all&amp;ssl=1 220w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/DHT22_RaspberryPi_ESP8266.jpg?resize=250%2C53&amp;quality=100&amp;strip=all&amp;ssl=1 250w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/DHT22_RaspberryPi_ESP8266.jpg?resize=280%2C59&amp;quality=100&amp;strip=all&amp;ssl=1 280w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/DHT22_RaspberryPi_ESP8266.jpg?resize=510%2C107&amp;quality=100&amp;strip=all&amp;ssl=1 510w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/DHT22_RaspberryPi_ESP8266.jpg?resize=750%2C158&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/DHT22_RaspberryPi_ESP8266.jpg?resize=975%2C205&amp;quality=100&amp;strip=all&amp;ssl=1 975w\" sizes=\"(max-width: 1065px) 100vw, 1065px\" \/><\/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\/NOO2qh3SYYg?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-publishing-mqtt-messages-to-esp8266\/\">Raspberry Pi Publishing MQTT Messages to ESP8266<\/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<\/strong><\/pre>\n<h2>Installing 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 git-core<\/strong><\/pre>\n<p>Then, you use pip to install Flask and Paho MQTT:<\/p>\n<pre>pi@raspberrypi ~ $ <strong>sudo pip install flask<\/strong>\r\npi@raspberrypi ~ $ <strong>sudo pip install paho-mqtt<\/strong><\/pre>\n<h2>Installing SocketIO<\/h2>\n<p>This project uses SocketIO which allows you to create a\u00a0Python Flask web page that can be asynchronously updated by your Python Flask application. This means that you don&#8217;t need to refresh the web page to see the latest readings, they are instantly updated. You&#8217;ll\u00a0be installing the <a href=\"https:\/\/github.com\/miguelgrinberg\/Flask-SocketIO\" target=\"_blank\" rel=\"noopener noreferrer\">Flask SocketIO<\/a> Python package.<\/p>\n<pre>pi@raspberrypi ~ $ <strong>sudo pip install flask-socketio\r\n<\/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. It&#8217;s also subscribed to temperature and humidity MQTT topics to receive the readings.<\/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\nfrom flask_socketio import SocketIO, emit\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'secret!'\nsocketio = SocketIO(app)\n\n# The callback for when the client receives a CONNACK response from the server.\ndef on_connect(client, userdata, flags, rc):\n    print(&quot;Connected with result code &quot;+str(rc))\n\n    # Subscribing in on_connect() means that if we lose the connection and\n    # reconnect then subscriptions will be renewed.\n    client.subscribe(&quot;\/esp8266\/temperature&quot;)\n    client.subscribe(&quot;\/esp8266\/humidity&quot;)\n\n# The callback for when a PUBLISH message is received from the ESP8266.\ndef on_message(client, userdata, message):\n    #socketio.emit('my variable')\n    print(&quot;Received message '&quot; + str(message.payload) + &quot;' on topic '&quot;\n        + message.topic + &quot;' with QoS &quot; + str(message.qos))\n    if message.topic == &quot;\/esp8266\/temperature&quot;:\n        print(&quot;temperature update&quot;)\n\tsocketio.emit('dht_temperature', {'data': message.payload})\n    if message.topic == &quot;\/esp8266\/humidity&quot;:\n        print(&quot;humidity update&quot;)\n\tsocketio.emit('dht_humidity', {'data': message.payload})\n\nmqttc=mqtt.Client()\nmqttc.on_connect = on_connect\nmqttc.on_message = on_message\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', async_mode=socketio.async_mode, **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;)\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;1&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   if action == &quot;0&quot; and board == 'esp8266':\n      mqttc.publish(pins[changePin]['topic'],&quot;0&quot;)\n      pins[changePin]['state'] = 'False'\n   # Along with the pin dictionary, put the message into the template data dictionary:\n   templateData = {\n      'pins' : pins\n   }\n   return render_template('main.html', **templateData)\n\n@socketio.on('my event')\ndef handle_my_custom_event(json):\n    print('received json data here: ' + str(json))\n\nif __name__ == &quot;__main__&quot;:\n   socketio.run(app, 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-DHT\/app.py\" target=\"_blank\">View raw code<\/a><\/p>\n<h2>Creating the HTML File<\/h2>\n<div class=\"code-block code-block-5\">\n<p>\u00a0Keeping HTML tags separated from your\u00a0Python script is how you\u00a0keep your project organized.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;script src=&quot;https:\/\/code.jquery.com\/jquery-3.1.1.min.js&quot; integrity=&quot;sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=&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;script type=&quot;text\/javascript&quot; src=&quot;\/\/cdnjs.cloudflare.com\/ajax\/libs\/socket.io\/1.3.6\/socket.io.min.js&quot;&gt;&lt;\/script&gt;\n   &lt;script type=&quot;text\/javascript&quot; charset=&quot;utf-8&quot;&gt;\n      $(document).ready(function() {\n      \tvar socket = io.connect('http:\/\/' + document.domain + ':' + location.port);\n      \tsocket.on('connect', function() {\n          socket.emit('my event', {data: 'I\\'m connected!'});\n      \t});\n      \tsocket.on('dht_temperature', function(msg) {\n\t  var nDate = new Date();\n          $('#readingsUpdated').text(nDate.getHours() + 'h:' + nDate.getMinutes() +\n             'm:' + nDate.getSeconds() + 's').html();\n          $('#temperature').text(msg.data).html();\n      \t});\n      \tsocket.on('dht_humidity', function(msg) {\n          $('#humidity').text(msg.data).html();\n      \t});\n      });\n   &lt;\/script&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;h3&gt;DHT Readings (updated &lt;span id=&quot;readingsUpdated&quot;&gt;&lt;\/span&gt;)&lt;\/h3&gt;\n   &lt;h3&gt;Temperature: &lt;span id=&quot;temperature&quot;&gt;&lt;\/span&gt;\u00baC&lt;\/h3&gt;\n   &lt;h3&gt;Humidity: &lt;span id=&quot;humidity&quot;&gt;&lt;\/span&gt;%&lt;\/h3&gt;\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-DHT\/templates\/main.html\" target=\"_blank\">View raw code<\/a><\/p>\n<\/div>\n<div class=\"single-post-content cf\">\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 PubSubClient library<\/h3>\n<p><strong>1)\u00a0<\/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>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<h3>Installing the DHT sensor library<\/h3>\n<p>The\u00a0<a href=\"https:\/\/github.com\/adafruit\/DHT-sensor-library\" target=\"_blank\" rel=\"noopener noreferrer\">DHT sensor library<\/a> provides an easy way of\u00a0using any DHT sensor to read temperature and humidity with your ESP8266 or Arduino boards.<\/p>\n<p><strong>1)<\/strong> <a href=\"https:\/\/github.com\/adafruit\/DHT-sensor-library\/archive\/master.zip\" target=\"_blank\" rel=\"noopener noreferrer\">Click here to download the DHT sensor\u00a0library<\/a>. You should have a\u00a0<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>DHT-sensor-library-master <\/strong>folder<\/p>\n<p><strong>3)<\/strong> Rename your folder from\u00a0<del><strong>DHT-sensor-library-master<\/strong><\/del>\u00a0to<strong>\u00a0DHT<\/strong><\/p>\n<p><strong>4)<\/strong> Move the <strong>DHT\u00a0<\/strong>folder to your Arduino IDE installation\u00a0<strong>libraries<\/strong> folder<\/p>\n<p><strong>5)<\/strong>\u00a0Then, re-open your Arduino IDE<\/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#include &quot;DHT.h&quot;\n\n\/\/ Uncomment one of the lines bellow for whatever DHT sensor type you're using!\n\/\/#define DHTTYPE DHT11   \/\/ DHT 11\n\/\/#define DHTTYPE DHT21   \/\/ DHT 21 (AM2301)\n#define DHTTYPE DHT22   \/\/ DHT 22  (AM2302), AM2321\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\/\/ DHT Sensor\nconst int DHTPin = 14;\n\n\/\/ Initialize DHT sensor.\nDHT dht(DHTPin, DHTTYPE);\n\n\/\/ Timers auxiliar variables\nlong now = millis();\nlong lastMeasure = 0;\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  dht.begin();\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  now = millis();\n  \/\/ Publishes new temperature and humidity every 10 seconds\n  if (now - lastMeasure &gt; 10000) {\n    lastMeasure = now;\n    \/\/ Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)\n    float h = dht.readHumidity();\n    \/\/ Read temperature as Celsius (the default)\n    float t = dht.readTemperature();\n    \/\/ Read temperature as Fahrenheit (isFahrenheit = true)\n    float f = dht.readTemperature(true);\n\n    \/\/ Check if any reads failed and exit early (to try again).\n    if (isnan(h) || isnan(t) || isnan(f)) {\n      Serial.println(&quot;Failed to read from DHT sensor!&quot;);\n      return;\n    }\n\n    \/\/ Computes temperature values in Celsius\n    float hic = dht.computeHeatIndex(t, h, false);\n    static char temperatureTemp[7];\n    dtostrf(hic, 6, 2, temperatureTemp);\n    \n    \/\/ Uncomment to compute temperature values in Fahrenheit \n    \/\/ float hif = dht.computeHeatIndex(f, h);\n    \/\/ static char temperatureTemp[7];\n    \/\/ dtostrf(hic, 6, 2, temperatureTemp);\n    \n    static char humidityTemp[7];\n    dtostrf(h, 6, 2, humidityTemp);\n\n    \/\/ Publishes Temperature and Humidity values\n    client.publish(&quot;\/esp8266\/temperature&quot;, temperatureTemp);\n    client.publish(&quot;\/esp8266\/humidity&quot;, humidityTemp);\n    \n    Serial.print(&quot;Humidity: &quot;);\n    Serial.print(h);\n    Serial.print(&quot; %\\t Temperature: &quot;);\n    Serial.print(t);\n    Serial.print(&quot; *C &quot;);\n    Serial.print(f);\n    Serial.print(&quot; *F\\t Heat index: &quot;);\n    Serial.print(hic);\n    Serial.println(&quot; *C &quot;);\n    \/\/ Serial.print(hif);\n    \/\/ Serial.println(&quot; *F&quot;);\n  }\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-DHT\/esp8266_dht.ino\" target=\"_blank\">View raw code<\/a><\/p>\n<\/div>\n<h3>Schematics<\/h3>\n<p>To complete this project\u00a0you need\u00a0these next components:<\/p>\n<ul>\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/esp8266-esp-12e-nodemcu-wi-fi-development-board\/\" target=\"_blank\" rel=\"noopener noreferrer\">1x\u00a0ESP8266 12E\u00a0<\/a>&#8211; read <a href=\"https:\/\/makeradvisor.com\/best-esp8266-wi-fi-development-board\/\" target=\"_blank\" rel=\"noopener noreferrer\">Best ESP8266 Wi-Fi Development Boards<\/a><\/li>\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/dht22-temperature-humidity-sensor\/\" target=\"_blank\" rel=\"noopener noreferrer\">1x DHT22 Sensor\u00a0<\/a><\/li>\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/resistors-kits\/\" target=\"_blank\" rel=\"noopener noreferrer\">1x 4700 Ohm Resistor<\/a><\/li>\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/resistors-kits\/\" target=\"_blank\" rel=\"noopener noreferrer\">2x 470 Ohm resistors<\/a><\/li>\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/3mm-5mm-leds-kit-storage-box\/\" target=\"_blank\" rel=\"noopener noreferrer\">2x LEDs<\/a><\/li>\n<\/ul>\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<p><strong>Note:<\/strong>\u00a0other DHT sensor types will also work with a small\u00a0change in the code.<\/p>\n<p>Here\u2019s the schematics:<\/p>\n<p><img data-recalc-dims=\"1\" decoding=\"async\" class=\"aligncenter wp-image-35827\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/ESP8266_Temperature_Humidity.png?resize=417%2C616&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" width=\"417\" height=\"616\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/ESP8266_Temperature_Humidity.png?w=504&amp;quality=100&amp;strip=all&amp;ssl=1 504w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/ESP8266_Temperature_Humidity.png?resize=101%2C150&amp;quality=100&amp;strip=all&amp;ssl=1 101w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/ESP8266_Temperature_Humidity.png?resize=203%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 203w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/ESP8266_Temperature_Humidity.png?resize=54%2C80&amp;quality=100&amp;strip=all&amp;ssl=1 54w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/ESP8266_Temperature_Humidity.png?resize=149%2C220&amp;quality=100&amp;strip=all&amp;ssl=1 149w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/ESP8266_Temperature_Humidity.png?resize=68%2C100&amp;quality=100&amp;strip=all&amp;ssl=1 68w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/ESP8266_Temperature_Humidity.png?resize=161%2C238&amp;quality=100&amp;strip=all&amp;ssl=1 161w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/ESP8266_Temperature_Humidity.png?resize=281%2C415&amp;quality=100&amp;strip=all&amp;ssl=1 281w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/ESP8266_Temperature_Humidity.png?resize=329%2C487&amp;quality=100&amp;strip=all&amp;ssl=1 329w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/ESP8266_Temperature_Humidity.png?resize=403%2C595&amp;quality=100&amp;strip=all&amp;ssl=1 403w\" sizes=\"(max-width: 417px) 100vw, 417px\" \/><\/p>\n<div class=\"single-post-content cf\">\n<p><span style=\"color: #ff0000;\"><strong>Important:<\/strong><\/span>\u00a0the\u00a0DHT sensor requires 5V to operate properly, so make sure you use the <em>Vin<\/em> pin from your ESP8266 that outputs 5V.<\/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<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><strong>Note: you must enter your IP\u00a0address followed by :8181<\/strong><\/p>\n<p><img data-recalc-dims=\"1\" decoding=\"async\" class=\"aligncenter wp-image-35820\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/raspberry_pi_socketio_python_esp8266.png?resize=402%2C342&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" width=\"402\" height=\"342\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/raspberry_pi_socketio_python_esp8266.png?w=714&amp;quality=100&amp;strip=all&amp;ssl=1 714w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/raspberry_pi_socketio_python_esp8266.png?resize=150%2C128&amp;quality=100&amp;strip=all&amp;ssl=1 150w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/raspberry_pi_socketio_python_esp8266.png?resize=300%2C255&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/raspberry_pi_socketio_python_esp8266.png?resize=80%2C68&amp;quality=100&amp;strip=all&amp;ssl=1 80w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/raspberry_pi_socketio_python_esp8266.png?resize=220%2C187&amp;quality=100&amp;strip=all&amp;ssl=1 220w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/raspberry_pi_socketio_python_esp8266.png?resize=117%2C100&amp;quality=100&amp;strip=all&amp;ssl=1 117w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/raspberry_pi_socketio_python_esp8266.png?resize=176%2C150&amp;quality=100&amp;strip=all&amp;ssl=1 176w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/raspberry_pi_socketio_python_esp8266.png?resize=279%2C238&amp;quality=100&amp;strip=all&amp;ssl=1 279w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/raspberry_pi_socketio_python_esp8266.png?resize=487%2C415&amp;quality=100&amp;strip=all&amp;ssl=1 487w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/raspberry_pi_socketio_python_esp8266.png?resize=572%2C487&amp;quality=100&amp;strip=all&amp;ssl=1 572w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/raspberry_pi_socketio_python_esp8266.png?resize=699%2C595&amp;quality=100&amp;strip=all&amp;ssl=1 699w\" sizes=\"(max-width: 402px) 100vw, 402px\" \/><\/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\/NOO2qh3SYYg?rel=0\" frameborder=\"0\" allowfullscreen><\/iframe><\/p>\n<h2>Wrapping up<\/h2>\n<p>In the next blog post, we will publish sensor readings with the ESP8266 to the Python web server, but those readings are going to be stored in an <a href=\"https:\/\/randomnerdtutorials.com\/sqlite-database-on-a-raspberry-pi\/\">SQLite database<\/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<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In this project you\u2019ll create a standalone web server with a Raspberry Pi that displays temperature and humidity readings with a DHT22 sensor. You can also control two outputs from &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"ESP8266 Publishing DHT22 Readings with MQTT to Raspberry Pi\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/esp8266-publishing-dht22-readings-with-mqtt-to-raspberry-pi\/#more-31752\" aria-label=\"Read more about ESP8266 Publishing DHT22 Readings with MQTT to Raspberry Pi\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":1,"featured_media":35826,"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":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[265,214,246,300,240,225,282,283,284,264,289,268],"tags":[],"class_list":["post-31752","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-esp8266-project","category-esp8266","category-esp8266-arduino-ide","category-0-esp8266","category-esp8266-projects","category-home-automation","category-mqtt","category-mqtt-broker","category-mqtt-client","category-project","category-python","category-raspberry-pi-project"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/DHT22_RaspberryPi_ESP8266-featured.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\/31752","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=31752"}],"version-history":[{"count":0,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/31752\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/35826"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=31752"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=31752"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=31752"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}