ESP32 Weather Station – Live Web Dashboard with Charts

ESP32 Weather Station Live Webserver Dashboard with Charts ESP32 Weather Station Live Webserver Dashboard with Charts

Most “DIY weather station” tutorials stop at printing numbers on a Serial Monitor or, at best, an OLED screen you have to walk up to and squint at. That’s fine for a demo, but it’s not something you’d actually leave running on a shelf and use. In this project we’re building something you’ll actually want to keep switched on: an ESP32 weather station that reads temperature, humidity, atmospheric pressure and ambient light, then serves all of it as a live, auto-updating dashboard with charts — right from the ESP32 itself, no app and no cloud account required.

You’ll be able to open http://myweatherstation.local from your laptop or phone on the same WiFi network and see your room (or balcony, or greenhouse) conditions update in real time, with a rolling 60-minute history logged every 5 minutes so you can actually see trends, not just a snapshot. And because WiFi credentials are the one thing that always breaks a home IoT project, we’ve added a physical WiFi reset button so you can re-pair the device to a new network without re-flashing anything.

Here’s what makes this build different from the usual “sensor + web server” tutorial:

  • Three sensors, one dashboard — DHT22 for temperature and humidity, BMP280 for barometric pressure, and BH1750 for ambient light, all read over I2C/single-wire and merged into one clean UI.
  • Live charts, not just numbers — four auto-refreshing line charts (temperature, humidity, pressure, light) built with Chart.js, so trends are visible at a glance.
  • 60-minute rolling history at 5-minute intervals — stored directly in the ESP32’s RAM, no SD card or SPIFFS wear needed.
  • Light shown as 0–100%, not raw lux — far easier to read at a glance, with a simple calibration step explained below.
  • One-button WiFi reset using WiFiManager, so a network change never means re-uploading code.
  • myweatherstation.local — access the dashboard by name instead of hunting for an IP address on your router’s admin page.
  • A genuinely responsive, fast-loading UI — pure HTML/CSS/JS served directly from the ESP32, no frameworks, no bloat.

Let’s build it.


Requirements

Hardware Requirements:

  • ESP32 Dev Board (ESP32-WROOM-32 or similar)
  • DHT22 (AM2302) Temperature & Humidity Sensor
  • BMP280 Barometric Pressure Sensor module (3.3V, I2C)
  • BH1750 Ambient Light Sensor module (GY-30 / GY-302 board)
  • 10kΩ resistor (pull-up for DHT22 data line, only needed if your module doesn’t already have one)
  • Push button (or use the ESP32’s built-in BOOT button — no extra wiring needed)
  • Breadboard and jumper wires
  • Micro-USB cable and 5V power supply

Software Requirements:

  • Arduino IDE (1.8.19 or the newer 2.x IDE)
  • ESP32 Board Package installed via Boards Manager
  • The libraries listed in the Required Libraries section below

Sensor Details

DHT22

dht22 temperature and humidity sensor

What is it? The DHT22 (also sold as the AM2302) is a digital temperature and humidity sensor that combines a capacitive humidity element with a thermistor, and outputs a calibrated digital signal over a single data pin — no analog-to-digital conversion needed on your side.

Why DHT22 over DHT11? The DHT22 has a wider range and noticeably better accuracy than the cheaper DHT11, which matters a lot once you’re plotting trend charts — a sensor with ±2°C and ±5% RH noise makes for a very jumpy graph.

Technical specifications:

  • Operating voltage: 3.3V – 5.5V
  • Humidity range: 0–100% RH, accuracy ±2% RH
  • Temperature range: -40°C to 80°C, accuracy ±0.5°C
  • Sampling rate: roughly once every 2 seconds
  • Single-wire digital output (needs a 10kΩ pull-up between VCC and DATA if your breakout board doesn’t already have one built in)

BMP280

BME/BMP280 pinout diagram

What is it? The BMP280 is Bosch’s compact barometric pressure and temperature sensor, communicating over I2C (or SPI, though we’re using I2C here). It’s the same sensor family used in a lot of smartphones and fitness watches for altitude estimation.

Why include it? Pressure trends are one of the most useful — and most overlooked — indicators for basic weather forecasting. A steadily falling pressure reading is a classic sign that rain is on the way, long before humidity or temperature tells you anything.

Technical specifications:

  • Operating voltage: 1.8V – 3.6V (most breakout boards regulate down from 3.3V/5V)
  • Pressure range: 300–1100 hPa
  • Absolute accuracy: ±1 hPa
  • Temperature range: -40°C to 85°C
  • Interface: I2C (address 0x76 or 0x77 depending on the module) or SPI

Related Article: Interfacing BMP280 with ESP32

BH1750

BH1750 light intensity sensor pinout diagram

What is it? The BH1750 is a 16-bit digital ambient light sensor that measures illuminance directly in lux over I2C, without needing any external calibration circuitry the way an LDR (light-dependent resistor) does. It’s far more consistent than an LDR, especially under artificial lighting.

Why convert lux to a percentage? Raw lux values are hard to interpret at a glance — direct sunlight can be 30,000–100,000 lux, an overcast day maybe 1,000–10,000 lux, and a well-lit room only 200–500 lux. Rather than showing a number that means nothing to most visitors, this project converts the raw lux reading into a 0–100% “brightness level” scaled against a configurable maximum, which reads far more naturally on a dashboard. We’ll cover exactly how to tune that scale for your environment in the calibration section.

Technical specifications:

  • Operating voltage: 3.3V – 5V (most breakout boards include a regulator)
  • Measurement range: 1 – 65,535 lux
  • Resolution: 1 lux (high-resolution mode)
  • Interface: I2C, default address 0x23 (or 0x5C if the ADDR pin is pulled high)

Related Article: Interfacing BH1750 Light intensity sensor with Arduino


Circuit Diagram and Wiring

Both the BMP280 and BH1750 share the same I2C bus, so wiring is simpler than it looks — you’re really just connecting two devices to the same four lines and adding the DHT22 separately.

ESP32 weather station on webserver with charts and logs circuit diagram

 

Sensor Pin Connects to ESP32
DHT22 VCC 3.3V
DHT22 DATA GPIO 4 (with 10kΩ pull-up to 3.3V if not built into the module)
DHT22 GND GND
BMP280 VIN/VCC 3.3V
BMP280 GND GND
BMP280 SCL GPIO 22
BMP280 SDA GPIO 21
BH1750 VCC 3.3V
BH1750 GND GND
BH1750 SCL GPIO 22
BH1750 SDA GPIO 21
WiFi Reset Button GPIO 0 (this is the ESP32’s built-in BOOT button — no wiring needed)
Status LED (optional) GPIO 2 (built-in LED on most dev boards)

A couple of wiring notes worth catching before you power it on:

  • Don’t power any of these sensors from 5V if the breakout board doesn’t have its own regulator. Most BMP280 and BH1750 modules sold for hobbyist use do include a 3.3V regulator and level shifting, but double-check your specific board’s silkscreen or listing before assuming.
  • BMP280 and BH1750 share the same SDA/SCL lines — that’s normal for I2C, since each device has its own address. If you happen to have two boards with the same address (rare, but it happens with certain “combo” boards), you’ll need to change one via its ADDR pin.
  • If you’re not using the built-in BOOT button for the WiFi reset function, wire an external push button between GPIO 0 and GND instead.

Build a Professional Weather Station with PCBWay—Custom PCBs & 3D-Printed Enclosures for Your ESP32 Project

Create a sophisticated weather monitoring system that displays real-time environmental data on a live web dashboard with charts. PCBWay’s integrated manufacturing services help you transform your ESP32 and sensor array prototype into a polished, professional weather station—perfect for home automation, agricultural monitoring, or educational projects.

Custom PCB Manufacturing for Multi-Sensor Integration:
PCBWay manufactures high-quality custom PCBs that consolidate your ESP32, DHT22 temperature/humidity sensor, BMP280 pressure sensor, and power management onto a single compact board. Their PCBs feature clean I²C/SPI traces for stable sensor communication, proper isolation to prevent signal interference, and robust power regulation with dedicated planes for reliable Wi-Fi data transmission to your web dashboard. Choose professional SMT assembly to receive a fully populated, tested board ready for web server deployment.

Weatherproof 3D-Printed Enclosures:
Protect your outdoor weather station with a custom enclosure from PCBWay’s advanced 3D printing service. Design a weather-resistant housing using UV-stabilized ASA or waterproof PETG, featuring ventilation for accurate sensor readings, cable glands for waterproof wiring, and secure mounting points for pole or wall installation.

Why PCBWay Delivers Professional Results:

  • Reliable Data: Clean PCB design ensures accurate sensor readings for your web dashboard
  • Outdoor Durability: Custom enclosures protect electronics from sun, rain, and temperature extremes
  • Seamless Integration: Perfect PCB-to-enclosure fit from one trusted source
  • Complete Solution: From prototype to weather-ready monitoring station

Build Your Weather Station Today:
Upload your PCB design and enclosure model for instant quotes, DFM feedback, and professional manufacturing only at PCBWAY.COM


Required Libraries

Install these through Sketch → Include Library → Manage Libraries in the Arduino IDE (search by name) unless a direct link is given:

  • DHT sensor library by Adafruit
  • Adafruit Unified Sensor by Adafruit (dependency for both the DHT and BMP280 libraries)
  • Adafruit BMP280 Library by Adafruit
  • BH1750 by Christopher Laws — GitHub link
  • ArduinoJson by Benoit Blanchon (version 6.x)
  • WiFiManager by tzapu — GitHub link, Change WiFi Credentials without uploading code again
  • WiFi.h, WebServer.h, ESPmDNS.h, Wire.h and time.h are all bundled with the ESP32 board package, so no separate install is needed for those.

Full ESP32 Code

This is the complete sketch — sensor reading, WiFi provisioning with a physical reset button, the rolling 60-minute log, and the embedded web dashboard are all in one file. Upload it as-is and it will boot into a WeatherStation-Setup WiFi access point the very first time, ready for you to connect and enter your home WiFi credentials.

#include <WiFi.h>
#include <WiFiManager.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <Wire.h>
#include <DHT.h>
#include <Adafruit_BMP280.h>
#include <BH1750.h>
#include <ArduinoJson.h>
#include <time.h>

// ---------- Pin configuration ----------
#define DHTPIN            4
#define DHTTYPE           DHT22
#define WIFI_RESET_BTN    0     // ESP32 BOOT button
#define STATUS_LED        2     // built-in LED on most dev boards

// ---------- Light calibration ----------
// Raw BH1750 lux reading that should map to 100%.
// See the "Calibrating the Light Percentage" section of the article.
float MAX_LUX = 20000.0;

// ---------- Logging configuration ----------
#define LOG_POINTS        12                     // 60 minutes / 5-minute interval
#define LOG_INTERVAL_MS   (5UL * 60UL * 1000UL)   // 5 minutes
#define READ_INTERVAL_MS  3000UL                  // live sensor refresh, 3 seconds

DHT dht(DHTPIN, DHTTYPE);
Adafruit_BMP280 bmp;
BH1750 lightMeter;
WebServer server(80);

float tempLog[LOG_POINTS], humLog[LOG_POINTS], presLog[LOG_POINTS], lightLog[LOG_POINTS];
String timeLog[LOG_POINTS];
int logIndex = 0;
bool logFilled = false;

float curTemp = 0, curHum = 0, curPres = 0, curLightPct = 0;
unsigned long lastRead = 0;
unsigned long lastLog = 0;
unsigned long lastWifiCheck = 0;

unsigned long buttonPressStart = 0;
bool buttonHeld = false;

const char* ntpServer = "pool.ntp.org";
const long  gmtOffset_sec = 19800;   // +5:30 IST — change to match your timezone
const int   daylightOffset_sec = 0;

// ---------- Function prototypes ----------
// The Arduino IDE normally auto-generates these, but its parser gets confused
// by the braces/quotes inside the raw HTML string below and silently stops
// generating prototypes for anything after it. Declaring them here manually
// avoids the "was not declared in this scope" errors that causes.
void readSensors();
void logReading();
String getTimeString();
void checkWifiResetButton();
void handleRoot();
void handleResetWifi();
void handleData();

const char MAIN_page[] PROGMEM = R"HTMLPAGE(
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weather Station</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4"></script>
<style>
  :root{
    --bg:#0f1524; --card:#171f34; --card2:#1c2540; --text:#eef1fb;
    --muted:#8892b0; --accent:#4fd1c5; --warm:#f6ad55; --cool:#63b3ed; --pink:#f687b3;
  }
  *{box-sizing:border-box;}
  body{
    margin:0; font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;
    background:linear-gradient(160deg,#0f1524,#141b30 60%,#0f1524);
    color:var(--text); min-height:100vh; padding:20px;
  }
  header{
    display:flex; justify-content:space-between; align-items:center;
    flex-wrap:wrap; gap:10px; max-width:1100px; margin:0 auto 24px;
  }
  h1{font-size:1.4rem; margin:0; font-weight:700;}
  .status{
    display:flex; align-items:center; gap:8px; font-size:.85rem; color:var(--muted);
    background:var(--card); padding:8px 14px; border-radius:20px;
  }
  .dot{width:9px; height:9px; border-radius:50%; background:#4ade80;}
  .dot.off{background:#f87171;}
  .grid{
    max-width:1100px; margin:0 auto; display:grid;
    grid-template-columns:repeat(4,1fr); gap:16px; margin-bottom:20px;
  }
  .card{
    background:var(--card); border-radius:16px; padding:18px 20px;
    box-shadow:0 6px 20px rgba(0,0,0,.25);
  }
  .card .label{color:var(--muted); font-size:.8rem; text-transform:uppercase; letter-spacing:.06em;}
  .card .value{font-size:2rem; font-weight:700; margin-top:6px;}
  .card .unit{font-size:1rem; color:var(--muted); font-weight:400;}
  .charts{
    max-width:1100px; margin:0 auto; display:grid;
    grid-template-columns:1fr 1fr; gap:16px;
  }
  .chart-card{background:var(--card2); border-radius:16px; padding:16px; height:260px;}
  .chart-card h3{margin:0 0 8px; font-size:.9rem; color:var(--muted); font-weight:600;}
  footer{max-width:1100px; margin:24px auto 0; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:10px;}
  .btn{
    background:var(--card); color:var(--text); border:1px solid #2a3454; padding:10px 16px;
    border-radius:10px; cursor:pointer; font-size:.85rem;
  }
  .btn:hover{border-color:var(--accent);}
  .muted{color:var(--muted); font-size:.8rem;}
  @media(max-width:800px){
    .grid{grid-template-columns:repeat(2,1fr);}
    .charts{grid-template-columns:1fr;}
  }
</style>
</head>
<body>
<header>
  <h1>🌦️ Weather Station</h1>
  <div class="status"><span class="dot" id="wifiDot"></span><span id="wifiText">Connecting…</span></div>
</header>

<div class="grid">
  <div class="card"><div class="label">Temperature</div><div class="value" id="tempVal">--<span class="unit">°C</span></div></div>
  <div class="card"><div class="label">Humidity</div><div class="value" id="humVal">--<span class="unit">%</span></div></div>
  <div class="card"><div class="label">Pressure</div><div class="value" id="presVal">--<span class="unit">hPa</span></div></div>
  <div class="card"><div class="label">Light Level</div><div class="value" id="lightVal">--<span class="unit">%</span></div></div>
</div>

<div class="charts">
  <div class="chart-card"><h3>Temperature (°C) — last 60 min</h3><canvas id="chartTemp"></canvas></div>
  <div class="chart-card"><h3>Humidity (%) — last 60 min</h3><canvas id="chartHum"></canvas></div>
  <div class="chart-card"><h3>Pressure (hPa) — last 60 min</h3><canvas id="chartPres"></canvas></div>
  <div class="chart-card"><h3>Light Level (%) — last 60 min</h3><canvas id="chartLight"></canvas></div>
</div>

<footer>
  <span class="muted">Updated every 5 seconds · logged every 5 minutes</span>
  <button class="btn" onclick="resetWifi()">Reset WiFi</button>
</footer>

<script>
function baseOpts(color){
  return {
    type:'line',
    data:{labels:[],datasets:[{data:[],borderColor:color,backgroundColor:color+'22',
      tension:.35,fill:true,pointRadius:2}]},
    options:{
      responsive:true,maintainAspectRatio:false,
      plugins:{legend:{display:false}},
      scales:{
        x:{ticks:{color:'#8892b0',maxTicksLimit:6},grid:{color:'#232c47'}},
        y:{ticks:{color:'#8892b0'},grid:{color:'#232c47'}}
      }
    }
  };
}
const chartTemp  = new Chart(document.getElementById('chartTemp'),  baseOpts('#f6ad55'));
const chartHum   = new Chart(document.getElementById('chartHum'),   baseOpts('#63b3ed'));
const chartPres  = new Chart(document.getElementById('chartPres'),  baseOpts('#f687b3'));
const chartLight = new Chart(document.getElementById('chartLight'), baseOpts('#4fd1c5'));

function updateChart(c, labels, values){
  c.data.labels = labels;
  c.data.datasets[0].data = values;
  c.update('none');
}

async function refresh(){
  try{
    const res = await fetch('/data');
    const d = await res.json();

    document.getElementById('tempVal').innerHTML  = d.temp.toFixed(1)  + '<span class="unit">°C</span>';
    document.getElementById('humVal').innerHTML   = d.hum.toFixed(1)   + '<span class="unit">%</span>';
    document.getElementById('presVal').innerHTML  = d.pres.toFixed(1)  + '<span class="unit">hPa</span>';
    document.getElementById('lightVal').innerHTML = d.light.toFixed(0) + '<span class="unit">%</span>';

    const dot = document.getElementById('wifiDot');
    const txt = document.getElementById('wifiText');
    if(d.wifi === 'Connected'){ dot.classList.remove('off'); txt.textContent = 'WiFi connected · ' + d.rssi + ' dBm'; }
    else { dot.classList.add('off'); txt.textContent = 'WiFi disconnected'; }

    updateChart(chartTemp,  d.timeLog, d.tempLog);
    updateChart(chartHum,   d.timeLog, d.humLog);
    updateChart(chartPres,  d.timeLog, d.presLog);
    updateChart(chartLight, d.timeLog, d.lightLog);
  }catch(e){
    document.getElementById('wifiText').textContent = 'Device unreachable';
  }
}

function resetWifi(){
  if(confirm('This will forget the saved WiFi network and reboot into setup mode. Continue?')){
    fetch('/resetwifi').then(()=> alert('Restarting into setup mode — connect to the "WeatherStation-Setup" WiFi network to reconfigure.'));
  }
}

refresh();
setInterval(refresh, 5000);
</script>
</body>
</html>
)HTMLPAGE";

// ---------- Setup ----------
void setup() {
  Serial.begin(115200);
  pinMode(WIFI_RESET_BTN, INPUT_PULLUP);
  pinMode(STATUS_LED, OUTPUT);

  dht.begin();
  Wire.begin();

  if (!bmp.begin(0x76) && !bmp.begin(0x77)) {
    Serial.println("BMP280 not found — check wiring/address.");
  }
  if (!lightMeter.begin()) {
    Serial.println("BH1750 not found — check wiring/address.");
  }

  for (int i = 0; i < LOG_POINTS; i++) {
    tempLog[i] = humLog[i] = presLog[i] = lightLog[i] = 0;
    timeLog[i] = "--:--";
  }

  WiFiManager wm;
  // wm.resetSettings(); // uncomment once to force re-provisioning during testing
  bool connected = wm.autoConnect("WeatherStation-Setup");
  if (!connected) {
    Serial.println("Failed to connect and no timeout — restarting.");
    ESP.restart();
  }

  if (MDNS.begin("myweatherstation")) {
    Serial.println("Dashboard ready at: http://myweatherstation.local");
    MDNS.addService("http", "tcp", 80);
  }

  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);

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

  readSensors();
  logReading();
}

// ---------- Main loop ----------
void loop() {
  server.handleClient();
  checkWifiResetButton();

  unsigned long now = millis();

  if (now - lastRead >= READ_INTERVAL_MS) {
    lastRead = now;
    readSensors();
  }

  if (now - lastLog >= LOG_INTERVAL_MS) {
    lastLog = now;
    logReading();
  }

  if (now - lastWifiCheck >= 5000) {
    lastWifiCheck = now;
    digitalWrite(STATUS_LED, WiFi.status() == WL_CONNECTED ? HIGH : (millis() / 300) % 2);
  }
}

// ---------- Sensors ----------
void readSensors() {
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  if (!isnan(h) && !isnan(t)) { curTemp = t; curHum = h; }

  curPres = bmp.readPressure() / 100.0F; // Pa -> hPa

  float lux = lightMeter.readLightLevel();
  if (lux < 0) lux = 0;
  float pct = (lux / MAX_LUX) * 100.0;
  curLightPct = constrain(pct, 0, 100);
}

void logReading() {
  tempLog[logIndex]  = curTemp;
  humLog[logIndex]   = curHum;
  presLog[logIndex]  = curPres;
  lightLog[logIndex] = curLightPct;
  timeLog[logIndex]  = getTimeString();

  logIndex = (logIndex + 1) % LOG_POINTS;
  if (logIndex == 0) logFilled = true;
}

String getTimeString() {
  struct tm timeinfo;
  if (!getLocalTime(&timeinfo, 200)) return "--:--";
  char buf[6];
  strftime(buf, sizeof(buf), "%H:%M", &timeinfo);
  return String(buf);
}

// ---------- WiFi reset button (hold ~3s) ----------
void checkWifiResetButton() {
  if (digitalRead(WIFI_RESET_BTN) == LOW) {
    if (!buttonHeld) {
      buttonHeld = true;
      buttonPressStart = millis();
    } else if (millis() - buttonPressStart > 3000) {
      Serial.println("Button held — resetting WiFi settings.");
      WiFiManager wm;
      wm.resetSettings();
      delay(300);
      ESP.restart();
    }
  } else {
    buttonHeld = false;
  }
}

// ---------- Web handlers ----------
void handleRoot() {
  server.send_P(200, "text/html", MAIN_page);
}

void handleResetWifi() {
  server.send(200, "text/plain", "Resetting WiFi settings, restarting...");
  delay(300);
  WiFiManager wm;
  wm.resetSettings();
  ESP.restart();
}

void handleData() {
  StaticJsonDocument<3072> doc;
  doc["temp"]  = curTemp;
  doc["hum"]   = curHum;
  doc["pres"]  = curPres;
  doc["light"] = curLightPct;
  doc["wifi"]  = WiFi.status() == WL_CONNECTED ? "Connected" : "Disconnected";
  doc["rssi"]  = WiFi.RSSI();

  JsonArray tArr = doc.createNestedArray("tempLog");
  JsonArray hArr = doc.createNestedArray("humLog");
  JsonArray pArr = doc.createNestedArray("presLog");
  JsonArray lArr = doc.createNestedArray("lightLog");
  JsonArray timeArr = doc.createNestedArray("timeLog");

  int count = logFilled ? LOG_POINTS : logIndex;
  int start = logFilled ? logIndex : 0;

  for (int i = 0; i < count; i++) {
    int idx = (start + i) % LOG_POINTS;
    tArr.add(tempLog[idx]);
    hArr.add(humLog[idx]);
    pArr.add(presLog[idx]);
    lArr.add(lightLog[idx]);
    timeArr.add(timeLog[idx]);
  }

  String out;
  serializeJson(doc, out);
  server.send(200, "application/json", out);
}

A few implementation notes worth understanding rather than just copy-pasting:

  • The log array is a ring buffer. Instead of shifting 12 array elements every 5 minutes (wasteful), the code just overwrites the oldest slot and tracks where the “start” of the data currently is. handleData() reads it back out in the correct chronological order before sending it to the browser.
  • server.send_P() sends the MAIN_page string straight out of flash (PROGMEM) instead of copying it into RAM first, which matters once your HTML/CSS/JS starts getting large.
  • The chart data lives entirely in the ESP32’s RAM. There’s no SPIFFS or SD card write involved, which means zero flash wear from logging — the trade-off is that the 60-minute history resets on reboot. If you want history to survive a power cut, see the extensions section below.

How the Web Dashboard Works

ESP32 Weather Station output on Webserver Dashboard with Charts

 

The dashboard is a single HTML page served from the ESP32 itself — there’s no separate app, no companion server, and nothing to install. Once your browser loads it, a small JavaScript loop calls fetch('/data') every 5 seconds, which returns a compact JSON object containing the current readings plus the full rolling log. That data is used to update the four stat cards and the four Chart.js line charts without reloading the page, so the UI feels closer to a native app than a typical Arduino web page.

Keeping the page fast came down to a few deliberate choices:

  • No web frameworks. Plain HTML, CSS and vanilla JavaScript keep the payload tiny, which matters since the ESP32 is serving it directly with limited RAM and bandwidth.
  • Chart.update('none') instead of redrawing charts from scratch — this skips the animation on every refresh, which keeps things smooth even when all four charts update simultaneously.
  • System fonts only — no external font files to download, so the page renders instantly even on a slow connection.
  • One CDN dependency (Chart.js) — this is the only thing that requires internet access. If you plan to run the dashboard on a network with no internet uplink at all, download chart.min.js, store it in SPIFFS, and change the <script src="..."> tag to point at a local /chart.js route instead.

Setting Up WiFi and the Reset Button

This project uses the WiFiManager library instead of hardcoding your SSID and password into the sketch — a small change that fixes one of the most annoying parts of any home IoT project.

First boot: the ESP32 won’t find any saved WiFi credentials, so it starts its own access point called WeatherStation-Setup. Connect to that network from your phone or laptop, and a captive portal should pop up automatically (if it doesn’t, open a browser and go to 192.168.4.1). Pick your home WiFi network from the list, enter the password, and the ESP32 will save it, reboot, and join your network.

Changing networks later — the WiFi reset button: rather than re-flashing the sketch just to switch networks (say, you’re moving the sensor to a new house, or lending it to a friend), hold the ESP32’s BOOT button (GPIO 0) for about 3 seconds. This wipes the saved credentials via wm.resetSettings() and reboots straight back into the WeatherStation-Setup access point, ready to be paired again. There’s also a “Reset WiFi” button right on the dashboard itself that does the same thing remotely, in case the board isn’t physically accessible.


Accessing myweatherstation.local

Once connected to your home network, the sketch registers an mDNS hostname so you can reach the dashboard at http://myweatherstation.local instead of tracking down whatever IP address your router happened to assign it.

A couple of platform notes:

  • macOS and iOS support .local addresses out of the box (via Bonjour) — this will just work.
  • Android and most Linux distributions also resolve .local addresses natively in most cases.
  • Windows needs Bonjour installed to resolve .local hostnames reliably — it ships with iTunes, or you can install “Bonjour Print Services” standalone. Without it, Windows machines should fall back to the IP address shown in the Serial Monitor after boot.

If myweatherstation.local doesn’t resolve on your network for any reason, the ESP32’s IP address (printed to Serial on connect, and viewable from your router’s connected-devices list) always works as a fallback.


Calibrating the Light Percentage

The BH1750 measures light in lux, a unit that spans an enormous range — a dim room might be 50 lux, an office 500 lux, and direct sunlight can exceed 50,000 lux. Rather than display a raw number that’s meaningless to most people glancing at a dashboard, the sketch scales the reading against a MAX_LUX constant to produce a friendlier 0–100% value.

To calibrate it for your own setup:

  1. Upload the sketch and open the Serial Monitor, or temporarily add a Serial.println(lux) line inside readSensors().
  2. Note the highest lux value you realistically expect the sensor to see — for an indoor desk placement that might be a few thousand lux near a window; for an outdoor mount in direct sun, it could be 50,000+.
  3. Set MAX_LUX in the sketch to that value. Readings above it will simply cap at 100%, which is fine — the goal is a meaningful scale for your actual environment, not a scientifically exact lux readout.

If you’d rather keep the precise lux value available too, it’s a one-line change: just add doc["lux"] = lux; inside handleData() and display it alongside the percentage on the dashboard.


Troubleshooting

  • 'handleRoot' was not declared in this scope (or similar for other functions) — this happens because the Arduino IDE auto-generates function prototypes by scanning the file, and that scanner gets confused by the braces and quotes inside the raw HTML string (R"HTMLPAGE(...)"). It silently stops generating prototypes for anything defined after that string. The sketch above already includes manual prototypes right before MAIN_page to prevent this — if you’re editing the code and adding new functions, declare them the same way, above the HTML string.
  • “BMP280 not found” in Serial Monitor — the two most common BMP280 breakout addresses are 0x76 and 0x77; the sketch already tries both, so if it still fails, double-check your SDA/SCL wiring and confirm the module is genuinely a BMP280 and not a BME280 clone mislabeled (they use different Adafruit libraries).
  • DHT22 returns nan readings — this is almost always a wiring or timing issue. Make sure there’s a pull-up resistor between DATA and 3.3V (many breakout boards already include one), and avoid reading it faster than once every 2 seconds.
  • Captive portal doesn’t appear after connecting to WeatherStation-Setup — some phones are slow to trigger it; manually open a browser and navigate to 192.168.4.1.
  • myweatherstation.local doesn’t load on Windows — install Bonjour, or just use the ESP32’s IP address instead (check your router’s client list or the Serial Monitor).
  • Charts don’t appear but the stat cards update fine — this almost always means the device serving the dashboard has no path to the Chart.js CDN. Check the browser’s internet access, or switch to a locally hosted copy of Chart.js as described in the dashboard section.
  • Dashboard feels slow to update — the default 5-second poll interval is a balance between “live” and not hammering the ESP32’s single web server thread. If you have other clients connected simultaneously, consider raising this to 8–10 seconds in the JavaScript setInterval() call.

Ways to Extend This Project

Once the base dashboard is working, a few natural next steps:

  • Persist history across reboots by writing the log arrays to SPIFFS or an SD card on a timer, and reading them back in setup().
  • Push data to the cloud (ThingSpeak, Blynk, or a self-hosted Home Assistant instance via MQTT) so you can track long-term trends beyond 60 minutes.
  • Add OTA updates with ArduinoOTA so you can push firmware changes without a USB cable once the station is mounted somewhere inconvenient.
  • Export logged data as CSV by adding a /download route that streams the log arrays as a downloadable file.
  • Add a rain gauge or wind sensor for a fuller weather picture — the same JSON/chart pattern used here extends cleanly to more sensors.
  • Battery + solar power for a fully outdoor-mountable station, using the ESP32’s deep sleep modes between readings to stretch battery life (note this needs rethinking the “live” 3-second read loop into a wake-read-sleep cycle).

Related project: Live Weather Station using NodeMCU ESP8266 with dashboard IOT


FAQs

Can I use a DHT11 instead of a DHT22?

Yes — just change DHTTYPE to DHT11. Expect noisier temperature and humidity charts, since the DHT11 has roughly ±2°C and ±5%RH accuracy versus the DHT22’s tighter tolerances.

Why does the light reading show a percentage instead of lux?

Raw lux values swing across several orders of magnitude depending on lighting conditions, which makes them hard to read at a glance on a dashboard. Scaling against a calibrated maximum (see Calibrating the Light Percentage) gives a far more intuitive 0–100% “brightness level” instead.

Does myweatherstation.local work from outside my home network?

No — mDNS hostnames only resolve within the local network. To access the dashboard remotely, you’d need to set up port forwarding, a VPN back into your home network, or push data to a cloud service instead.

How much of the ESP32’s memory does this use?

Comfortably little. The 12-point log arrays, the embedded HTML page, and the JSON buffer all fit well within a standard ESP32’s RAM and flash, leaving plenty of headroom for the extensions listed above.

Will the logged data survive a power cut? Not in this version — the log lives in RAM for simplicity and to avoid flash wear from writing every 5 minutes. See the extensions section for how to persist it to SPIFFS or an SD card if that matters for your use case.

Can I run this on ESP8266 instead of ESP32? Mostly, with adjustments — you’d need to remap pins (ESP8266 has fewer usable GPIOs), swap WebServer.h for ESP8266WebServer.h, and confirm your WiFiManager version supports ESP8266 (most do). The ESP32’s extra RAM makes it a more comfortable fit for running three sensors, a web server, and live charts simultaneously, though.

Add a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *