{"id":35947,"date":"2017-03-23T07:20:42","date_gmt":"2017-03-23T07:20:42","guid":{"rendered":"http:\/\/randomnerdtutorials.com\/?p=35947"},"modified":"2019-04-02T10:23:29","modified_gmt":"2019-04-02T10:23:29","slug":"esp8266-publishing-dht22-readings-to-sqlite-database","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/esp8266-publishing-dht22-readings-to-sqlite-database\/","title":{"rendered":"ESP8266 Publishing DHT22 Readings to SQLite Database"},"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 that are stored in an SQLite database.<\/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<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\/esp8266-publishing-dht22-readings-with-mqtt-to-raspberry-pi\/\">ESP8266 Publishing DHT22 Readings with MQTT to Raspberry Pi<\/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\/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<\/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:<\/p>\n<pre>pi@raspberrypi ~ $ <strong>sudo pip install flask<\/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, receives the temperature\/humidity readings and saves\u00a0those sensor readings in an SQLite database.<\/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\nimport json\nimport sqlite3\n\napp = Flask(__name__)\n\ndef dict_factory(cursor, row):\n    d = {}\n    for idx, col in enumerate(cursor.description):\n        d[col[0]] = row[idx]\n    return d\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    # Subscribing in on_connect() means that if we lose the connection and\n    # reconnect then subscriptions will be renewed.\n    client.subscribe(&quot;\/esp8266\/dhtreadings&quot;)\n\n# The callback for when a PUBLISH message is received from the ESP8266.\ndef on_message(client, userdata, message):\n    if message.topic == &quot;\/esp8266\/dhtreadings&quot;:\n        print(&quot;DHT readings update&quot;)\n        #print(message.payload.json())\n        #print(dhtreadings_json['temperature'])\n        #print(dhtreadings_json['humidity'])\n\n        dhtreadings_json = json.loads(message.payload)\n\n        # connects to SQLite database. File is named &quot;sensordata.db&quot; without the quotes\n        # WARNING: your database file should be in the same directory of the app.py file or have the correct path\n        conn=sqlite3.connect('sensordata.db')\n        c=conn.cursor()\n\n        c.execute(&quot;&quot;&quot;INSERT INTO dhtreadings (temperature,\n            humidity, currentdate, currentime, device) VALUES((?), (?), date('now'),\n            time('now'), (?))&quot;&quot;&quot;, (dhtreadings_json['temperature'],\n            dhtreadings_json['humidity'], 'esp8266') )\n\n        conn.commit()\n        conn.close()\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@app.route(&quot;\/&quot;)\ndef main():\n   # connects to SQLite database. File is named &quot;sensordata.db&quot; without the quotes\n   # WARNING: your database file should be in the same directory of the app.py file or have the correct path\n   conn=sqlite3.connect('sensordata.db')\n   conn.row_factory = dict_factory\n   c=conn.cursor()\n   c.execute(&quot;SELECT * FROM dhtreadings ORDER BY id DESC LIMIT 20&quot;)\n   readings = c.fetchall()\n   #print(readings)\n   return render_template('main.html', readings=readings)\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-SQLite\/app.py\" target=\"_blank\">View raw code<\/a><\/p>\n<h2>Preparing Your SQLite File<\/h2>\n<p>Follow this next tutorial to learn<a href=\"https:\/\/randomnerdtutorials.com\/sqlite-database-on-a-raspberry-pi\/\"> how to Install SQLite database on a Raspberry Pi and prepare the database<\/a>. Having an SQLite database file that has the following schema:<\/p>\n<pre>sqlite&gt; <strong>.fullschema<\/strong>\r\nCREATE TABLE dhtreadings(id INTEGER PRIMARY KEY AUTOINCREMENT, temperature NUMERIC, humidity NUMERIC, currentdate DATE, currentime TIME, device TEXT);<\/pre>\n<p>Your\u00a0SQLite database\u00a0file should be named &#8220;sensordata.db&#8221; without the quotes.<\/p>\n<p><span style=\"color: #ff0000;\"><strong>WARNING:<\/strong><\/span> your database file should be in the same directory of the app.py file or have the correct path in your Python app.py file created in a preceding section (section\u00a0conn=sqlite3.connect(&#8216;sensordata.db&#8217;)).<\/p>\n<h2>Creating the HTML File<\/h2>\n<div class=\"code-block code-block-5\">\n<p>Keeping 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;\/head&gt;\n\n&lt;body&gt;\n   &lt;h1&gt;RPi Web Server - ESP8266 SQLite Data&lt;\/h1&gt;\n   &lt;table class=&quot;table table-hover&quot;&gt;\n     &lt;tr&gt;&lt;th&gt;ID&lt;\/th&gt;\n     &lt;th&gt;Temperature&lt;\/th&gt;\n     &lt;th&gt;Humidity&lt;\/th&gt;\n     &lt;th&gt;Date&lt;\/th&gt;\n     &lt;th&gt;Time&lt;\/th&gt;\n     &lt;th&gt;Device&lt;\/th&gt;&lt;\/tr&gt;\n     {% for entry in readings %}\n        &lt;tr&gt;&lt;td&gt;{{ entry.id }}&lt;\/td&gt;\n        &lt;td&gt;{{ entry.temperature }}&lt;\/td&gt;\n        &lt;td&gt;{{ entry.humidity }}&lt;\/td&gt;\n        &lt;td&gt;{{ entry.currentdate }}&lt;\/td&gt;\n        &lt;td&gt;{{ entry.currentime }}&lt;\/td&gt;\n        &lt;td&gt;{{ entry.device }}&lt;\/td&gt;&lt;\/tr&gt;\n     {% endfor %}\n   &lt;\/table&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-SQLite\/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:\/\/rntlab.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\/\/ 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\nchar data[80];\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\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    } 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 DHT sensor, 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  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 30 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    String dhtReadings = &quot;{ \\&quot;temperature\\&quot;: \\&quot;&quot; + String(temperatureTemp) + &quot;\\&quot;, \\&quot;humidity\\&quot; : \\&quot;&quot; + String(humidityTemp) + &quot;\\&quot;}&quot;;\n    dhtReadings.toCharArray(data, (dhtReadings.length() + 1));\n    \n    \/\/ Publishes Temperature and Humidity values\n    client.publish(&quot;\/esp8266\/dhtreadings&quot;, data);\n    Serial.println(data);\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-SQLite\/esp8266_sqlite.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>\u2013 read\u00a0<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\/jumper-wires-kit-120-pieces\/\" target=\"_blank\" rel=\"noopener noreferrer\">Jumper wires<\/a><\/li>\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/mb-102-solderless-breadboard-830-points\/\" target=\"_blank\" rel=\"noopener noreferrer\">Breadboard<\/a><\/li>\n<\/ul>\n<p><strong>Note:<\/strong>\u00a0other DHT sensor types will also work with a small\u00a0change in the code.<\/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<p>Here\u2019s the schematics:<\/p>\n<p><img data-recalc-dims=\"1\" decoding=\"async\" class=\"aligncenter wp-image-35950\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/ESP8266_Humidity_temperature_bb.png?resize=354%2C528&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" width=\"354\" height=\"528\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/ESP8266_Humidity_temperature_bb.png?w=581&amp;quality=100&amp;strip=all&amp;ssl=1 581w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/ESP8266_Humidity_temperature_bb.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_Humidity_temperature_bb.png?resize=201%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 201w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/ESP8266_Humidity_temperature_bb.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_Humidity_temperature_bb.png?resize=147%2C220&amp;quality=100&amp;strip=all&amp;ssl=1 147w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/ESP8266_Humidity_temperature_bb.png?resize=67%2C100&amp;quality=100&amp;strip=all&amp;ssl=1 67w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/ESP8266_Humidity_temperature_bb.png?resize=159%2C238&amp;quality=100&amp;strip=all&amp;ssl=1 159w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/ESP8266_Humidity_temperature_bb.png?resize=278%2C415&amp;quality=100&amp;strip=all&amp;ssl=1 278w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/ESP8266_Humidity_temperature_bb.png?resize=326%2C487&amp;quality=100&amp;strip=all&amp;ssl=1 326w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/ESP8266_Humidity_temperature_bb.png?resize=399%2C595&amp;quality=100&amp;strip=all&amp;ssl=1 399w\" sizes=\"(max-width: 354px) 100vw, 354px\" \/><\/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-35952\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/sqlite_raspberry_pi_readings_mqtt.png?resize=799%2C413&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" width=\"799\" height=\"413\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/sqlite_raspberry_pi_readings_mqtt.png?w=900&amp;quality=100&amp;strip=all&amp;ssl=1 900w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/sqlite_raspberry_pi_readings_mqtt.png?resize=150%2C78&amp;quality=100&amp;strip=all&amp;ssl=1 150w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/sqlite_raspberry_pi_readings_mqtt.png?resize=300%2C155&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/sqlite_raspberry_pi_readings_mqtt.png?resize=768%2C397&amp;quality=100&amp;strip=all&amp;ssl=1 768w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/sqlite_raspberry_pi_readings_mqtt.png?resize=80%2C41&amp;quality=100&amp;strip=all&amp;ssl=1 80w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/sqlite_raspberry_pi_readings_mqtt.png?resize=220%2C114&amp;quality=100&amp;strip=all&amp;ssl=1 220w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/sqlite_raspberry_pi_readings_mqtt.png?resize=194%2C100&amp;quality=100&amp;strip=all&amp;ssl=1 194w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/sqlite_raspberry_pi_readings_mqtt.png?resize=280%2C145&amp;quality=100&amp;strip=all&amp;ssl=1 280w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/sqlite_raspberry_pi_readings_mqtt.png?resize=461%2C238&amp;quality=100&amp;strip=all&amp;ssl=1 461w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/sqlite_raspberry_pi_readings_mqtt.png?resize=750%2C388&amp;quality=100&amp;strip=all&amp;ssl=1 750w\" sizes=\"(max-width: 799px) 100vw, 799px\" \/><\/p>\n<p>&nbsp;<\/p>\n<h2>Wrapping up<\/h2>\n<p>That&#8217;s it for now, I hope you can take these examples and build\u00a0more features that fit your needs.<\/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 that are stored in an SQLite database. &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"ESP8266 Publishing DHT22 Readings to SQLite Database\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/esp8266-publishing-dht22-readings-to-sqlite-database\/#more-35947\" aria-label=\"Read more about ESP8266 Publishing DHT22 Readings to SQLite Database\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":1,"featured_media":35954,"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":[285,214,265,300,225,282,283,284,288,264,289,268,287,286],"tags":[],"class_list":["post-35947","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-databases","category-esp8266","category-esp8266-project","category-0-esp8266","category-home-automation","category-mqtt","category-mqtt-broker","category-mqtt-client","category-phpliteadmin","category-project","category-python","category-raspberry-pi-project","category-sql","category-sqlite"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/DHT22_RaspberryPi_ESP8266-1.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\/35947","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=35947"}],"version-history":[{"count":0,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/35947\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/35954"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=35947"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=35947"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=35947"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}