MicroPython: DHT11/DHT22 Web Server with ESP32/ESP8266 (Weather Station)

In this tutorial, we will learn to interface DHT11 and DHT22 sensors with ESP32 and ESP8266 using Micropython firmware. We will use upycraft and Thonny IDE. We will create a DHT11/DHT22 web server with MicroPython. 

micropython esp32 esp8266 dht11 dht22 web server

In the DHT web server, we will see how to display temperature and humidity values on the web page which will be accessible through an IP address. All devices which are connected to the same router to which ESP32/ESP8266 device is connected can access this web page using an IP address. 

DHT11/DHT22 Web Server Introduction 

Have you ever seen a remote monitoring system where an HMI-based system displays remote sensor values? Did you ever try to make a web server that can control or display values of different sensors on your local server?

 If yes, then this tutorial is a getting started step by step guide for you. We will learn the example of interfacing DHT11 and DHT22  with ESP32 and how to display its values on the web server.

DHT11 and DHT22 sensors provide temperature and humidity output on a single wire protocol. We will measure these values with the help of the ESP32/ESP8266 using MicroPython firmware. On top of that, we will use the network and socket API of microPython to create a socket server on ESP32/ESP8266 which we will serve the web page to a socket client. ESP32/ESP8266 web server will contain a HTML document which displays temperature and humidity values.This web page will be used to display temperature value both in Celsius and Fahrenheit and humidity percentage.

ESP32 ESP82266 DHT11 DHT22 MicroPython Web Server temperature and humidity

Note: ESP32/ESP8266 boards will be used in station mode to connect these boards to your local WiFi network. But you can also create a soft access point web server with ESP32/ESP8266. 

Prerequisites 

Before we start this lesson make sure you are familiar with and have the latest version of MicroPython firmware installed in your ESP boards and have a running Integrated Development Environment(IDE) in which we will be doing the programming. We will be using the same uPyCraft IDE as we have done previously when we learned how to blink and chase LEDs in microPython.

If you are using Thonny IDE, you can check this getting started guide:

DHT11/DHT22 Introduction 

The DHT11/DHT22 is a sensor which measures relative humidity and temperature sensor. It provides a calibrated digital output with a 1-wire protocol. Both sensors are inexpensive. They are quite similar to each other with some differences of specifications. 

DHT22 is almost similar to the DHT11 but the former measures temperature and humidity with higher accuracy and supports wider range.

DHT11 vs DHT22

The following table lists the comparison of both DHT sensors. 

DHT22DHT11
Temperature-40 to 80 ºC +/- 0.5ºC0 to 50 ºC +/-2 ºC
Humidity 0 to 100% +/-2%20 to 90% +/-5%
ResolutionHumidity: 0.1%Temperature: 0.1ºCHumidity: 1%Temperature: 1ºC
Operating Voltage3- 6 V DC( directly powerable from ESP32/ESP8266)3-5.5 V DC( directly powerable from ESP32/ESP8266)
Sampling time2 seconds1 second
Current rating$4 to $10$1 to $5
Output data typefloatint
Pinout4-pin (same as DHT11)4-pin (same as DHT22)
Price ($)52

As you can see from the above comparison table that DHT22 offers wider temperature range and resolution for temperature and humidity. But it is more expensive than DHT11. However, DHT11 has a better sampling period. Furthermore, the operating voltage range for both sensors is almost and we can directly power these sensors from power pins of ESP32 and ESP8266. 

Regardless of above differences, both DHT sensors have the same working principle and same pinout. We can use the same MicroPython script to read temperature and humidity readings by selecting DHT type inside the code. 

DHT sensors are pre-calibrated. We can directly connect them with ESP32/ESP8266 to obtain sensor output reading. They are internally composed of a humidity sensing sensor and a thermistor. These two components measure humidity and temperature. 

DHT11/DHT22 Pinout 

This following figure shows the pinout diagram of DHT sensors. DHT sensor consists of four pins. But on DHT modules only three pins are exposed to the pinout of the module and10k ohm pull-up resistor is internally connected to pin 2. 

dht11 dht22 pinout diagram

Pin Description

The following lists the pinout of the DHT sensor and their brief description. Pin number starts from left to right when you hold the sensor from the front end. 

DHT11/DHT22 PinConnection with ESP32/ESP8266
1 ( Vcc)3.3V 
2 (Data Out)Any GPIO pins of ESP boards along with 10k ohm pull-up resistor
3 (NC)Not used
4 (GND)Ground
  • Vcc is the power supply pin. Apply voltage in a range of 3.3 V to 5.0 V to this pin
  • Data Out is the digital output pin. It sends out the value of measured temperature and humidity in the form of serial data
  • N/C is not connected
  • GND: Connect the GND pin 

Parts Required 

To make a DHT web server with MicroPython, you must connect a 10k ohm pull-up resistor with a data_out pin of DHT11/DHT22. You will need following components

  • ESP32/ESP8266
  • DHT11 and DHT22
  • Bread Board
  • 10K ohm resistor
  • Jumper wires

DHT11/DHT22 Interfacing with ESP32/ESP8266

Connect the DHT11/DHT22 to ESP32/ESP8266 along with a 10K ohm pull-up resistor. The connection diagrams are shown in the pictures below.

DHT11 DHT22 Interfacing with ESP32 MicroPython
DHT22 Interfacing with ESP32 MicroPython
DHT11 DHT22 Interfacing with ESP8266 NodeMCU MicroPython
DHT22 Interfacing with ESP8266 NodeMCU
  • The first pin for both sensors is a power supply(Vcc) pin. Connect it with the 3.3 volt pin of ESP32 and ESP8266.
  • Data out is the pin through which we get temperature and humidity samples from the DHT sensor. Connect this pin with GPIO4 of ESP32 and also connect the data pin with a 10k pull-up resistor. But you can also use any digital pin of ESP32 and ESP8266

A Pull-up resistor is used to keep the data pin high for proper communication between the microcontroller and sensor. You can check the datasheet of DHT11 and DHT22 to get more information about it. DHT22 is also known by the name of AM2302.

  • Third pin is not used
  • Connect the fourth pin (GND) to the ground pin of the ESP32/ESP8266 board

Create DHT11/DHT22 Web Server with MicroPython 

To create a DHT11/DHT22 web server with ESP32/ESP8266 using MicroPython, we need to create two MicroPython files such as boot.py and main.py. The boot.py file is a microPython script which runs once ESP32/ESP8266 boots. The main.py file contains HTML document, socket server to listen to socket client requests, script to send and receive data through MicroPython socket API. 

First connect ESP32 or ESP8266 boards with your computer. Select the serial port in uPyCraft IDE and go to Tools>Serial and select the COM port to which ESP32/ESP8266 board is connected. 

Selecting serial port upycraft IDE

Besides serial port, you should also select the module, go to Tools>Board and select ESP32/ESP8266. Here you can see that two serial ports are showing in my case. Because we have connected both ESP32 and ESP8266 boards with my computer.

Selecting board upycraft IDE

Create a new file MicroPython file and click on the “Save file” button to save the file on your computer. When you click on the “Save file” button, A new window as shown below will open. Save this file with the name of boot.py.

upycraft IDE save file and give name

Similarly, Create one more file and give it the name of main.py. Copy the content of main.py to this file given in the next section. 

Now upload both these files to ESP boards. After downloading, you will see two files under the device option in UpyCraft IDE as shown below:

Create DHT Web server files Micropython

Boot.py File ESP32/ ESP8266 DHT MicroPython web server 

Copy the following code to “boot.py” file. 

try:
  import usocket as socket
except:
  import socket

import network
from machine import Pin
import dht

import esp
esp.osdebug(None)

import gc
gc.collect()

ssid = 'Bilal'
password = 'mominmomin'

station = network.WLAN(network.STA_IF)

station.active(True)
station.connect(ssid, password)

while station.isconnected() == False:
  pass

print('Connection successful')
print(station.ifconfig())

dht_pin = dht.DHT22(Pin(14))  # Comment it if you are using DHT11 and uncomment the next line
#dht_pin = dht.DHT11(Pin(4)) # Uncomment it if you are using DHT11 and comment the above line

In the boot.py file, we will include MicroPython socket programming methods to connect ESP32/ESP8266 to WiFi networks. Furthermore, we will also import Pin and dht class from the machine module of MicroPython to configure GPIO4 pin to be used to read temperature and humidity from DHT11/DHT22. 

Importing Socket Module

Sockets provides end-to-end communication between a server and a client on a connection oriented barrier. That means a server and a client needs to establish a connection before transferring data between to each other. 

We will use the sockets library of MicroPython to create a slider switch web server. MicroPython socket API is a subset of the corresponding Python Socket module. First, we should import the socket module as follows:

try:
  import usocket as socket
except:
  import socket

Importing Network Library

To use the socket module, we need to connect ESP32 and ESP8266 with our local WiFi network. For that purpose, we use a network library. Micropython’s network API provides methods to connect ESP32/ESP8266 modules to a WiFi network and to perform routing configuration and settings. Import the network library as follows:

import network 

Disabling Debug Output

By default, ESP32/ESP8266 boards print debugging output on the serial console. Debug output is already disabled on some official MicroPython boards. But, in the case of ESP32 and ESP8266, we will have to disable debug output manually by adding the following lines to the MicroPython code of our project. It is recommended to add these lines to the boot.py file.

import esp
esp.osdebug(None)

Like python, MicroPython is also an object-oriented programming language. All modules contain classes of different peripherals and other libraries such as socket, network, Pins, ADC, PWM, etc. We create objects of these classes to use in our MicroPython code. MicroPython provides a module to perform automation memory management of created objects. The “gc” module is a garbage collector API provided in MicroPython which is a subset of corresponding Python implementation. The collect() method automatically reclaim memory occupied by objects which are no longer required by the MicroPython program. To use the “gc” module in your application, first import the “gc” module. After that call collect() method as follows: 

import gc     #Import garbage collector module
gc.collect()   #Perform garbage collection

MicroPython: Connecting to a WiFi Network

As discussed earlier, we use a network module to connect to a WiFi router. The network module provides two WiFi interfaces. One for the station, when the ESP32/ESP8266 connects to a router. Similarly, one for the access point that is for other devices to connect to the ESP8266/ESP32. Because we want to connect ESP32 and ESP8266 to a WiFi router. Therefore, we will use the station mode interface. We create an instance of this object using the station interface (network.STA_IF).

station = network.WLAN(network.STA_IF)

The network.WLAN() is used to create a.WLAN network interface object. 

Supported interfaces ar:

  • network.STA_IF (station mode)
  • network.AP_IF (Soft access point mode)

After that, activate the station by passing the “True” argument to the sta_if.active() method. Here station is an instance of the object which we created in the last step. We will use the same instance to access all methods of network class. 

station .active(True)

We define two variables that hold the name and password of your WiFi network. The following variables hold your network credentials:

ssid= 'Enter_Your_WiFI_Name_Here'
password = 'Enter_Your_WiFI_Passoword_Here'

You must enter your WiFi credentials such as network SSID and password in the above two variables before uploading this code to ESP32 and ESP8266. Furthermore, make sure to write the correct SSID and password. Otherwise, your ESP boards will not connect to the WiFi router. 

The connect() method is used to connect to the specified wireless network using the specified WiFi name and password. 

station.connect(ssid, password)

In station mode, isconnected() method returns “True” if ESP32/PES8266 successfully connects to a WiFi network and a device also assigned a valid IP address. Otherwise, it returns “False”. This statement checks if the ESP device connects to the WiFi or not. The code does not move to the next step till the ESP board is not connected to the WiFi network. 

while station.isconnected() == False:
 pass

After a WiFi connection is established on ESP boards with a WiFi router, an IP address has already been assigned to ESP devices. The ifconfig() method provides an IP address assigned to the ESP32/ESP8266 device. In this statement, we print the IP address using the ifconfig() method on the sta_if object which we created previously. .

print('Connection successful')
print(sta_if.ifconfig())

Importing DHT Library

To initialize DHT11/DHT22 sensors, create an instance of the DHT class on GPIO14  by creating an object with the name of dht_pin. 

dht_pin= dht.DHT22(Pin(4))  # Comment it if you are using DHT11 and uncomment the next line
#dht_pin = dht.DHT11(Pin(4)) # Uncomment it if you are using DHT11 and comment the above line

DHT MicroPython Web Server Main.py File

Copy the following code to main.py which we created earlier. 

def read_dht():
  global temp, hum
  temp = hum = 0
  try:
    dht_pin.measure()
    temp = dht_pin.temperature()
    hum = dht_pin.humidity()
    if (isinstance(temp, float) and isinstance(hum, float)) or (isinstance(temp, int) and isinstance(hum, int)):
      msg = (b'{0:3.1f},{1:3.1f}'.format(temp, hum))

      # uncomment for Fahrenheit
      #temp = temp * (9/5) + 32.0

      hum = round(hum, 2)
      return(msg)
    else:
      return('Invalid sensor readings.')
  except OSError as e:
    return('Failed to read sensor.')

def web_page():
  html = """<html><head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    body {
      padding: 20px;
      margin: auto;
      width: 50%;
      text-align: center;
    }
    .progress { background-color: #F5F5F5; }
    .progress.vertical {
      position: relative;
      width: 25%;
      height: 60%;
      display: inline-block;
      margin: 20px;
    }
    .progress.vertical > .progress-bar {
      width: 100% !important;
      position: absolute;bottom: 0;
    }
    .progress-bar { background: linear-gradient(to top, hsl(352, 51%, 62%) 0%, #f12711 100%); }
    .progress-bar-hum { background: linear-gradient(to top, #9CECFB 0%, hsl(256, 100%, 51%) 50%, hsl(217, 94%, 20%) 100%); }
    .progress-bar-temp { background: linear-gradient(to top, #9CECFB 0%, hsl(256, 100%, 51%) 50%, hsl(217, 94%, 20%) 100%); }
    p {
      position: absolute;
      font-size: 1.5rem;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      z-index: 5;
    }
  </style>
</head><body>
  <h1>MicroPython ESP DHT11/DHT22 Web Server</h1>
  <div class="progress vertical">
    <p>"""+str(temp)+"""&deg;C<p>
    <div role="progressbar" style="height: """+str(temp)+"""%;" class="progress-bar progress-bar-temp, "></div>
  </div>
  <div class="progress vertical">
    <p>"""+str(hum)+"""%</p>
    <div role="progressbar" style="height: """+str(hum)+"""%;" class="progress-bar progress-bar-hum"></div>
  </div>
</body></html>"""
  return html

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)

while True:
  conn, addr = s.accept()
  print('Got a connection from %s' % str(addr))
  request = conn.recv(1024)
  print('Content = %s' % str(request))
  sensor_readings = read_dht()
  print(sensor_readings)
  response = web_page()
  conn.send('HTTP/1.1 200 OK\n')
  conn.send('Content-Type: text/html\n')
  conn.send('Connection: close\n\n')
  conn.sendall(response)
  conn.close()

DHT Data Reading Function

In the main.py file, first, define a function read_dht() which reads the temperature and humidity readings from DHT11/DHT22 sensors. We can use the function in our other projects to read temperature and humidity values from DHT sensors.

def read_dht():

Inside the rad_dht() function, we declare two global variables and initialize them to zero. The reason we have declared them as global variables is because we want to use these variables throughout our MicroPython script. The temp and hum variables will hold temperature and humidity values ,respectively.

 global temp, hum
 temp = hum = 0

Inside the main definition of read_dht() routine, try and except statements are used to take DHT sensor reading and to avoid exceptions, respectively. The main purpose of try and except statements is to avoid exceptions and continue the execution of the program when an exception occurs. It is useful to avoid web servers from crashing when a web client requests a web page and the DHT sensor is not able to provide sensor reading. 

Next, take a sample from the DHT sensor by using an object “dht.pin” we created previously on measure() method.

 try:
    dht_pin.measure()

After that reads the values of temperature and humidity by using respective methods on an object such as dht_pin.temperature() and dht_pin.humidity(). 

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

DHT22 sensor provides temperature and humidity reading in float data type. On the other hand, the DHT11 sensor provides temperature and humidity reading in =int data type. Therefore, we should validate the readings by checking them using isinstance() method. The isinstance() routine takes a variable and its type as an argument. If both arguments have the same data type, it will return True. Otherwise, it returns False. 

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

 If you want to print temperature and humidity values on the MicroPython shell console, this statement saves both readings in the form string. Afterward, we can display them on the shell console using print(mesg) statement. 

msg = (b'{0:3.1f},{1:3.1f}'.format(temp, hum))

In case you want to measure temperature in Fahrenheit, this statement converts measured temperature into Fahrenheit. Uncomment this line for Fahrenheit. 

# uncomment for Fahrenheit
#temp = temp * (9/5) + 32.0

The round() method will round off the humidity reading up to 2 decimal points and returns the message. 

hum = round(hum, 2)
return(msg)

If isinstance() instance returns False that means we don’t receive valid temperature and humidity readings from DHT11 or DHT22 sensors. In that case, we will only return ‘Invalid sensor readings.’ message. 

else:
    return('Invalid sensor readings.')

 The except statement will execute if the measure() method will not be able to take sensor samples due to many reasons such as DHT disconnection, faulty sensor, etc. 


except OSError as e:
    return('Failed to read sensor.')

This is how we can take temperature and humidity samples from DHT11/DHT22 using MicroPython and ES32/ESP8266. 

Create DHT Sensor Web page 

The main part of our MicroPython script starts with defining a web_page(). The function serves HTML and CSS files to create a web page for ESP32/ESP8266 web server to display temperature and humidity values. We use a progress bar in this tutorial to display sensor readings. 

Note: We can also create a variable to hold HTML file instead of creating a function. But using a function to serve web pages provide support to serve dynamic web pages where HTML code may change according to different operations that we perform inside the microPython script. 

Now let’s go through each line of HTML code to understand how it builds the web page. 

HTML is a hypertext markup language which is used to build web pages. All web browsers understand this language and can read web pages which are based on HTML language. 

In HTML, we place all the content of a web page between <html> and </html> tags. The <html> tag shows the beginning of a web page and the  </html> indicates the end of a web page. 

HTML code mainly includes two parts such as head and body. The head part contains CSS, scripts, meta tags, links of external resources and styling codes. It is placed between <head> and </head> tags. 

Note: Whatever code or data, we place inside the head tags will not be visible to the user. It is only used to enhance the functionality of a web page such as scripts and styles, etc. 

Inside head tags, create a <meta> tag to make the web page responsive in any web browser.

<meta name="viewport" content="width=device-width, initial-scale=1">

Styling DHT Web Page with CSS

CSS is used to give styles to a web page. To add CSS files in head tags, we use <style></style> tags. This CSS code styles the progress bar and web page.

<style>
    body {
      padding: 20px;
      margin: auto;
      width: 50%;
      text-align: center;
    }
    .progress { background-color: #F5F5F5; }
    .progress.vertical {
      position: relative;
      width: 25%;
      height: 60%;
      display: inline-block;
      margin: 20px;
    }
    .progress.vertical > .progress-bar {
      width: 100% !important;
      position: absolute;bottom: 0;
    }
    .progress-bar { background: linear-gradient(to top, hsl(352, 51%, 62%) 0%, #f12711 100%); }
    .progress-bar-hum { background: linear-gradient(to top, #9CECFB 0%, hsl(256, 100%, 51%) 50%, hsl(217, 94%, 20%) 100%); }
    .progress-bar-temp { background: linear-gradient(to top, #9CECFB 0%, hsl(256, 100%, 51%) 50%, hsl(217, 94%, 20%) 100%); }
    p {
      position: absolute;
      font-size: 1.5rem;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      z-index: 5;
    }
  </style>

This CSS code sets text alignment, padding, margin and width of body tags of HTML document.  We want to display temperature and humidity on progress bars and want them to show at the center location of the web page. 

 body {
      padding: 20px;
      margin: auto;
      width: 50%;
      text-align: center;
    }

Creating Progress Bar

In this MicroPython DHT web server example, we use two progress bars to display sensor reading by taking measurements with the help of ESP32 and ESP8266. HTML, by default, does not support vertical progress bars. Therefore, we use CSS to make vertical progress bars and to give styles to them. This code performs basic styling of progress bars. The progress-bar-hum sets the color of the humidity progress bar from light blue to dark blue and  .progress-bar-temp sets the color of the temperature progress bar from light red to dark red. 

.progress { background-color: #F5F5F5; }
    .progress.vertical {
      position: relative;
      width: 25%;
      height: 60%;
      display: inline-block;
      margin: 20px;
    }
    .progress.vertical > .progress-bar {
      width: 100% !important;
      position: absolute;bottom: 0;
    }
    .progress-bar { background: linear-gradient(to top, hsl(352, 51%, 62%) 0%, #f12711 100%); }
    .progress-bar-hum { background: linear-gradient(to top, #9CECFB 0%, hsl(256, 100%, 51%) 50%, hsl(217, 94%, 20%) 100%); }
    .progress-bar-temp { background: linear-gradient(to top, #9CECFB 0%, hsl(256, 100%, 51%) 50%, hsl(217, 94%, 20%) 100%); }
    p {
      position: absolute;
      font-size: 1.5rem;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      z-index: 5;
    }

HTML Web Page Body

The second most important part of an HTML document is the body which goes inside the tags <body> and </body>. The body part includes the main content of the web page such as headings, images, buttons, icons, tables, charts, etc. For example, in this DHT11/DHT22 ESP microPython based web server, the body part includes heading and two progress bars. 

In HTML h2 tag inserts heading to the web page and different levels of headings can be added such as h1,h2, h3,h4, h5, h6. Here h1 is a top-most level heading and h6 is the lowest-level heading. In this example, we add the text “MicroPython ESP DHT11/DHT22 Web Server” heading of level 1. But you can add any other text as per your requirement. 

<h1>MicroPython ESP DHT11/DHT22 Web Server</h1>

Next, there are two HTML paragraphs and two div tags components in our web page. The <p> and </p> tags are used to insert paragraphs in the HTML body. 

These div tags are used to add CSS class to our body part of an HTML document. This code displays a vertical progress bar to display temperature and humidity readings. 

<div class="progress vertical">
    <p>"""+str(temp)+"""&deg;C<p>
    <div role="progressbar" style="height: """+str(temp)+"""%;" class="progress-bar progress-bar-temp, "></div>
  </div>
  <div class="progress vertical">
    <p>"""+str(hum)+"""%</p>
    <div role="progressbar" style="height: """+str(hum)+"""%;" class="progress-bar progress-bar-hum"></div>
  </div>

The ‘+’ operator is used to concatenate sensor readings in string data type into web pages. For example, these two lines concatenate temperature and humidity values into a web page. Moreover, the str() function converts the sensor reading into strings.

<p>"""+str(temp)+"""&deg;C<p>
<p>"""+str(hum)+"""%</p>

The following code sets the height of temperature and humidity progress bars by using string concatenation operation as discussed in the last paragraph. 

<div role="progressbar" style="height: """+str(temp)+"""%;" class="progress-bar progress-bar-temp, "></div>
<div role="progressbar" style="height: """+str(hum)+"""%;" class="progress-bar progress-bar-hum"></div>

Create DHT11/DHT22 Web Server with MicroPython Socket API

To establish a socket using MicroPython on the server side which is ESP32 or ESP8266, we need to perform the following steps: 

We can create a socket using the socket.socket() function available in the socket module of MicroPython. General syntax to create a socket object is as follows: 

s = socket.socket (socket_family, socket_type, protocol=0)

For this example, we create a socket object with a socket family of AF_INET transport mechanism and socket type of SOCK_STREAM. 

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

Once we have a socket object, the next step is to bind the socket to an ip address and a port number using bind() method. 

s.bind(('', 80))

The next step is to create a listening socket which can listen to incoming http get requests from a web client. In response to these requests from web clients, a micropython web server can send web pages.

s.listen(5)

Inside the while loop, we listen to http requests from web clients. When a web client makes a request, the web server listens to it and accepts the connection request through accept() method. 

conn, addr = s.accept()

Use printf() method to print the address of a client which saved in the addr variable in the last line. 

 print('Got a connection from %s' % str(addr))

The following line receives the data from a socket client and saves it to a request variable to be used later on. 

request = conn.recv(1024)

The print() method prints the data that was received from a socket client. 

print('Content = %s' % str(request))

In response to a web client request, we take temperature and humidity samples by using read_dht() function and print the sensor readings on the shell console. 

sensor_readings = read_dht()
print(sensor_readings)

After taking a reading sample from DHT11 or DHT22 with ESP32/ESP8266, now temp and hum global variables have the latest temperature and humidity values. The web_page() function generates web page with latest sensor values.

To send HTML documents to a socket client in response to a request, create a response variable and provide the reference of the web_page() function to the response variable. 

response = web_page()

At the end send the web page content to a socket client using the send() and sendall() methods and close the connection using the close method. 


conn.send('HTTP/1.1 200 OK\n')
conn.send('Content-Type: text/html\n')
conn.send('Connection: close\n\n')
conn.sendall(response)
conn.close()

ESP32/ESP8266 DHT11/DHT22 MicroPython Web Server Demo

micropython esp32 esp8266 dht11 dht22 web server demo

To test the MicroPython DHT web server with ESP32 and ESP8266, upload both boot.py and main.py files to ESP boards one by one. First, upload boot.py file and after that upload the main.py file. After uploading MicroPython scripts, click on Enable/Reset button of ESP32: 

ESP32 enable button

Sometimeslater, your ESP board will make a connection with your WiFi router and shows a “successful connection” message and also prints the IP address on the MicroPython shell as follows: 

IP address

Now, open your web browser either on your laptop or mobile and type the IP address which we have found in the last step. You will see the web page with the latest temperature and humidity values shown on progress bars.

MicroPython DHT11 DHT22 ESP32 ESP8266 Web server

On Mobile, you will see web page like this:

MicroPython DHT11 DHT22 ESP32 ESP8266 Web server on mobile

Video Demo:

We have similar guides with Arduino IDE:

More MicroPython tutorials:

Leave a Comment