Home / Projects

Project: ESP32 weather station with its own web page

An ESP32 board wired to a BME280 sensor over I2C, SDA to GPIO 21 and SCL to GPIO 22, serving a web page over Wi-Fi to a phone that shows the temperature, humidity and pressure
Beginner

This project turns an ESP32 and a BME280 sensor into a small weather station. The ESP32 joins your Wi-Fi and runs its own web server, so any phone, tablet or computer on the same network can open a page showing the temperature, humidity and air pressure, updating every few seconds. You'll learn how I2C sensors work, how an ESP32 serves a web page, and how a page fetches fresh data without reloading.

Difficulty: beginner. Time: about 45 minutes. Works on: ESP32 boards with the original ESP32 chip (ESP32-WROOM-32). Other ESP32 boards work too if you change the two I2C pins to suit your board.

What you need

  • An ESP32 development board and a USB data cable
  • A BME280 sensor module (3.3 V)
  • Two half-size breadboards and four jumper wires
  • A 2.4 GHz Wi-Fi network (the original ESP32 can't use 5 GHz)
Shopping list (5 items)

Some shop links are affiliate links (Amazon UK, Tooled Up): if you buy through one we may earn a small commission, at no extra cost to you. As an Amazon Associate I earn from qualifying purchases. It never changes which products we recommend, and no shop has paid to be included.

Everything for this build, in one place. Each link goes to a page we checked had the part in stock.

  • 1×
    ESP32 development board (ESP32-WROOM-32, 30 pins)A pack of two ELEGOO boards with USB-C and a CP2102 USB chip, so the spare can go in your next project. The board is wide: put it across two breadboards side by side so both rows of pins have free holes.
  • 1×
    USB-A to USB-C data cableThe boards come without a cable. These Anker cables carry data as well as charge, which uploading needs.
  • 1×
    BME280 sensor module, 3.3 V, pins already solderedIt must say BME280. The cheaper BMP280 looks almost the same but has no humidity sensor.
  • 2×
    Half-size breadboards (400 points)Two side by side, with the ESP32 straddling the gap between them.
  • 1×
    Jumper wire kit (male-male, male-female and female-female)40 of each kind. Male-female wires go from a Raspberry Pi's pins to a breadboard.
  • Free
    Arduino IDEThe free Arduino editor. Nothing to buy.

Each button opens that shop's page for the part, checked when we wrote the list; if one shop is out of stock, try the next. Any equivalent part with the same value works.

The sensor

The BME280, made by Bosch, measures three things in a chip about 2.5 mm square: temperature, relative humidity and air pressure. Bosch's datasheet gives its typical accuracy as about ±1 °C, ±3 % relative humidity and ±1 hPa. It talks to the ESP32 over I2C, a two-wire bus: SDA carries the data and SCL the clock. Each I2C device has an address, and BME280 modules use either 0x76 or 0x77 depending on how the board maker wired one of its pins. The sketch tries both. Our guide to I2C, SPI and UART explains the bus in more detail.

The circuit

BME280 pinESP32 pin
VIN (or VCC)3V3
GNDGND
SCLGPIO 22
SDAGPIO 21

GPIO 21 and 22 are the ESP32's default I2C pins in the Arduino core. If your module has extra pins called CSB and SDO, leave them unconnected. Power the module from 3V3, not 5V: this module is made for 3.3 V.

  1. Unplug the ESP32. Put it across the two breadboards so each row of pins has free holes beside it.
  2. Push the BME280's pins into a free part of a breadboard.
  3. Wire the four connections in the table. Our ESP32 pinout shows where each pin is, but check the labels printed on your own board, because layouts vary between makers.

Setting up the Arduino IDE for the ESP32

If you've never used an ESP32 with the Arduino IDE, follow our ESP32 first steps guide first. In short: add Espressif's boards manager address in the IDE's preferences, install esp32 by Espressif Systems from the Boards Manager, then choose ESP32 Dev Module and your board's port. If an upload stops at "Connecting...", hold the board's BOOT button until the upload starts.

You also need Adafruit's BME280 library. In the IDE, open the Library Manager (the books icon on the left), search for Adafruit BME280, and click Install. When it asks to install the libraries it depends on, choose Install all.

The sketch

Put your Wi-Fi name and password between the quotes at the top, upload, then open the Serial Monitor at 115200 baud. Once the ESP32 joins your network it prints an address like http://192.168.1.50. Type that address into a browser on any device on the same Wi-Fi.

// ESP32 weather station: a BME280 sensor and a web page you can open on any phone on your Wi-Fi.
#include <WiFi.h>
#include <WebServer.h>
#include <Wire.h>
#include <Adafruit_BME280.h>

const char *WIFI_NAME = "your-wifi-name";
const char *WIFI_PASSWORD = "your-wifi-password";

Adafruit_BME280 bme;
WebServer server(80);

float tempC = 0, humidity = 0, pressureHpa = 0;
unsigned long lastRead = 0;
const unsigned long READ_EVERY = 30000;  // ms between readings

const char PAGE[] = R"rawliteral(<!DOCTYPE html>
<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Weather station</title>
<style>body{font-family:sans-serif;text-align:center;margin:2em}b{font-size:2.5em;display:block}</style>
</head><body><h1>Weather station</h1>
<p>Temperature <b id="t">-</b></p><p>Humidity <b id="h">-</b></p><p>Pressure <b id="p">-</b></p>
<script>
async function update() {
  try {
    const d = await (await fetch('/data')).json();
    document.getElementById('t').textContent = d.temperature.toFixed(1) + ' °C';
    document.getElementById('h').textContent = d.humidity.toFixed(0) + ' %';
    document.getElementById('p').textContent = d.pressure.toFixed(0) + ' hPa';
  } catch (e) {}
}
update();
setInterval(update, 10000);
</script></body></html>)rawliteral";

void readSensor() {
  bme.takeForcedMeasurement();  // wake the sensor for one reading, then it sleeps again
  tempC = bme.readTemperature();
  humidity = bme.readHumidity();
  pressureHpa = bme.readPressure() / 100.0;  // pascals to hectopascals
}

void handleRoot() {
  server.send(200, "text/html", PAGE);
}

void handleData() {
  char json[100];
  snprintf(json, sizeof(json), "{\"temperature\":%.2f,\"humidity\":%.1f,\"pressure\":%.1f}", tempC, humidity, pressureHpa);
  server.send(200, "application/json", json);
}

void setup() {
  Serial.begin(115200);
  Wire.begin();  // SDA on GPIO 21, SCL on GPIO 22
  if (!bme.begin(0x76) && !bme.begin(0x77)) {
    Serial.println("No BME280 found. Check the wiring and the address.");
    while (true) delay(1000);
  }
  // Bosch's recommended settings for weather monitoring: one reading at a time, no oversampling
  bme.setSampling(Adafruit_BME280::MODE_FORCED,
                  Adafruit_BME280::SAMPLING_X1, Adafruit_BME280::SAMPLING_X1, Adafruit_BME280::SAMPLING_X1,
                  Adafruit_BME280::FILTER_OFF);
  readSensor();
  lastRead = millis();

  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_NAME, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  Serial.print("Open http://");
  Serial.println(WiFi.localIP());

  server.on("/", handleRoot);
  server.on("/data", handleData);
  server.begin();
}

void loop() {
  server.handleClient();
  if (millis() - lastRead >= READ_EVERY) {
    readSensor();
    lastRead = millis();
  }
  delay(2);
}

How it works

  • Reading the sensor. The sensor runs in forced mode: it takes one measurement when asked, then sleeps. Bosch recommends this, with no oversampling and the filter off, for weather monitoring, because it keeps the chip from warming itself up. The sketch takes a reading every 30 seconds.
  • Two pages. The ESP32's web server answers two addresses. / sends the page itself, which is stored in the sketch as one long string. /data sends just the latest numbers as JSON, a simple text format like {"temperature":21.37,"humidity":48.2,"pressure":1012.9}.
  • Updating without reloading. A few lines of JavaScript in the page ask for /data every 10 seconds and put the numbers on the screen. The page itself only loads once.
  • Tested. We ran this exact sketch on a simulated ESP32 with a simulated sensor and web requests, checking the Wi-Fi connection, the readings, the 30-second timing and that both pages send the right content.

Accuracy

  • Keep the sensor away from the ESP32. The ESP32 gets warm when Wi-Fi is on, and a sensor right next to it reads high. Put it on short wires, a few centimetres from the board, and out of direct sunlight.
  • Pressure isn't the forecast's number. The sensor measures the actual pressure where it is. Weather forecasts quote pressure corrected to sea level, which is higher by roughly 1.2 hPa for every 10 m you are above sea level. At 100 m up, expect your reading to be about 12 hPa lower than the forecast.
  • Humidity follows temperature. Relative humidity changes when the temperature changes, even if the amount of water in the air doesn't, so an indoor sensor near a radiator or a kettle will swing about.

Troubleshooting

  • "No BME280 found": check SDA and SCL aren't swapped and the module has power. If the wiring is right, you may have a BMP280, which has a different chip ID. It has no humidity sensor, so this sketch won't use it.
  • Stuck on "Connecting to Wi-Fi": check the name and password (both are case-sensitive) and that your router has a 2.4 GHz network.
  • The page won't open: your phone must be on the same Wi-Fi network as the ESP32, not on mobile data or a guest network.
  • The board keeps restarting: Wi-Fi needs short bursts of current. Try another USB cable or port.

Take it further

Sources

The main references behind this guide. Numbers we worked out ourselves, such as the code outputs, come from running the code.