This tutorial is a step-by-step guide that covers how to build a standalone ESP32 or ESP8266 NodeMCU Web Server that displays DS18B20 sensor readings using MicroPython firmware. We’ll create an ESP32/ESP8266 Web Server that is mobile responsive and it can be accessed with any device with a browser in your local network.
If you want to learn how a relay module works, read our MicroPython Guide: DS18B20 with ESP32 and ESP8266 (Temperature Readings).
We have similar guides using Arduino IDE:
- ESP32 DS18B20 Temperature Sensor with Arduino IDE (Single, Multiple, Web Server)
- ESP8266 DS18B20 Temperature Sensor with Arduino IDE (Single, Multiple, Web Server)
Prerequisites
To follow this tutorial you need MicroPython firmware installed in your ESP32 or ESP8266 boards. You also need an IDE to write and upload the code to your board. We suggest using Thonny IDE or uPyCraft IDE:
- Thonny IDE:
- uPyCraft IDE:
- Getting Started with uPyCraft IDE
- Install uPyCraft IDE (Windows, Mac OS X, Linux)
- Flash/Upload MicroPython Firmware to ESP32 and ESP8266
Learn more about MicroPython: MicroPython Programming with ESP32 and ESP8266 eBook.
Introducing DS18B20 Temperature Sensor
The DS18B20 temperature sensor is a one-wire digital temperature sensor. This means that it just requires one data line (and GND) to communicate with your ESP32 or ESP8266.
It can be powered by an external power supply or it can derive power from the data line (called “parasite mode”), which eliminates the need for an external power supply.
Parts Required
To follow this tutorial you need the following parts:
- ESP32 or ESP8266 (read ESP32 vs ESP8266)
- DS18B20 temperature sensor (one or multiple sensors) – waterproof version
- 4.7k Ohm resistor
- Jumper wires
- Breadboard
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!
Schematic – ESP32
If you’re using an ESP32, follow the next diagram.
Schematic – ESP8266
If you’re using an ESP8266, follow the next schematic diagram.
Note: in this tutorial we’re connecting the DS18B20 data line to GPIO 4, but you can use any other suitable GPIO.
Code Web Server – DS18B20 Temperature Readings
For this example, you need two files:
- boot.py: runs when the device starts and sets up several configuration options like your network credentials, importing libraries, setting the pins, etc.
- main.py: this is the main script where we’ll handle the web server. It executes immediately after the boot.py.
Note: it is a good practice to include the boot.py and main.py files. However, if you prefer, you can include all the code in the main.py file.
boot.py (DS18B20 web server)
Create a new file in your IDE called boot.py and copy the following code.
# Complete project details at https://RandomNerdTutorials.com
try:
import usocket as socket
except:
import socket
from time import sleep
from machine import Pin
import onewire, ds18x20
import network
import esp
esp.osdebug(None)
import gc
gc.collect()
ds_pin = Pin(4)
ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))
ssid = 'REPLACE_WITH_YOUR_SSID'
password = 'REPLACE_WITH_YOUR_PASSWORD'
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(ssid, password)
while station.isconnected() == False:
pass
print('Connection successful')
print(station.ifconfig())
This file imports the required libraries, sets up the DS18B20 sensor and connects to your network.
Here, we’re setting the DS18B20 data pin on GPIO 4 but you can use any other suitable pin:
ds_pin = Pin(4)
ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))
You should insert your network credentials in the following variables so that the ESP is able to connect to your network.
ssid = 'REPLACE_WITH_YOUR_SSID'
password = 'REPLACE_WITH_YOUR_PASSWORD'
main.py (DS18B20 web server)
In the main.py file is where we’ll create the web server and handle the requests. Copy the following code to your main.py file.
# Complete project details at https://RandomNerdTutorials.com
def read_ds_sensor():
roms = ds_sensor.scan()
print('Found DS devices: ', roms)
print('Temperatures: ')
ds_sensor.convert_temp()
for rom in roms:
temp = ds_sensor.read_temp(rom)
if isinstance(temp, float):
msg = round(temp, 2)
print(temp, end=' ')
print('Valid temperature')
return msg
return b'0.0'
def web_page():
temp = read_ds_sensor()
html = """<!DOCTYPE HTML><html><head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<style> html { font-family: Arial; display: inline-block; margin: 0px auto; text-align: center; }
h2 { font-size: 3.0rem; } p { font-size: 3.0rem; } .units { font-size: 1.2rem; }
.ds-labels{ font-size: 1.5rem; vertical-align:middle; padding-bottom: 15px; }
</style></head><body><h2>ESP with DS18B20</h2>
<p><i class="fas fa-thermometer-half" style="color:#059e8a;"></i>
<span class="ds-labels">Temperature</span>
<span id="temperature">""" + str(temp) + """</span>
<sup class="units">°C</sup>
</p>
<p><i class="fas fa-thermometer-half" style="color:#059e8a;"></i>
<span class="ds-labels">Temperature</span>
<span id="temperature">""" + str(round(temp * (9/5) + 32.0, 2)) + """</span>
<sup class="units">°F</sup>
</p></body></html>"""
return html
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)
while True:
try:
if gc.mem_free() < 102000:
gc.collect()
conn, addr = s.accept()
conn.settimeout(3.0)
print('Got a connection from %s' % str(addr))
request = conn.recv(1024)
conn.settimeout(None)
request = str(request)
print('Content = %s' % request)
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()
except OSError as e:
conn.close()
print('Connection closed')
Reading the DS18B20 Sensor
The code starts by creating a function called read_ds_sensor() that gets the temperature from the DS18B20 temperature sensor. If you’ve followed the previous section, you should be familiar with the methods used here.
def read_ds_sensor():
roms = ds_sensor.scan()
print('Found DS devices: ', roms)
ds_sensor.convert_temp()
for rom in roms:
temp = ds_sensor.read_temp(rom)
if isinstance(temp, float):
temp = round(temp, 2)
print('Valid temperature')
return temp
return '0'
Web Page
The web_page() function returns the HTML page with the latest temperature readings.
We’ve built a similar web page on a previous tutorial. So, if you want to learn how the HTML works, you can read this article: MicroPython: ESP32/ESP8266 with DHT11/DHT22 Web Server.
Creating the web server
After that, make the usual procedures to create a socket server.
while True:
try:
if gc.mem_free() < 102000:
gc.collect()
conn, addr = s.accept()
conn.settimeout(3.0)
print('Got a connection from %s' % str(addr))
request = conn.recv(1024)
conn.settimeout(None)
request = str(request)
print('Content = %s' % request)
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()
except OSError as e:
conn.close()
print('Connection closed')
For an in-depth explanation of this procedure, refer to this tutorial.
Basically, when the ESP receives a request, we send the web page with the latest readings as a response:
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)
Web Server Demonstration
After uploading the boot.py and main.py files to your board. Click the ESP RST button to run the code.
Then, open your browser and type the ESP IP address. You can access the web page with the latest sensor readings in Celsius and Fahrenheit degrees:
Wrapping Up
We hope you’ve found this MicroPython guide about the DS18B20 temperature sensor with the ESP32 and ESP8266 useful. We have other projects with the ESP and MicroPython that you may like:
- MicroPython: BME280 with ESP32 and ESP8266 (Pressure, Temperature, Humidity)
MicroPython: ESP32/ESP8266 with DHT11/DHT22 Web Server - MicroPython: Getting Started with MQTT on ESP32/ESP8266
- Low Power Weather Station Datalogger using ESP8266 and BME280 with MicroPython
- MicroPython: OLED Display with ESP32 and ESP8266
Learn more about MicroPython with ESP32 and ESP8266 with our eBook: MicroPython Programming with ESP32 and ESP8266
Thanks for reading.
Hi,
why do you not use Flask module to design UI? very interesting, it implements route among pages too.
thanks and regards
Thanks for the suggestion.
Thanks for another great tutorial! Is there a way to modify the code to have the web page auto-refresh every x seconds?
You can use http-equiv meta tag inside head section as below:
\<head>
  \<meta http-equiv=”refresh” content=”30″>
\</head>
This will refresh document every 30 second
I added back slash for tag to appear properly on the post. Please ignore them while using in your code