MicroPython: ESP32/ESP8266 DS18B20 Web Server (Weather Station)

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.

ESP32 ESP8266 MicroPython DS18B20 Temperature Web Server Guide

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:

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:

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.

DS18B20 Temperature Sensor Pinout Pins

Parts Required

To follow this tutorial you need the following parts:

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.

DS18B20 Temperature Sensor with ESP32 Normal Mode Wiring Schematic Diagram

Schematic – ESP8266

If you’re using an ESP8266, follow the next schematic diagram.

DS18B20 Temperature Sensor with ESP8266 Normal Mode Wiring 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

Display DS18B20 Temperature Readings on Web Server MicroPython

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())

View raw code

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">&deg;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">&deg;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')

View raw code

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:

DS18B20 Temperature Readings on ESP32 ESP8266 Web Server

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:

Learn more about MicroPython with ESP32 and ESP8266 with our eBook: MicroPython Programming with ESP32 and ESP8266

Thanks for reading.



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

5 thoughts on “MicroPython: ESP32/ESP8266 DS18B20 Web Server (Weather Station)”

    • 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

      Reply

Leave a Comment

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.