In this project you’ll 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.
In order to create the web server you will be using a Python microframework called Flask. Here’s the high level overview of the system:
First, watch the video demonstration
Recommended resources:
- You need a Raspberry Pi board – read Best Raspberry Pi Starter Kits
- Raspberry Pi Publishing MQTT Messages to ESP8266
- Raspberry Pi Web Server using Flask to Control GPIOs
- Testing Mosquitto Broker and Client on Raspbbery Pi
- How to Install Mosquitto Broker on Raspberry Pi
- What is MQTT and How It Works
- Getting Started with Node-RED on Raspberry Pi
If you like home automation and you want to build a complete home automation system, I recommend downloading my home automation course.
Basic Raspberry Pi Setup
Before you continue reading this project, please make sure you have Raspbian Operating System installed in your Raspberry Pi.
You can read my Getting Started with the Raspberry Pi Guide to install Raspbian and complete the basic setup.
Run and install Mosquitto broker
The Raspberry Pi is going to interact with the ESP8266 with the MQTT protocol. Having Mosquitto broker installed, you need to have Mosquitto broker running on the background:
pi@raspberry:~ $ mosquitto -d
Installing Flask
We’re going to use a Python microframework called Flask to turn the Raspberry Pi into web server.
To install Flask, you’ll need to have pip installed. Run the following commands to update your Pi and install pip:
pi@raspberrypi ~ $ sudo apt-get update pi@raspberrypi ~ $ sudo apt-get upgrade pi@raspberrypi ~ $ sudo apt-get install python-pip python-flask git-core
Then, you use pip to install Flask and Paho MQTT:
pi@raspberrypi ~ $ sudo pip install flask pi@raspberrypi ~ $ sudo pip install paho-mqtt
Installing SocketIO
This project uses SocketIO which allows you to create a Python Flask web page that can be asynchronously updated by your Python Flask application. This means that you don’t need to refresh the web page to see the latest readings, they are instantly updated. You’ll be installing the Flask SocketIO Python package.
pi@raspberrypi ~ $ sudo pip install flask-socketio
Creating the Python Script
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’s also subscribed to temperature and humidity MQTT topics to receive the readings.
To keep everything organized, start by creating a new folder:
pi@raspberrypi ~ $ mkdir web-server
pi@raspberrypi ~ $ cd web-server
pi@raspberrypi:~/web-server $
Create a new file called app.py.
pi@raspberrypi:~/web-server $ nano app.py
Copy and paste the following script to your Raspberry Pi
#
# Created by Rui Santos
# Complete project details: https://randomnerdtutorials.com
#
import paho.mqtt.client as mqtt
from flask import Flask, render_template, request
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("/esp8266/temperature")
client.subscribe("/esp8266/humidity")
# The callback for when a PUBLISH message is received from the ESP8266.
def on_message(client, userdata, message):
#socketio.emit('my variable')
print("Received message '" + str(message.payload) + "' on topic '"
+ message.topic + "' with QoS " + str(message.qos))
if message.topic == "/esp8266/temperature":
print("temperature update")
socketio.emit('dht_temperature', {'data': message.payload})
if message.topic == "/esp8266/humidity":
print("humidity update")
socketio.emit('dht_humidity', {'data': message.payload})
mqttc=mqtt.Client()
mqttc.on_connect = on_connect
mqttc.on_message = on_message
mqttc.connect("localhost",1883,60)
mqttc.loop_start()
# Create a dictionary called pins to store the pin number, name, and pin state:
pins = {
4 : {'name' : 'GPIO 4', 'board' : 'esp8266', 'topic' : 'esp8266/4', 'state' : 'False'},
5 : {'name' : 'GPIO 5', 'board' : 'esp8266', 'topic' : 'esp8266/5', 'state' : 'False'}
}
# Put the pin dictionary into the template data dictionary:
templateData = {
'pins' : pins
}
@app.route("/")
def main():
# Pass the template data into the template main.html and return it to the user
return render_template('main.html', async_mode=socketio.async_mode, **templateData)
# The function below is executed when someone requests a URL with the pin number and action in it:
@app.route("/<board>/<changePin>/<action>")
def action(board, changePin, action):
# Convert the pin from the URL into an integer:
changePin = int(changePin)
# Get the device name for the pin being changed:
devicePin = pins[changePin]['name']
# If the action part of the URL is "1" execute the code indented below:
if action == "1" and board == 'esp8266':
mqttc.publish(pins[changePin]['topic'],"1")
pins[changePin]['state'] = 'True'
if action == "0" and board == 'esp8266':
mqttc.publish(pins[changePin]['topic'],"0")
pins[changePin]['state'] = 'False'
# Along with the pin dictionary, put the message into the template data dictionary:
templateData = {
'pins' : pins
}
return render_template('main.html', **templateData)
@socketio.on('my event')
def handle_my_custom_event(json):
print('received json data here: ' + str(json))
if __name__ == "__main__":
socketio.run(app, host='0.0.0.0', port=8181, debug=True)
Creating the HTML File
Keeping HTML tags separated from your Python script is how you keep your project organized.Flask uses a template engine called Jinja2 that you can use to send dynamic data from your Python script to your HTML file.
Create a new folder called templates:
pi@raspberrypi:~/web-server $ mkdir templates pi@raspberrypi:~/web-server $ cd templates pi@raspberrypi:~/web-server/templates $
Create a new file called main.html.
pi@raspberrypi:~/web-server/templates $ nano main.html
Copy and paste the following template to your Pi:
<!DOCTYPE html>
<head>
<title>RPi Web Server</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
var socket = io.connect('http://' + document.domain + ':' + location.port);
socket.on('connect', function() {
socket.emit('my event', {data: 'I\'m connected!'});
});
socket.on('dht_temperature', function(msg) {
var nDate = new Date();
$('#readingsUpdated').text(nDate.getHours() + 'h:' + nDate.getMinutes() +
'm:' + nDate.getSeconds() + 's').html();
$('#temperature').text(msg.data).html();
});
socket.on('dht_humidity', function(msg) {
$('#humidity').text(msg.data).html();
});
});
</script>
</head>
<body>
<h1>RPi Web Server - ESP8266 MQTT</h1>
{% for pin in pins %}
<h2>{{ pins[pin].name }}
{% if pins[pin].state == 'True' %}
is currently <strong>on</strong></h2><div class="row"><div class="col-md-2">
<a href="/esp8266/{{pin}}/0" class="btn btn-block btn-lg btn-default" role="button">Turn off</a></div></div>
{% else %}
is currently <strong>off</strong></h2><div class="row"><div class="col-md-2">
<a href="/esp8266/{{pin}}/1" class="btn btn-block btn-lg btn-primary" role="button">Turn on</a></div></div>
{% endif %}
{% endfor %}
<h3>DHT Readings (updated <span id="readingsUpdated"></span>)</h3>
<h3>Temperature: <span id="temperature"></span>ºC</h3>
<h3>Humidity: <span id="humidity"></span>%</h3>
</body>
</html>
Programming the ESP8266
For the ESP8266 to interact with the Raspberry Pi web server, you need to install PubSubClient library. 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).
Installing the PubSubClient library
1) Click here to download the PubSubClient library. You should have a .zip folder in your Downloads folder
2) Unzip the .zip folder and you should get pubsubclient-master folder
3) Rename your folder from pubsubclient-master to pubsubclient
4) Move the pubsubclient folder to your Arduino IDE installation libraries folder
The library comes with a number of example sketches. See File > Examples > PubSubClient within the Arduino IDE software.
Installing the DHT sensor library
The DHT sensor library provides an easy way of using any DHT sensor to read temperature and humidity with your ESP8266 or Arduino boards.
1) Click here to download the DHT sensor library. You should have a .zip folder in your Downloads folder
2) Unzip the .zip folder and you should get DHT-sensor-library-master folder
3) Rename your folder from DHT-sensor-library-master to DHT
4) Move the DHT folder to your Arduino IDE installation libraries folder
5) Then, re-open your Arduino IDE
Uploading sketch
Finally, you can upload the full sketch to your ESP8266 (replace with your SSID, password and RPi IP address):
/*****
All the resources for this project:
https://randomnerdtutorials.com/
*****/
// Loading the ESP8266WiFi library and the PubSubClient library
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include "DHT.h"
// Uncomment one of the lines bellow for whatever DHT sensor type you're using!
//#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
// Change the credentials below, so your ESP8266 connects to your router
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";
// Change the variable to your Raspberry Pi IP address, so it connects to your MQTT broker
const char* mqtt_server = "YOUR_RPi_IP_Address";
// Initializes the espClient
WiFiClient espClient;
PubSubClient client(espClient);
// Connect an LED to each GPIO of your ESP8266
const int ledGPIO5 = 5;
const int ledGPIO4 = 4;
// DHT Sensor
const int DHTPin = 14;
// Initialize DHT sensor.
DHT dht(DHTPin, DHTTYPE);
// Timers auxiliar variables
long now = millis();
long lastMeasure = 0;
// Don't change the function below. This functions connects your ESP8266 to your router
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("WiFi connected - ESP IP address: ");
Serial.println(WiFi.localIP());
}
// This functions is executed when some device publishes a message to a topic that your ESP8266 is subscribed to
// Change the function below to add logic to your program, so when a device publishes a message to a topic that
// your ESP8266 is subscribed you can actually do something
void callback(String topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String messageTemp;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
messageTemp += (char)message[i];
}
Serial.println();
// Feel free to add more if statements to control more GPIOs with MQTT
// 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
if(topic=="esp8266/4"){
Serial.print("Changing GPIO 4 to ");
if(messageTemp == "1"){
digitalWrite(ledGPIO4, HIGH);
Serial.print("On");
}
else if(messageTemp == "0"){
digitalWrite(ledGPIO4, LOW);
Serial.print("Off");
}
}
if(topic=="esp8266/5"){
Serial.print("Changing GPIO 5 to ");
if(messageTemp == "1"){
digitalWrite(ledGPIO5, HIGH);
Serial.print("On");
}
else if(messageTemp == "0"){
digitalWrite(ledGPIO5, LOW);
Serial.print("Off");
}
}
Serial.println();
}
// This functions reconnects your ESP8266 to your MQTT broker
// Change the function below if you want to subscribe to more topics with your ESP8266
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
/*
YOU NEED TO CHANGE THIS NEXT LINE, IF YOU'RE HAVING PROBLEMS WITH MQTT MULTIPLE CONNECTIONS
To change the ESP device ID, you will have to give a unique name to the ESP8266.
Here's how it looks like now:
if (client.connect("ESP8266Client")) {
If you want more devices connected to the MQTT broker, you can do it like this:
if (client.connect("ESPOffice")) {
Then, for the other ESP:
if (client.connect("ESPGarage")) {
That should solve your MQTT multiple connections problem
THE SECTION IN loop() function should match your device name
*/
if (client.connect("ESP8266Client")) {
Serial.println("connected");
// Subscribe or resubscribe to a topic
// You can subscribe to more topics (to control more LEDs in this example)
client.subscribe("esp8266/4");
client.subscribe("esp8266/5");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
// The setup function sets your ESP GPIOs to Outputs, starts the serial communication at a baud rate of 115200
// Sets your mqtt broker and sets the callback function
// The callback function is what receives messages and actually controls the LEDs
void setup() {
dht.begin();
pinMode(ledGPIO4, OUTPUT);
pinMode(ledGPIO5, OUTPUT);
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
// For this project, you don't need to change anything in the loop function.
// Basically it ensures that you ESP is connected to your broker
void loop() {
if (!client.connected()) {
reconnect();
}
if(!client.loop())
/*
YOU NEED TO CHANGE THIS NEXT LINE, IF YOU'RE HAVING PROBLEMS WITH MQTT MULTIPLE CONNECTIONS
To change the ESP device ID, you will have to give a unique name to the ESP8266.
Here's how it looks like now:
client.connect("ESP8266Client");
If you want more devices connected to the MQTT broker, you can do it like this:
client.connect("ESPOffice");
Then, for the other ESP:
client.connect("ESPGarage");
That should solve your MQTT multiple connections problem
THE SECTION IN recionnect() function should match your device name
*/
client.connect("ESP8266Client");
now = millis();
// Publishes new temperature and humidity every 10 seconds
if (now - lastMeasure > 10000) {
lastMeasure = now;
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Computes temperature values in Celsius
float hic = dht.computeHeatIndex(t, h, false);
static char temperatureTemp[7];
dtostrf(hic, 6, 2, temperatureTemp);
// Uncomment to compute temperature values in Fahrenheit
// float hif = dht.computeHeatIndex(f, h);
// static char temperatureTemp[7];
// dtostrf(hic, 6, 2, temperatureTemp);
static char humidityTemp[7];
dtostrf(h, 6, 2, humidityTemp);
// Publishes Temperature and Humidity values
client.publish("/esp8266/temperature", temperatureTemp);
client.publish("/esp8266/humidity", humidityTemp);
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(f);
Serial.print(" *F\t Heat index: ");
Serial.print(hic);
Serial.println(" *C ");
// Serial.print(hif);
// Serial.println(" *F");
}
}
Schematics
To complete this project you need these next components:
- 1x ESP8266 12E – read Best ESP8266 Wi-Fi Development Boards
- 1x DHT22 Sensor
- 1x 4700 Ohm Resistor
- 2x 470 Ohm resistors
- 2x LEDs
You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!
Note: other DHT sensor types will also work with a small change in the code.
Here’s the schematics:
Important: the DHT sensor requires 5V to operate properly, so make sure you use the Vin pin from your ESP8266 that outputs 5V.
Launching the Web Server
To launch your Raspberry Pi web server move to the folder that contains the file app.py:
pi@raspberrypi:~/web-server/templates $ cd ..
Then, run the following command:
pi@raspberrypi:~/web-server $ sudo python app.py
Your web server should start immediately on port :8181!
Demonstration
Open your Raspberry Pi address in your browser by entering its IP address, in my case: http://192.168.1.98:8181
Note: you must enter your IP address followed by :8181
Here’s a video demo of the web server in action:
Wrapping up
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 SQLite database.
Like home automation? Learn more about Node-RED, Raspberry Pi, ESP8266 and Arduino with my course: Build a Home Automation System for $100.
Do you have any questions? Leave a comment down below!
Thanks for reading. If you like this post probably you might like my next ones, so please support me by subscribing my blog.
I followed your tutorial and do not see the wsp8266 values on the webpage.
I can see the publlish /response of the buttons
Open the Arduino IDE Serial monitor window and check if your ESP is actually reading any values from your sensor…
same idk why doesnt work on me, data doesnot published. i just need answer im newbie in coding i cant understand any forum other than this
Rui, Thanks for this one, very helpful. I plan to implement it as soon as we get moved.
I will use the BME280 for temp,humidity, and barometric pressure.
I will also use the HMC6352 compass for wind dir along with a 6 wire slip-ring to keep wires from twisting. I have tested and works well.
Keep up the good work my friend
Yes, I just bought some BME280 a few days ago. I really like that sensor too.
Thanks for sharing your thoughts
Great tutorial. I’m excited to get Flask working. When I start app.py I get the following stdout:
WebSocket transport not available. Install eventlet or gevent and gevent-websocket for improved performance.
* Running on http://0.0.0.0:8181/
* Restarting with reloader
When I try to access the website I get a lot of errors starting wtih:
UnicodeDecodeError
UnicodeDecodeError: ‘utf8’ codec can’t decode byte 0xba in position 2565: invalid start byte
Any thoughts?
Bruster
Sounds like this is missing in your installation: github.com/miguelgrinberg/Flask-SocketIO/issues/153
Hi Rui,
Great post!
You could do this perhaps more efficient by using Node-red on the PI?
Regards,
Koen
Hi Koen,
I could and I will, but this is a more “advanced” project series that shows how to build a Python web server from scratch with most of the functionalities that you would like to have on a home automation system.
Thanks for the suggestion,
Regards,
Rui
root@minibian:~# sudo pip install flask
-bash: sudo: command not found
root@minibian:~#
help plz
You have to install Python pip package
Hi Rui,
Great project!
I have one question: In my setup I see that the app.py is receiving the correct temperature value. But, in the webpage it shows the humidity value duplicated instead o temperature value.
I copied and pasted your sources and cannot find the error…
Any ideas?
Thanks!
Hi Krishna,
I’ve just checked my code again and I don’t understand how that could be possible…
All the variable assignments are done properly…
Hi Rui, Thanks for the tutorial, I have the majority of the project working!! I did have to change the connection of the 4700 resistor, from being connected between data & gnd, to data & V+ to get temperature information.
I am seeing the temp on the serial output, happily updating, but is doesn’t show via the web page. I will investigate and post back, unless you beat me to it!!.
Hi Tony,
I’m not sure. did you enter the right MQTT broker ip address in your Arduino code?
Sounds like the MQTT publishing is not working…
The webpage on the PI is updating and showing the light (GPIO) status correctly. I have run the mosquitto in verbose mode on the PI, and i can see publishings appearing.
Received PUBLISH from paho/0A56F50600CD26C74D (d0, q0, r0, m0, ‘esp8266/5’, … (1 bytes))
Received PUBLISH from ESP8266Client (d0, q0, r0, m0, ‘/esp8266/humidity’, … (6 bytes))
I am not sure where the mosquitto service ‘stores’ information, to see if anything is being updated (if at all?)
i’ve attempted to decipher the sketch, but i can’t work out where the temp/humidity publication takes place…
i’ve opened a couple of terminal windows, and subscribed to the temp and humidity feeds, and the data is coming through fine, which leaves it as a web page issue. I will trawl through and find out if i’ve missed anything!
I know it has been a while, but have you figured this out? I am having the same type of issues. I can turn LEDs on and Off, but I can’t get the temp and humidity to display on the web page. Once in a great while (maybe 1% of the time and only when I refresh manually), it will flash up there, then it’s gone. Any ideas?
Thanks for Great tutorial. I planned to extend the numbers of nodes about 50 with soil moisture sensors. Is this server good enough to handle communication of large nodes? I am beginner in MQTT. Please Guide!
Yes, MQTT is powerful enough to handle thousands of requests easily. In fact, this is one of the best communication protocols to use with that application
Thanks,
Rui
Hi, Rui.Thanks for this tutorial.It really works, but there is a problem when i run python app.py, then it show a line before the IP address: The websocket transport is not available, install eventlet or gevent and gevent-websocket for improved performance. is there anything wrong? i followed your tutorial step by step. Should I install eventlet?
hi rui nice tutorial
i have a question please when i run the python code i get this messge on the webpage
UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xba in position 2044: invalid start byte
Try to create a new file from scratch and make sure that all the quotation mark characters ” or ‘ are correctly inserted after copying the code from this web page
Did you ever figure this out? I am having the same type of an issue. I already redid everything with totally new files and checked the quote marks on the Pi itself to, I think, make sure they are right.
I figured it out. It was an encoding issue for the degree symbol. I changed the temperature display line in the HTML file to
Temperature: °
° is the HTML version of the degree symbol.
Rui,
thx for tutorial, everything works pefect !!
I’ve added sudo python /PathToFile/app.py command to /etc/rc.local file but it doesn’t won’t to start on boot. Does it require some more to do, ie. additional privlages ?
Thx!
Marcin
I’m glad it worked. I’m not sure what’s missing, but I recommend reading this tutorial and try another method to start a Python script on boot: dexterindustries.com/howto/run-a-program-on-your-raspberry-pi-at-startup/
I solved the problem with boot at startup, thx.
Have you try ESP.deepSleep? Could you give me a hint what should i have to change in code to use it ? I put it at the end of the setup part but it does’t work properly. ESP goes to sleep, wakes up but doesn’t send any informations.
Txh in advance.
thanks a lot
i could not find the programing codes (esp and python )
Here is the Raspberry Pi code: https://raw.githubusercontent.com/RuiSantosdotme/Random-Nerd-Tutorials/master/Projects/RPi-ESP-DHT/app.py
And the ESP8266 code: https://raw.githubusercontent.com/RuiSantosdotme/Random-Nerd-Tutorials/master/Projects/RPi-ESP-DHT/esp8266_dht.ino
thank you
can i get html code (main.html) ??
Here it is: https://github.com/RuiSantosdotme/Random-Nerd-Tutorials/blob/master/Projects/RPi-ESP-DHT/templates/main.html
Regards,
Sara
hello, I’m crazy, 5 times I copy it, led works, but no temperature, I’ve deleted Celcius sign *, I’ve updated boostrap links. Anything else ? to review? esp I’ve bought it works and sends me the info *. Thank you very much and great contribution
Hi RUI
I could implement it successfully. In addition to this I had done some experiment by adding another GPIO pin in the same ESP 12E and also modified the program successfully. I wanted to add another ESP12E with temperature sensor so that I could receive two sets of readings from two different locations. I tries a lot but could not run app.py file.Every time it showed some error like indentation error:unexpected error.
Can you guide me in this regard.
Thanks
I have followed your procedure. Everything is going well except that temperature and humidity readings are not being displayed on the browser. It says:
DHT Readings (updated)
Temperature: *C
Humidity: %
That’s it.
Moreover, how can I save these readings in a file on my pi?
Hi.
It is probably something to do with the DHT22 sensor wiring or power source.
Can you try this simple example and see if you are able to get readings? https://randomnerdtutorials.com/complete-guide-for-dht11dht22-humidity-and-temperature-sensor-with-arduino/
There are Python methods that you can easily use in your script to create a file and save data. This tutorial explains in great detail and in an easy way how to deal with files using Python:
pythonforbeginners.com/files/reading-and-writing-files-in-python
I hope this helps.
Regards,
Sara 🙂
hi
can I publish to mqtt topics using a web user interface running on esp-01/esp-8266/esp-32, on my local wireless network.
I’ll be waiting for your reply and be very thankful for your guidance.
Hi Nouman.
What do you mean by “publish to topics using a web user interface”?
Regards,
Sara
Hi
I mean that for example in this project, “ESP8266 Publishing DHT22 Readings with MQTT to Raspberry Pi”, Raspberry Pi is running a web server from which we can control two GPIOs of ESP8266 through “Mosquitto_pub” as well as get “Temperature” and “Humidity” measurements through “Mosquitto_sub”.
Can we run the same web server on ESP-01 or ESP8266 or ESP32 ?
Hope you will get my point.
I’ll be waiting for your reply and be very thankful for your guidance.
Hi Nouman.
Yes, you can have the webserver running on an ESP-01, ESP8266 or ESP32. But the code we use to create Raspberry Pi web server is not compatible with those boards.
To build a web server with those boards, you can follow the next tutorials:
– https://randomnerdtutorials.com/esp8266-web-server/
– https://randomnerdtutorials.com/esp32-web-server-arduino-ide/
Then, you can learn more about MQTT with these tutorials:
– https://randomnerdtutorials.com/esp32-mqtt-publish-subscribe-arduino-ide/
– https://randomnerdtutorials.com/esp8266-and-node-red-with-mqtt/
I hope this helps.
Regards,
Sara
HI,
I tried everything, but I can’t connect the esp8266 with my raspberry pi web-server. It says “connection…….failed, rc=-2 try again in 5 seconds”
help plz
Kind regards
Hi Max.
Make sure the Raspeberry Pi is running the MQTTT broker. Also, make sure you’ve inserted the right IP address of your MQTT broker.
https://randomnerdtutorials.com/testing-mosquitto-broker-and-client-on-raspbbery-pi/
Regards,
Sara
Hi,
i want code for
ESP8266 Publishing pulse sensor Readings with MQTT to Raspberry Pi
plzz help me to get this
regards
Hi.
We don’t have any tutorials for the pulse sensor.
But the publishing process is the same as with any other reading like temperature or humidity.
You just need to prepare your code to read the pulse sensors instead of temperature or humidity.
Regards,
Sara
I also had the same issue of not showing temperature and humidity measurements in the HTML page. There is a known issue with the backward compatibility bewteen the socket.IO libraries of both Python and HTML (JavaScript). the official websocket.io web page:
https://socket.io/docs/v4/client-installation/
The following versions worked for me:
Flask== 1.1.2
Flask-SocketIO==5.3.2
python-socketio==5.7.2
simple-websocket==0.7.0
As for the socket.io.js library in the section of the HTML, the library version that worked for me was:
“type = text/javascript” src = “//cdnjs.cloudflare.com/ajax/libs/socket.io/4.2.0/xocket.io.js” >
Additionally, you need to remove the ‘b’ character that python adds in the MQTT message payload and that the HTML can’t recognize. In my case, changing “message.payload” by “str(message.payload).strip(“‘b”)” in both the “if” clauses of the “def on_message” callback, worked out fine.
Hi, I applied your solution step by step but I got another problem! The readings have be displayed for a few second and then disappeared! I restarted the circuit but the readings have not been displayed on the web server. Any idea what is the problem?
In order to modify a version of a package library in python you can use the “pip install –upgrade” command. For instance:
pip install –upgrade python-socketio==5.3.2
May I know how to add more clients to this tutorial? Any tutorials to refer? Is it possible to handle different model of ESP8266 (clients) at the same time? Hopefully you can answer my question. Thank you.
Hi.
Yes, it is possible.
You just need to upload the same code to all boards.
If you want each board to publish in a specific topic, you just need to use different topics. For example:
board1/esp8266/temperature
board2/esp8266/temperature
and so on.
I hope this helps.
Regards,
Sara
I have issue of getting the readings of Humidity and temperature as follows:
DHT Readings (updated )
Temperature: ºC
Humidity: %
From the raspberry pi, I’m getting this messages:
“GET / HTTP/1.1” 200 –
“GET /socket.io/?EIO=3&transport=polling&t=1682928889001-0 HTTP/1.1” 400 –
May i know what the issues of not getting the readings?
additional findings is from the arduino ide’s serial monitor message is getting ” Attempting MQTT connection failed…., rc=2 try again in 5 seconds
Probably I know the reasons. Because mqtt I added mosquitto username and password authentication. I have modified app.py in order to get “connect code 0” But i still getting rc= 2 from Arduino ide. Any other parts that I may have left out? Please help. thank you.
Did you add the mqtt broker username and password on the Arduino sketch?
Yes. but still giving the same message. ” Attempting MQTT connection failed…., rc=2 try again in 5 seconds”
Also try to restart your Raspberry Pi to restart the MQTT broker.
Regards,
Sara
additional findings is from the arduino ide’s serial monitor message is getting ” Attempting MQTT connection failed…., rc=2 try again in 5 seconds
Hi.
Take a look at the Mosquitto broker installation tutorial: https://randomnerdtutorials.com/how-to-install-mosquitto-broker-on-raspberry-pi/
Check the section “Enable Remote Access/ Authentication”.
To test it right away, follow the section without authentication.
Regards,
Sara
Hi it works! thanks. May i check with you how do i change the QoS to 1 or 2?
Hi , is there any reason I’m getting two sets of results on the web server page as below ?
ID Temperature Humidity Date Time Device
1037 19.89 53.3 2023-11-22 16:44:46 esp8266
1036 19.89 53.3 2023-11-22 16:44:46 esp8266
1035 19.89 53.4 2023-11-22 16:44:16 esp8266
1034 19.89 53.4 2023-11-22 16:44:16 esp8266
by the way brilliant topic to try , I’ve learnt loads about it all, thanks so much for taking the time to prepare this tutorial