Home / Learn Chip Programming / Project 5: Wi-Fi Weather Station (ESP32)
Project 5: Wi-Fi Weather Station (ESP32)
Read a BME280, show values on an OLED, serve a web page and publish to MQTT.
Theory in plain words
What it is
The ESP32 joins your Wi-Fi, reads temperature, humidity and pressure every few seconds, draws them on the OLED, serves a JSON endpoint and publishes to an MQTT broker.
Why we use it
It combines I2C sensors, displays, Wi-Fi, HTTP and MQTT: the full IoT stack in one small project.
How it works
Initialise I2C, read the BME280, format JSON, start a web server with one route, and publish the same JSON to a topic every 10 s.
Where it is used
- Home automation
- Agriculture monitoring
- Smart building sensors
Equipment
BME280 and the OLED share the same two I2C wires, so wiring is simple.
Wiring
| From | To | Note |
|---|---|---|
| ESP32 GPIO21 (SDA) | BME280 SDA and OLED SDA | both modules on the same bus |
| ESP32 GPIO22 (SCL) | BME280 SCL and OLED SCL | addresses: BME280 0x76, OLED 0x3C |
| ESP32 3V3 | VCC of both modules | use 3.3 V |
| ESP32 GND | GND of both | common ground |
Live dashboard simulator
The same JSON is shown on the web page and sent over MQTT. If Wi-Fi drops the station should reconnect automatically.
Code (Arduino core for ESP32)
#include <WiFi.h>
#include <WebServer.h>
#include <PubSubClient.h>
#include <Adafruit_BME280.h>
#include <Adafruit_SSD1306.h>
const char *SSID = "your-wifi", *PASS = "your-pass", *BROKER = "broker.hivemq.com";
Adafruit_BME280 bme; Adafruit_SSD1306 oled(128, 64, &Wire, -1);
WiFiClient net; PubSubClient mqtt(net); WebServer web(80);
String json() { char b[128]; snprintf(b, sizeof b, "{\"temp_c\":%.1f,\"humidity\":%.0f,\"pressure_hpa\":%.0f}", bme.readTemperature(), bme.readHumidity(), bme.readPressure() / 100.0f); return b; }
void setup() {
Wire.begin(21, 22); bme.begin(0x76); oled.begin(SSD1306_SWITCHCAPVCC, 0x3C);
WiFi.begin(SSID, PASS); while (WiFi.status() != WL_CONNECTED) delay(300);
web.on("/json", []() { web.send(200, "application/json", json()); }); web.begin();
mqtt.setServer(BROKER, 1883);
}
void loop() {
web.handleClient();
if (!mqtt.connected()) mqtt.connect("esp32-weather-xyz");
mqtt.loop();
static uint32_t t0; if (millis() - t0 > 10000) {
t0 = millis(); mqtt.publish("home/weather-xyz", json().c_str());
oled.clearDisplay(); oled.setTextSize(1); oled.setTextColor(WHITE); oled.setCursor(0, 0);
oled.printf("T %.1f C\nH %.0f %%\nP %.0f hPa", bme.readTemperature(), bme.readHumidity(), bme.readPressure() / 100.0f); oled.display();
}
}- Run an I2C scanner: you must see 0x3C and 0x76 (or 0x77).
- Print BME280 readings on the serial monitor first.
- Show them on the OLED.
- Join Wi-Fi and open
http://ESP-IP/jsonin a phone browser. - Subscribe to your topic with an MQTT client app to see the live data.
Quick quiz
1. BME280 and OLED can share...
Different addresses, same SDA and SCL.
2. JSON is used to...
Readable by web apps and dashboards.