What you’ll build
This project turns an ESP32 development board into a small weather station that:
- measures temperature, humidity and barometric pressure with a BME280 sensor,
- shows the readings on a 0.96-inch OLED display,
- serves a web page and a JSON endpoint on your local Wi-Fi network, so any phone or computer on the network can check the readings.
It’s an indoor or sheltered build to start with. Later sections cover how to make it more accurate, add wind and rain sensors, run it on a battery and connect it to Home Assistant or MQTT.
You’ll need basic soldering skills (most sensor breakouts arrive with loose header pins) and a computer with the Arduino IDE.
Parts list
| Part | Notes |
|---|---|
| ESP32 development board | Any common ESP32-WROOM-32 “DevKit” style board works. ESP32-S3 and ESP32-C3 boards also work, but their default I2C pins differ. |
| BME280 breakout board | Temperature, humidity and pressure in one I2C sensor. Get one that runs at 3.3 V. |
| SSD1306 0.96” OLED, 128×64, I2C | The four-pin version (VCC, GND, SCL, SDA). |
| Breadboard and jumper wires | Female-to-male or male-to-male, depending on your boards. |
| USB cable | Must carry data, not just power. |
All of these are inexpensive and widely available.
Choosing a sensor
The BME280 is a popular choice because it measures all three basic weather variables on one I2C bus. Here’s how it compares with other common options:
| Sensor | Measures | Interface | Notes |
|---|---|---|---|
| DHT22 (AM2302) | Temperature, humidity | Single-wire, custom protocol | Cheap and common, slow to read, timing-sensitive |
| AHT20 | Temperature, humidity | I2C | Inexpensive, often paired with a BMP280 for pressure |
| SHT3x (e.g. SHT31) | Temperature, humidity | I2C | Generally regarded as more accurate for humidity |
| BMP280 | Temperature, pressure | I2C or SPI | No humidity |
| BME280 | Temperature, humidity, pressure | I2C or SPI | All three in one package |
Watch out for the BMP280/BME280 mix-up. The two chips look almost identical, and some listings sell BMP280 boards as BME280s. A BMP280 has no humidity sensor, so the humidity reading fails or reads 0. The chip ID register tells them apart: a BME280 reports 0x60 and a BMP280 reports 0x58. If the Adafruit library below refuses to start a board that otherwise responds on the I2C bus, a BMP280 is a likely cause.
Wiring
Both the BME280 and the OLED connect to the same I2C bus, so they share the SDA and SCL wires. On a standard ESP32 DevKit with the Arduino core, the default I2C pins are GPIO21 (SDA) and GPIO22 (SCL).
| Module pin | ESP32 pin |
|---|---|
| BME280 VIN (or VCC) | 3V3 |
| BME280 GND | GND |
| BME280 SDA | GPIO21 |
| BME280 SCL | GPIO22 |
| OLED VCC | 3V3 |
| OLED GND | GND |
| OLED SDA | GPIO21 |
| OLED SCL | GPIO22 |
Power both modules from 3.3 V, not 5 V, unless the module’s documentation says it has its own regulator and level shifting. Most breakout boards already include I2C pull-up resistors, so you usually don’t need to add any.
Some BME280 boards have extra pins labeled CSB and SDO. In I2C mode, SDO selects the address: tied low gives 0x76, tied high gives 0x77. Many boards fix this with a solder jumper.
Setting up the Arduino IDE
- Install the Arduino IDE (version 2.x).
- Open the Boards Manager, search for esp32 and install the package by Espressif Systems.
- Select your board, for example ESP32 Dev Module, and the correct serial port.
- Open the Library Manager and install:
- Adafruit BME280 Library
- Adafruit Unified Sensor
- Adafruit SSD1306
- Adafruit GFX Library
The IDE may offer to install dependencies such as Adafruit BusIO automatically; accept them.
If the board doesn’t show up as a serial port, you may need a USB driver for its USB-to-serial chip (commonly a CP210x or CH340).
Test the I2C bus first
Before writing the full sketch, confirm both devices respond. This short scanner prints every address it finds:
#include <Wire.h>
void setup() {
Serial.begin(115200);
Wire.begin(21, 22); // SDA, SCL
delay(500);
Serial.println("Scanning I2C bus...");
for (uint8_t addr = 1; addr < 127; addr++) {
Wire.beginTransmission(addr);
if (Wire.endTransmission() == 0) {
Serial.printf("Found device at 0x%02X\n", addr);
}
}
Serial.println("Done.");
}
void loop() {}
Open the Serial Monitor at 115200 baud. You should see two addresses: the OLED, usually at 0x3C, and the BME280 at 0x76 or 0x77. Note the BME280 address; you’ll need it in the next step.
The code
Replace the Wi-Fi credentials and, if your scanner found the BME280 at 0x77, change BME280_ADDR.
#include <WiFi.h>
#include <WebServer.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
const char* WIFI_SSID = "your-network";
const char* WIFI_PASS = "your-password";
const uint8_t BME280_ADDR = 0x76;
const uint8_t OLED_ADDR = 0x3C;
const unsigned long READ_INTERVAL_MS = 60000; // one reading per minute
Adafruit_BME280 bme;
Adafruit_SSD1306 display(128, 64, &Wire, -1);
WebServer server(80);
float temperatureC = NAN;
float humidity = NAN;
float pressureHpa = NAN;
unsigned long lastRead = 0;
void readSensor() {
bme.takeForcedMeasurement(); // wake the sensor for one reading
temperatureC = bme.readTemperature();
humidity = bme.readHumidity();
pressureHpa = bme.readPressure() / 100.0F; // Pa to hPa
}
void updateDisplay() {
display.clearDisplay();
display.setTextColor(SSD1306_WHITE);
display.setTextSize(1);
display.setCursor(0, 0);
display.println(WiFi.localIP());
display.setTextSize(2);
display.setCursor(0, 16);
display.printf("%.1f C\n", temperatureC);
display.setTextSize(1);
display.printf("\nRH %.0f %%\n", humidity);
display.printf("P %.1f hPa\n", pressureHpa);
display.display();
}
void handleRoot() {
String html = "<!DOCTYPE html><html><head><meta charset='utf-8'>";
html += "<meta name='viewport' content='width=device-width, initial-scale=1'>";
html += "<meta http-equiv='refresh' content='60'>";
html += "<title>ESP32 Weather Station</title></head><body>";
html += "<h1>ESP32 Weather Station</h1>";
html += "<p>Temperature: ";
html += String(temperatureC, 1);
html += " °C</p><p>Humidity: ";
html += String(humidity, 0);
html += " %</p><p>Pressure: ";
html += String(pressureHpa, 1);
html += " hPa</p></body></html>";
server.send(200, "text/html", html);
}
void handleJson() {
String json = "{\"temperature_c\":";
json += String(temperatureC, 2);
json += ",\"humidity_pct\":";
json += String(humidity, 1);
json += ",\"pressure_hpa\":";
json += String(pressureHpa, 2);
json += "}";
server.send(200, "application/json", json);
}
void setup() {
Serial.begin(115200);
Wire.begin(21, 22); // SDA, SCL
if (!bme.begin(BME280_ADDR, &Wire)) {
Serial.println("BME280 not found. Check wiring, address, or whether it's a BMP280.");
while (true) delay(1000);
}
// Recommended settings for weather monitoring: forced mode, 1x oversampling, no filter
bme.setSampling(Adafruit_BME280::MODE_FORCED,
Adafruit_BME280::SAMPLING_X1, // temperature
Adafruit_BME280::SAMPLING_X1, // pressure
Adafruit_BME280::SAMPLING_X1, // humidity
Adafruit_BME280::FILTER_OFF);
if (!display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR)) {
Serial.println("SSD1306 display not found.");
while (true) delay(1000);
}
display.clearDisplay();
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.println("Connecting to Wi-Fi...");
display.display();
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASS);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
server.on("/", handleRoot);
server.on("/data.json", handleJson);
server.begin();
readSensor();
updateDisplay();
lastRead = millis();
}
void loop() {
server.handleClient();
if (millis() - lastRead >= READ_INTERVAL_MS) {
lastRead = millis();
readSensor();
updateDisplay();
}
}
Upload the sketch, open the Serial Monitor and note the IP address it prints (it also appears on the OLED). Browse to http://<that-ip>/ for the web page, or http://<that-ip>/data.json for machine-readable data.
How the code works
- Forced mode. The BME280 sleeps between readings and takes a single measurement when
takeForcedMeasurement()is called. For weather data, one reading a minute is plenty, and keeping the sensor asleep reduces self-heating and power use. - Non-blocking loop. Instead of
delay(60000), the loop checksmillis()so the web server keeps answering requests between readings. Themillis() - lastReadform also handles the counter wrapping around after about 49 days. - Two endpoints. The HTML page is for people. The JSON endpoint is for other software, such as a script, a dashboard or a home automation system, which can poll it.
- Simple Wi-Fi handling. The sketch waits forever if it can’t connect, which is fine for a first build. For a station that runs unattended, add a timeout and a reconnect check in
loop().
Getting accurate readings
Getting the code to run is the easy part. Getting readings you can trust takes a little more care.
Keep the sensor away from heat
The most common complaint about DIY weather stations is a temperature reading a few degrees too high. Usually the sensor is picking up heat from the electronics around it:
- The ESP32 itself gets warm, especially with Wi-Fi active.
- The OLED and the board’s voltage regulator add heat.
- A BME280 left in continuous high-oversampling mode warms itself slightly.
To reduce the error, mount the sensor on short wires a few centimeters away from the ESP32, keep it out of any enclosure that holds the board, and use forced mode as in the sketch. Compare it against a trusted thermometer and, if there’s a consistent offset, correct it in software.
Bosch’s datasheet lists the BME280’s typical absolute accuracy as roughly ±1 °C for temperature, ±3 % relative humidity and ±1 hPa for pressure. Placement problems can easily cause bigger errors than that, so it’s worth getting them right first.
Station pressure vs sea-level pressure
The BME280 reports station pressure, the actual air pressure where the sensor sits. Weather forecasts quote pressure adjusted to sea level, so that readings from places at different altitudes can be compared. If you live well above sea level, your raw reading will be noticeably lower than the local forecast’s figure.
To convert, you need your altitude in meters. A common approximation is:
float altitudeM = 120.0; // your station's altitude
float seaLevelHpa = pressureHpa / pow(1.0 - altitudeM / 44330.0, 5.255);
The same relationship works in reverse: the library’s readAltitude(seaLevelHpa) estimates altitude from a known sea-level pressure, which is why weather-driven pressure changes make that altitude estimate drift.
Sending data to Home Assistant, MQTT or the cloud
A local web page is a good start. To keep history and build graphs, send the readings somewhere:
- ESPHome and Home Assistant. ESPHome replaces your Arduino sketch with firmware generated from a YAML configuration and has built-in BME280 and SSD1306 support. The station then appears in Home Assistant with very little code. It’s the easiest route if you already run Home Assistant.
- MQTT. Publish each reading to topics on an MQTT broker (Mosquitto is a common choice) using a client library such as PubSubClient. Home Assistant, Node-RED and many dashboards can subscribe to those topics.
- Cloud services. Platforms such as ThingSpeak and Adafruit IO accept readings over HTTP or MQTT and provide hosted charts. Check their free-tier limits on update rates.
Taking it outdoors
An outdoor station is a bigger project, mostly because of the mechanical and weatherproofing work.
Wind and rain sensors
Hobby wind and rain sensors usually work like this:
- Anemometer (wind speed): a reed switch or Hall-effect sensor closes once or more per rotation. Count pulses with an interrupt, then convert pulses per second into wind speed using the factor from the manufacturer’s documentation.
- Wind vane (direction): many models switch different resistors into a voltage divider depending on direction, so you read them with the ADC and map voltages to compass points.
- Tipping-bucket rain gauge: each tip closes a switch and represents a fixed amount of rain listed in the gauge’s specifications. Count tips with an interrupt.
Two ESP32-specific points: debounce reed-switch inputs (in software, or with a small RC filter), and on the original ESP32, use ADC1 pins (GPIO32 to GPIO39) for analog sensors. ADC2 is shared with the Wi-Fi radio and can’t be used reliably while Wi-Fi is on.
Mount the temperature and humidity sensor inside a radiation shield, a stack of ventilated plates (often called a Stevenson screen style shield) that blocks direct sun while letting air flow. A sensor in direct sunlight, or in a sealed box, reads far too high.
Running on battery
To run from a lithium-ion cell, take a reading, send it, then put the ESP32 into deep sleep until the next reading:
esp_sleep_enable_timer_wakeup(10ULL * 60ULL * 1000000ULL); // 10 minutes, in microseconds
esp_deep_sleep_start();
After waking, the ESP32 restarts from setup(), so the design changes: read, send, sleep, with no web server always listening. In this design the station pushes data (for example over MQTT) instead of serving it.
Expect disappointing battery life on a typical DevKit board, even in deep sleep. The USB-to-serial chip, power LED and voltage regulator keep drawing current while the ESP32 sleeps. For long battery life, use a board designed for low sleep current, or a bare module with an efficient regulator. Use a proper charge and protection circuit for the cell, such as a TP4056-based module with protection, and follow the cell’s handling guidance.
Troubleshooting
| Symptom | Likely cause | What to try |
|---|---|---|
| Scanner finds nothing | Wiring, power or wrong pins | Check 3V3/GND, swap SDA and SCL, confirm the GPIO numbers for your board |
Scanner finds the BME280 but bme.begin() fails |
Wrong address, or it’s a BMP280 | Try 0x77; check the chip ID, since 0x58 means BMP280 |
| Humidity reads 0 or nonsense | BMP280 instead of BME280 | Replace the sensor, or add a separate humidity sensor |
| Temperature reads several degrees high | Self-heating or nearby heat sources | Move the sensor away from the board, use forced mode, apply an offset |
| Board resets when Wi-Fi starts (“Brownout detector was triggered”) | Weak USB power or cable | Use a shorter or better cable, a powered hub, or a stronger supply |
| Can’t upload | Board not in bootloader mode or driver missing | Hold the BOOT button while the upload starts; install the CP210x or CH340 driver |
| Web page doesn’t load | Different network, or IP changed | Make sure your device is on the same network; set a DHCP reservation in your router |
Where to go next
Once the basic station works, you’ve touched most of the pieces of a real IoT device: a sensor bus, a display, networking and data delivery. If you want the theory behind that, our explainer on what IoT and embedded systems are covers how the device fits into the wider system. For your next build, browse our embedded systems and IoT project ideas, or go back to the full list of embedded systems project ideas sorted by skill level.