0-ESP32-MicroPython ESP32 ESP8266 MicroPython Project Tech

MicroPython: ESP32/ESP8266 with DHT11/DHT22 Web Server

MicroPython ESP32 ESP8266 with DHT11 DHT22 Web Server Temperature and humidity

On this tutorial, you’re going to discover ways to create a easy net server with the ESP32 or ESP8266 to show readings from the DHT11 or DHT22 temperature and humidity sensors.

MicroPython ESP32 ESP8266 with DHT11 DHT22 Web Server Temperature and humidity

For an introduction to the DHT11/DHT22 temperature and humidity sensors with MicroPython, learn the next information:

Conditions – Flashing MicroPython

To comply with this tutorial you want MicroPython firmware put in in your ESP32 or ESP8266 boards. You additionally want an IDE to write down and add the code to your board. We advise utilizing Thonny IDE or uPyCraft IDE:

Elements Required

To comply with this tutorial it’s essential to wire the DHT11 or DHT22 sensor to the ESP32 or ESP8266. You could use a 10okay Ohm pull-up resistor.

Right here’s an inventory of elements you must construct the circuit:

You should use the previous hyperlinks or go on to MakerAdvisor.com/instruments to seek out all of the elements on your tasks at the most effective worth!

Schematic: ESP32 with DHT11/DHT22

Wire the DHT22 or DHT11 sensor to the ESP32 improvement board as proven within the following schematic diagram.

MicroPython ESP32 with DHT11 DHT22 Web Server Temperature and humidity Circuit Schematic wiring

On this instance, we’re connecting the DHT knowledge pin to GPIO 14. Nevertheless, you need to use some other appropriate digital pin.

Discover ways to use the ESP32 GPIOs with our information: ESP32 Pinout Reference: Which GPIO pins do you have to use?

Schematic: ESP8266 with DHT11/DHT22

Comply with the subsequent tutorial in case you’re utilizing an ESP8266 board.

MicroPython ESP8266 with DHT11 DHT22 Web Server Temperature and humidity Circuit Schematic wiring

Code

For this challenge you’ll want a boot.py file and amain.py file. The boot.py file incorporates the code that solely must run as soon as on boot. This consists of importing libraries, community credentials, instantiating pins, connecting to your community, and different configurations.

The major.py file accommodates the code that runs the online server to serve information and carry out duties based mostly on the requests acquired by the shopper.

boot.py

Create a brand new file in your MicroPython IDE. Copy the next code to your boot.py file.

# Full venture particulars at https://RandomNerdTutorials.com

attempt:
import usocket as socket
besides:
import socket

import community
from machine import Pin
import dht

import esp
esp.osdebug(None)

import gc
gc.gather()

ssid = ‘REPLACE_WITH_YOUR_SSID’
password = ‘REPLACE_WITH_YOUR_PASSWORD’

station = community.WLAN(community.STA_IF)

station.lively(True)
station.join(ssid, password)

whereas station.isconnected() == False:
move

print(‘Connection profitable’)
print(station.ifconfig())

sensor = dht.DHT22(Pin(14))
#sensor = dht.DHT11(Pin(14))

View uncooked code

We’ve coated in nice element the online server code in a earlier tutorial. So, we’ll simply check out the related elements for this instance.

Import the required libraries to create an internet server.

attempt:
import usocket as socket
besides:
import socket

import community

Import the Pin class from the machine module and the dht module to learn from the DHT sensor.

from machine import Pin
import dht

You additionally have to initialize the sensor by making a dht occasion on GPIO 14 as follows:

sensor = dht.DHT22(Pin(14))

In the event you’re utilizing a DHT11 sensor, uncomment the subsequent line, and remark the earlier one:

sensor = dht.DHT11(Pin(14))

Don’t overlook so as to add your community credentials on the next strains:

ssid = ‘REPLACE_WITH_YOUR_SSID’
password = ‘REPLACE_WITH_YOUR_PASSWORD’

most important.py

Copy the next code to your primary.py file.

# Full venture particulars at https://RandomNerdTutorials.com

def read_sensor():
international temp, hum
temp = hum = zero
attempt:
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
if (isinstance(temp, float) and isinstance(hum, float)) or (isinstance(temp, int) and isinstance(hum, int)):
msg = (b’zero:three.1f,1:three.1f’.format(temp, hum))

# uncomment for Fahrenheit
#temp = temp * (9/5) + 32.zero

hum = spherical(hum, 2)
return(msg)
else:
return(‘Invalid sensor readings.’)
besides OSError as e:
return(‘Did not learn sensor.’)

def web_page():
html = “””

html
font-family: Arial;
show: inline-block;
margin: 0px auto;
text-align: middle;

h2 font-size: three.0rem;
p font-size: three.0rem;
.models font-size: 1.2rem;
.dht-labels
font-size: 1.5rem;
vertical-align:center;
padding-bottom: 15px;

ESP32 DHT Server


Temperature
“””+str(temp)+”””
°C


Humidity
“””+str(hum)+”””
%

“””
return html

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((”, 80))
s.pay attention(5)

whereas True:
conn, addr = s.settle for()
print(‘Obtained a connection from %s’ % str(addr))
request = conn.recv(1024)
print(‘Content material = %s’ % str(request))
sensor_readings = read_sensor()
print(sensor_readings)
response = web_page()
conn.ship(‘HTTP/1.1 200 OKn’)
conn.ship(‘Content material-Sort: textual content/htmln’)
conn.ship(‘Connection: closenn’)
conn.sendall(response)
conn.shut()

View uncooked code

Studying the DHT sensor

First, create a perform referred to as read_sensor() that reads temperature and humidity. You should use that perform in some other tasks through which you might want to take sensor readings from DHT sensors.

def read_sensor():

The perform begins by creating two international variables, so we will use them in all elements of the script (they’re initilazed as zero).

international temp, hum
temp = hum = zero

The temp variable holds the temperature learn from the sensor and the hum holds the humidity learn from the sensor.

Subsequent, use attempt to besides statements. Contained in the attempt assertion we attempt to get the temperature and humidity values.

Word: attempt to besides permits us to proceed the execution of this system when an exception occurs. For instance, when an error happens, a attempt block code execution is stopped and transferred to the besides block. In our instance, the exception is particularly helpful to stop the online server from crashing when we aren’t capable of learn from the sensor.

We measure the sensor through the use of the measure() technique on the sensor object.

attempt:
sensor.measure()

Then, learn the temperature with sensor.temperature() and the humidity with sensor.humidity(). Save these readings on the temp and hum variables.

temp = sensor.temperature()
hum = sensor.humidity()

Legitimate temperature and humidity readings must be of sort float (for those who’re utilizing a DHT22 sensor) or sort int (in case you’re utilizing a DHT11) sensor. So, we verify if we’ve got legitimate readings through the use of the isinstance() perform earlier than continuing.

if (isinstance(temp, float) and isinstance(hum, float)) or (isinstance(temp, int) and isinstance(hum,int)):

Notice: the isinstance() perform accepts as arguments the variable and the info sort: isinstance(variable, knowledge sort). It returns True if the variable corresponds to the inserted knowledge sort and False if it doesn’t.

If the readings are legitimate, put together a message to be printed on the Shell that features the temperature and humidity readings:

msg = (b’zero:three.1f,1:three.1f’.format(temp, hum))

If you wish to show temperature in Fahrenheit, uncomment the next line:

#temp = temp * (9/5) + 32.zero

Around the humidity studying to 2 decimal factors. This might be printed later on the internet server web page.

hum = spherical(hum, 2)

Lastly, return the message with the temperature and humidity:

return(msg)

In case we don’t get legitimate sensor readings (not float sort), we return Invalid sensor readings. message.

else:
return(‘Invalid sensor readings.’)

In case we’re not capable of learn from the sensor (for instance, in case it disconnects), return an error message.

besides OSError as e:
return(‘Did not learn sensor.’)

Net Web page

The web_page() perform returns the HTML web page. We’ll undergo every line of the HTML and see what it does.

The next tag makes your net web page responsive in any browser.

The tag is required to load the icons used within the webpage from the fontawesome web site.

Types

Between the tags, we add some CSS to type the online web page.

html
font-family: Arial;
show: inline-block;
margin: 0px auto;
text-align: middle;

h2 font-size: three.0rem;
p font-size: three.0rem;
.models font-size: 1.2rem;
.dht-labels
font-size: 1.5rem;
vertical-align:center;
padding-bottom: 15px;

Principally, we’re setting the HTML web page to show the textual content with Arial font in block with out margin, and aligned on the middle.

html
font-family: Arial;
show: inline-block;
margin: 0px auto;
text-align: middle;

We set the font measurement for the heading (h2), paragraph (p) and the models(.models) of the readings.

h2 font-size: three.0rem;
p font-size: three.0rem;
.models font-size: 1.2rem;

The labels for the readings are styled as proven under:

dht-labels
font-size: 1.5rem;
vertical-align:center;
padding-bottom: 15px;

All the earlier tags ought to go between the and tags. These tags are used to incorporate content material that isn’t immediately seen to the consumer, just like the , the tags, and the types.

HTML Physique

Contained in the tags is the place we add the online web page content material.

The

tags add a heading to the online web page. On this case, the “ESP32 DHT server” textual content, however you’ll be able to add some other textual content.

ESP32 DHT Server

Then, there are two paragraphs. One to show the temperature and the opposite to show the humidity. The paragraphs are delimited by the

and

tags. The paragraph for the temperature is the next:


Temperature
“””+str(temp)+”””
°C

And the paragraph for the humidity is on the next snipet:


Humidity
“””+str(hum)+”””
%

The tags show the fontawesome icons.

Learn how to show icons

To selected the icons, go to the Font Superior Icons web site.

ESP32/ESP8266 Web Server HTML page icons

Search the icon you’re in search of. For instance, “thermometer”.

ESP32/ESP8266 Web Server HTML page icons

Click on the specified icon. Then, you simply want to repeat the HTML textual content offered.

ESP32/ESP8266 Web Server HTML page icons

To selected the colour, you simply have to cross the type parameter with the colour in hexadecimal, as follows:

Continuing with the HTML textual content…

The subsequent line writes the phrase “Temperature” into the online web page.

Temperature

After that, we add the precise temperature worth to the HTML web page by concatenating the temp variable as proven under.

“””+str(temp)+”””

Lastly, we add the diploma image.

°C

The tags make the textual content superscript.

We use the identical strategy for the humidity paragraph.


Humidity
“””+str(hum)+”””
%

Creating the online server

After that, make the standard procedures to create a socket server.

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((”, 80))
s.pay attention(5)

whereas True:
conn, addr = s.settle for()
print(‘Obtained a connection from %s’ % str(addr))
request = conn.recv(1024)
print(‘Content material = %s’ % str(request))
sensor_readings = read_sensor()
print(sensor_readings)
response = web_page()
conn.ship(‘HTTP/1.1 200 OKn’)
conn.ship(‘Content material-Sort: textual content/htmln’)
conn.ship(‘Connection: closenn’)
conn.sendall(response)
conn.shut()

For an in-depth rationalization of this process, check with this tutorial.

Within the whereas loop, once we name the read_sensor() perform to print the sensor readings and to replace the worldwide variables temp and hum.

sensor_readings = read_sensor()
print(sensor_readings)

So, the web_page() perform generates HTML textual content with the newest sensor readings.

response = web_page()

Importing the Code

After copying the code and making any crucial modifications, you possibly can add the code to your ESP32 or ESP8266.

First, add the boot.py, after which the primary.py file to your ESP32 or ESP8266.

For those who’re utilizing Thonny IDE, you simply have to go to Gadget > Add present script as boot script or Add present script as principal script. After importing the code, press the ESP on-board RESET button.

The ESP32 or ESP8266 IP handle ought to be printed on the MicroPython Shell.

ESP32/ESP8266 DHT11 DHT22 Web Server IP Address MicroPython

Should you’re utilizing uPyCraft IDE and also you’re having hassle importing the code, go to the next tutorial and scroll right down to the “Operating Your First Script” part: Getting Began with MicroPython on ESP32 and ESP8266.

Hassle importing code with Thonny IDE? Go to this tutorial and scroll all the best way right down to the Troubleshooting Ideas for Thonny IDE part.

Demonstration

Open your browser and sort the ESP IP tackle. It is best to entry the online web page with the newest sensor readings:

ESP32/ESP8266 DHT11 DHT22 Web Server MicroPython Demonstration

On the similar time, you’ll be able to see on the MicroPython Shell, what’s happening within the background.

ESP32/ESP8266 DHT11 DHT22 Web Server MicroPython Demonstration

To get the newest sensor readings, you simply have to refresh the online web page.

Troubleshooting

In case your DHT sensor fails to get the readings, learn our DHT Troubleshooting Information that will help you repair the difficulty.

Wrapping Up

To create an internet server to show the temperature and humidity readings, you simply have to concatenate the variables that maintain the sensor readings with the HTML textual content. Ensure you get the sensor readings earlier than displaying the online web page, so that you simply all the time have the up to date temperature and humidity.

We hope you’ve discovered this tutorial helpful. If you wish to study extra about MicroPython with the ESP32 and ESP8266, check out our eBook:

You might also like the next tutorials:

Thanks for studying.