MicroPython: ESP32/ESP8266 BME280 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 BME280 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 BME280 Temperature Humidity Pressure Web Server Guide

If you want to learn how a BME280 sensor works, read our MicroPython Guide: BME280 with ESP32 and ESP8266 (Temperature, Humidity, Pressure).

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 the BME280 Sensor Module

The BME280 sensor module reads barometric pressure, temperature and humidity. Because pressure changes with altitude, you can also estimate altitude. There are several versions of this sensor module, but we’re using the one shown in the figure below.

BME280 sensor temperature, humidity, and pressure

This sensor communicates using I2C communication protocol, so the wiring is very simple. You can use the default ESP32 or ESP8266 I2C pins as shown in the following table:

BME280ESP32ESP8266
Vin3.3V3.3V
GNDGNDGND
SCLGPIO 22GPIO 5 (D1)
SDAGPIO 21GPIO 4 (D2)

Parts Required

MicroPython BME280 with ESP32 and ESP8266 Parts Required

For this project you need to wire the BME280 sensor module to the ESP32 or ESP8266 I2C pins. Here’s a list of parts you need for this tutorial:

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

Follow the next schematic diagram if you’re using an ESP32 board:

ESP32 BME280 Sensor Module Wiring Schematics Diagram

Recommended reading: ESP32 Pinout Reference Guide

Schematic – ESP8266

Follow the next schematic diagram if you’re using an ESP8266 board:

ESP8266 BME280 Sensor Module Wiring Schematics Diagram

Recommended reading: ESP8266 Pinout Reference Guide

BME280 MicroPython Library

The library to read from the BME280 sensor isn’t part of the standard MicroPython library by default. So, you need to upload the following library to your ESP32/ESP8266 board (save it with the name BME280.py).

View raw code

Follow the next set of instructions for the IDE you’re using:

  • A. Upload BME280 library with uPyCraft IDE
  • B. Upload BME280 library with Thonny IDE

A. Upload BME280 library with uPyCraft IDE

This section shows how to upload a library using uPyCraft IDE. If you’re using Thonny IDE, read the next section.

1. Create a new file by pressing the New File button (1).

2. Copy the BME280 library code into that file. The BME280 library code can be found here.

3. After copying the code, save the file by pressing the Save button (2).

Install BME280 library MicroPython ESP32 ESP8266 uPyCraft IDE step 1

4. Call this new file “BME280.py” and press ok.

Install BME280 library MicroPython ESP32 ESP8266 uPyCraft IDE step 2

5. Click the Download and Run button.

Install BME280 library MicroPython ESP32 ESP8266 uPyCraft IDE step 3

The file should be saved on the device folder with the name “BME280.py” as highlighted in the following figure.

Install BME280 library MicroPython ESP32 ESP8266 uPyCraft IDE step 4

Now, you can use the library functionalities in your code by importing the library.

B. Upload BME280 library with Thonny IDE

If you’re using Thonny IDE, follow the next steps:

1. Copy the library code to a new file. The BME280 library code can be found here.

2. Go to File > Save as…

Thonny IDE ESP32 ESP8266 MicroPython Save file library to device save as

3. Select save to “MicroPython device“:

Thonny IDE ESP32 ESP8266 MicroPython Save file library to device select

4. Name your file as bme680.py and press the OK button:

BME280 library new MicroPython file Thonny IDE

And that’s it. The library was uploaded to your board. To make sure that it was uploaded successfully, go to File > Save as… and select the MicroPython device. Your file should be listed there:

BME280 library MicroPython file created Thonny IDE

After uploading the library to your board, you can use the library functionalities in your code by importing the library.

Code Web Server – BME280 Temperature, Humidity, and Pressure

In this project, we’ll display sensor readings from the BME280 temperature, humidity and pressure sensor on a web server that you can access on your local network.

Display BME280 Readings on Web Server with ESP32 or ESP8266

For this example, you need three files:

  • BME280.py: this is the file that contains all the methods to use the BME280 sensor. That’s the file you’ve uploaded previously.
  • 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

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, I2C
import network

import esp
esp.osdebug(None)

import gc
gc.collect()

import BME280

# ESP32 - Pin assignment
i2c = I2C(scl=Pin(22), sda=Pin(21), freq=10000)
# ESP8266 - Pin assignment
#i2c = I2C(scl=Pin(5), sda=Pin(4), freq=10000)

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 necessary libraries, defines the I2C pins to connect to the sensor and connects to your network.

In the code, we’re using the ESP32 I2C pins:

i2c = I2C(scl=Pin(5), sda=Pin(4), freq=10000)

If you’re using the ESP8266, comment the previous line and uncomment the following:

i2c = I2C(scl=Pin(22), sda=Pin(21), freq=10000)

Then, insert your network credentials in the following variables:

ssid = 'REPLACE_WITH_YOUR_SSID'
password = 'REPLACE_WITH_YOUR_PASSWORD'

main.py

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 web_page():
  bme = BME280.BME280(i2c=i2c)
  
  html = """<html><head><meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" href="data:,"><style>body { text-align: center; font-family: "Trebuchet MS", Arial;}
  table { border-collapse: collapse; width:35%; margin-left:auto; margin-right:auto; }
  th { padding: 12px; background-color: #0043af; color: white; }
  tr { border: 1px solid #ddd; padding: 12px; }
  tr:hover { background-color: #bcbcbc; }
  td { border: none; padding: 12px; }
  .sensor { color:white; font-weight: bold; background-color: #bcbcbc; padding: 1px;
  </style></head><body><h1>ESP with BME280</h1>
  <table><tr><th>MEASUREMENT</th><th>VALUE</th></tr>
  <tr><td>Temp. Celsius</td><td><span class="sensor">""" + str(bme.temperature) + """</span></td></tr>
  <tr><td>Temp. Fahrenheit</td><td><span class="sensor">""" + str(round((bme.read_temperature()/100.0) * (9/5) + 32, 2))  + """F</span></td></tr>
  <tr><td>Pressure</td><td><span class="sensor">""" + str(bme.pressure) + """</span></td></tr>
  <tr><td>Humidity</td><td><span class="sensor">""" + str(bme.humidity) + """</span></td></tr></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

This code creates a socket server that sends an HTML page with the latest sensor readings when it receives a request on the ESP32 or ESP8266 IP address.

Basically, we have a function called web_page() that returns the HTML to build up the web page with the latest sensor readings. This HMTL text builds a table to display the readings:

html = """<html><head><meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" href="data:,"><style>body { text-align: center; font-family: "Trebuchet MS", Arial;}
  table { border-collapse: collapse; width:35%; margin-left:auto; margin-right:auto; }
  th { padding: 12px; background-color: #0043af; color: white; }
  tr { border: 1px solid #ddd; padding: 12px; }
  tr:hover { background-color: #bcbcbc; }
  td { border: none; padding: 12px; }
  .sensor { color:white; font-weight: bold; background-color: #bcbcbc; padding: 1px;
  </style></head><body><h1>ESP with BME280</h1>
  <table><tr><th>MEASUREMENT</th><th>VALUE</th></tr>
  <tr><td>Temp. Celsius</td><td><span class="sensor">""" + str(bme.temperature) + """</span></td></tr>
  <tr><td>Temp. Fahrenheit</td><td><span class="sensor">""" + str(round((bme.read_temperature()/100.0) * (9/5) + 32, 2)) + """F</span></td></tr>
  <tr><td>Pressure</td><td><span class="sensor">""" + str(bme.pressure) + """</span></td></tr>
  <tr><td>Humidity</td><td><span class="sensor">""" + str(bme.humidity) + """</span></td></tr> 
  </body></html>"""

Then, we create a socket server that sends the HTML when it gets a request. The HTML text is then saved on the response variable:

response = web_page()

And sent to the client:

conn.sendall(response)

We’ve explained in great detail how these kind of web servers work in previous tutorials. So, if you want to learn how it works, you can read the following articles:

Web Server Demonstration

Upload all the previous files to your ESP32 or ESP8266 board in the following order:

  1. BME280.py
  2. boot.py
  3. main.py

If you don’t know how to upload code, you can read our getting started guides with uPyCraft IDE, or Thonny IDE:

After uploading the code, your ESP32 or ESP8266 IP address should be displayed on the Serial Monitor.

Open a web browser in your local network and type your ESP IP address (in our example the IP is http://192.168.1.71). You should get a page with the latest sensor readings as shown in the following figure.

BME280 Web Server MicroPython with ESP8266 or ESP32

Auto refresh web page

With the web server script provided in this project, you need to refresh the web page to see the latest readings. If add the next meta tag inside the HTML <head></head> tags, your web page will auto refresh every 10 seconds:

<meta http-equiv="refresh" content="10">

Wrapping Up

We hope you’ve found this tutorial useful. We have other projects and tutorials with MicroPython that you may like:

If you want to learn more about programming the ESP32 and ESP8266 boards with MicroPython, get access to 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!

10 thoughts on “MicroPython: ESP32/ESP8266 BME280 Web Server (Weather Station)”

  1. Success! Following your tutorial I was able to get the BME280 microPython project up and running.

    I decreased the displayed precision by adding statements like hd = int(round((hd / 10),0)) before the .format statements. Do you have a good reference to .format? I really don’t understand the syntax in your example.

    Additionally I would like to add the degree symbol after the temperature. I was not able to do this. The usual ways of doing it in Python don’t seen to work in microPytnon.

    As always, thanks for the good example.

    Reply
  2. Suggestion , probably should not recommend Banggood, terrible customer service, keep saying items are on the way, they split orders even though they are placed together. When they do that they then charge twice for shipping, not a good place to purchase. I ordered items for your project and I was charged 2 shipping cost for items placed together. How can yin good conscience send people to them. You should read reviews of people ordering things, horrible.I expected better of you, maybe they treated you right.

    Reply
  3. In my opinion, the library BME280.py -> class Device -> method write16 -> self.i2c.writeto_mem(self._address, register, value) is probably wrong. Correct is self.i2c.writeto_mem(self._address, register, b).

    Reply
  4. Hi,
    The pressure reading from the BME280 in this project is wrong all the time. About 8 hPa too low and changing every time when displaying the pressure every 10 seconds. I used 2 different ESP32’s to check.

    Using the same BME280 with a Raspberry Pi in this project:
    youtube.com/watch?v=ChQpD2gsC20
    the pressure reading is correct and consistant with the local weather.

    Reply
  5. ESP with BME280
    < td>1000.40hPa
    MEASUREMENT VALUE
    Temp. Celsius 26.21C
    Temp. Fahrenheit 79.14F
    Pressure
    Humidity 81.55%

    I get the Pressure measured posted on top of the other measured Temp. & Humidity. Cannot figure this out. Can anybody suggest whay to do ?

    Reply
  6. Hi
    using BME280.py module I see a linear dependence preassure vs temp. During 24h outside measurement. -3 to +24C shows a shift 1080 to 1028 hPa. Durin same time our national weather dep SMHI shows a shift 1030 to 1028.
    Previous lua module on esp8266 only had single precision float – not good enought in lineary compensation part of Bosch BME280 equations.
    Is the integer aritmetic given good enought precision in this module?
    Best Regards /Stefan Edström

    Reply
  7. Just an update.. Thonny (at least in Version 4.0.0) has a menu item under Tools called “Manage Packages” which simplifies adding the BME (or any other) package (‘library’).

    Dave

    Reply
  8. I repeated the project with the BME280 sensor, but my humidity readings do not change and are equal to 0.0, tell me what could be the problem?

    Reply
  9. Hi,

    Instead of checking for free memory and trigger gc.collect(), why don’t you choose for c.enable() for automatic garbage collection?

    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.