Close Menu
  • Articles
    • Learn Electronics
    • Product Review
    • Tech Articles
  • Electronics Circuits
    • 555 Timer Projects
    • Op-Amp Circuits
    • Power Electronics
  • Microcontrollers
    • Arduino Projects
    • STM32 Projects
    • AMB82-Mini IoT AI Camera
    • BLE Projects
  • IoT Projects
    • ESP8266 Projects
    • ESP32 Projects
    • ESP32 MicroPython
    • ESP32-CAM Projects
    • LoRa/LoRaWAN Projects
  • Raspberry Pi
    • Raspberry Pi Projects
    • Raspberry Pi Pico Projects
    • Raspberry Pi Pico W Projects
  • Electronics Calculator
Facebook X (Twitter) Instagram
  • About Us
  • Disclaimer
  • Privacy Policy
  • Contact Us
  • Advertise With Us
Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
How To Electronics
  • Articles
    • Learn Electronics
    • Product Review
    • Tech Articles
  • Electronics Circuits
    • 555 Timer Projects
    • Op-Amp Circuits
    • Power Electronics
  • Microcontrollers
    • Arduino Projects
    • STM32 Projects
    • AMB82-Mini IoT AI Camera
    • BLE Projects
  • IoT Projects
    • ESP8266 Projects
    • ESP32 Projects
    • ESP32 MicroPython
    • ESP32-CAM Projects
    • LoRa/LoRaWAN Projects
  • Raspberry Pi
    • Raspberry Pi Projects
    • Raspberry Pi Pico Projects
    • Raspberry Pi Pico W Projects
  • Electronics Calculator
How To Electronics
Home » IoT Based PM & Air Quality Monitoring System using ESP32
ESP32 Projects IoT Projects

IoT Based PM & Air Quality Monitoring System using ESP32

Mamtaz AlamBy Mamtaz AlamUpdated:June 14, 202611 Mins Read
Share Facebook Twitter LinkedIn Telegram Reddit WhatsApp
IoT Based PM & Air Quality Monitoring System using ESP32
Share
Facebook Twitter LinkedIn Pinterest Email Reddit Telegram WhatsApp

Overview

In this project, we will make an IoT Based PM and Air Quality Monitoring System using ESP32, PMS7003, BME680, and OLED Display. This device will measure dust particles in the air, such as PM1.0, PM2.5, and PM10.

The BME680 sensor will measure temperature, humidity, IAQ, CO2 equivalent, and VOC equivalent. These values help us understand the overall air quality around us and detect poor ventilation, dust, smoke, or harmful gases.

All readings will be shown on the OLED display and also on a web dashboard using the ESP32 Wi-Fi. The ESP32 creates a local webserver and hosts a modern web dashboard. The dashboard displays all sensor readings in a clean and professional interface. It includes separate sections for live dashboard readings, PM readings, environment data, history logging, and alerts. The dashboard can also show graphs, log sensor data, export readings, and generate alerts when pollution or air quality values go beyond selected limits.


Components Required

Following are the components required for making this project. The components Purchased links are given as well.

S.N.Components NameQuantityPurchase Link
1ESP32 Board1Amazon | AliExpress
2PMS7003 PM Sensor1Amazon | AliExpress
3BME680 Sensor1Amazon | AliExpress
4OLED Display 0.96"1Amazon | AliExpress
510uF Electrolytic Capacitor2Amazon | AliExpress
60.1uF Ceramic Capacitor4Amazon | AliExpress
7Jumper Wires4Amazon | AliExpress




PMS7003 Particulate Matter Sensor

The PMS7003 is a digital particulate matter sensor used to measure dust particles present in the air. It is commonly used in air quality monitoring systems to detect fine particles such as PM1.0, PM2.5, and PM10.

PMS7003 PM2.5 Sensor

This sensor works on the principle of laser scattering. A small fan pulls air into the sensor, and a laser detects the particles passing through the air chamber. Based on the detected particles, the sensor calculates the particle concentration and sends the data through UART serial communication.

In this project, the PMS7003 is used with the ESP32 to measure real-time particulate matter levels. The readings help us understand the amount of dust, smoke, and pollution particles present in the surrounding air. Earlier we used PMS5003 with Arduino, which you can take as a reference for studying.

PMS7003 Specifications

  • Sensor Type: Laser Particulate Matter Sensor
  • Measured Particles: PM1.0, PM2.5, and PM10
  • Output Unit: µg/m³
  • Communication Interface: UART Serial
  • Baud Rate: 9600 bps
  • Operating Voltage: 5V DC
  • Working Current: Around 100 mA
  • Measuring Range: 0 to 500 µg/m³
  • Particle Detection Size: 0.3 µm and above
  • Response Time: Less than 10 seconds
  • Operating Temperature: -10°C to 60°C
  • Operating Humidity: 0% to 99% RH
  • Application: Air quality monitoring, dust detection, and pollution monitoring




BME680 Environmental Sensor

The BME680 is an environmental sensor that can measure temperature, humidity, pressure, and gas resistance. It is commonly used in air quality monitoring projects because it can help detect changes in the surrounding environment.

BME680

This sensor includes a gas sensor that can detect the presence of different volatile organic compounds, also known as VOCs. With the help of the BSEC library, the BME680 can calculate useful values such as IAQ, CO2 equivalent, and VOC equivalent.

In this project, the BME680 is connected to the ESP32 using the I2C communication protocol. It helps us monitor indoor air quality, room temperature, humidity level, and gas-based air pollution in real time. You can refer to BME680 ESP8266 tutorial for more better understanding.

BME680 Specifications

  • Sensor Type: Environmental and Gas Sensor
  • Measured Parameters: Temperature, Humidity, Pressure, and Gas Resistance
  • Calculated Values: IAQ, CO2 Equivalent, and VOC Equivalent
  • Communication Interface: I2C and SPI
  • I2C Address: 0x76 or 0x77
  • Operating Voltage: 3.3V DC
  • Temperature Range: -40°C to 85°C
  • Humidity Range: 0% to 100% RH
  • Pressure Range: 300 hPa to 1100 hPa
  • Gas Sensor: VOC gas detection
  • Low Power Consumption: Suitable for IoT devices
  • Application: Air quality monitoring, weather monitoring, indoor environment monitoring, and IoT projects

Circuit: IoT Based PM & Air Quality Monitoring System using ESP32

Here is the circuit diagram for IoT ESP32 based air quality monitoring system. The ESP32 is the main controller of the system. It reads air quality data from the PMS7003 sensor and reads environmental data from the BME280 sensor. The OLED display is used to show the sensor readings locally.

The OLED display and BME280 sensor both use the I2C communication pins of the ESP32. Their SCL pins are connected to ESP32 GPIO22, and their SDA pins are connected to ESP32 GPIO21. Both modules are powered using 3.3V and connected to common GND.

The PMS7003 sensor is connected to the ESP32 using UART serial communication. The TX pin of PMS7003 is connected to the RX pin of ESP32, and the RX pin of PMS7003 is connected to the TX pin of ESP32. The PMS7003 is powered from +5V and GND.

Capacitors are also added near the power supply lines for stable operation. These capacitors improve the stability of the OLED display, BME280 sensor, PMS7003 sensor, and ESP32 board.




PCB Designing & Gerber Files

The schematic of the ESP32 Air Quality & Particulate Matter monitoring system was created in EasyEDA, and from there it was converted into a compact PCB layout.

Fig: PCB Layout

The board is designed with mostly through-hole components to make easier assembly. You can view the 2D view of the PCB.

Fig: PCB 2D View

All of the critical components, including the ESP32 module, are placed on the front side of the PCB, which makes assembly easier and more reliable.

Here are the link of files that you can download for PCB manufacturing and PCB assembly services.

  1. Download: Schematic PDF
  2. Download: Gerber File




PCB Ordering Online & Assembly

The Gerber file for this ESP32, PMS7003, BME680 Air Quality Monitor is provided above. You can download the Gerber file and place an order with a PCB manufacturer like AIVON for as low as $1 for a PCB Prototype.

To order the PCB, visit the AIVON Official Website and upload the Gerber file using the Quote Now option. You can then choose your required parameters, such as Material Type, Dimensions, Quantity, Thickness, and Solder Mask Color.

AIVON is making PCB prototyping and assembly more affordable for new users by offering $1 PCB Prototype and $35 PCB Assembly with Shipping fee $30 OFF on your first PCB order. With this promotion, you can enjoy free shipping on your first order and affordable assembly service for your project.

Here is the promotion link: AIVON PCB/PCBA Promotion Offer

Once all the details are filled in, select your country and shipping method. After confirming everything, you can place the order and wait for your boards to arrive.




Assembly of the IoT Air Quality ESP32 Board

After I ordered the custom PCB, I received it within just 3 days. The PCB quality was very good, and it looked clean and professional. It is a double-sided PCB, which makes the circuit compact and neat.

Then I started soldering and assembling all the components on the board. For the ESP32 board, OLED display, and BME680 sensor, I used female header pins. This makes it easy to remove or replace the modules later if needed.

I also soldered the required capacitors on different parts of the PCB. These capacitors help to keep the power supply stable and reduce noise in the circuit. For the PMS7003 sensor, I used 4 jumper wires instead of directly soldering it on the PCB.

The PMS7003 needs proper air flow for accurate particle detection, so it should be placed in a suitable position. Using jumper wires makes it easier to adjust the position of the PMS7003 module.

IoT Air Quality Monitoring System using ESP32 PMS7003 BME680

After soldering all the parts, I connected the sensor and completed the final assembly of the IoT ESP32 air quality monitoring device.




Source Code/program

Let us take a look at the programming part of this project.

The code starts by including the required libraries for the project. The WiFi and WebServer libraries are used to connect the ESP32 to a Wi-Fi network and create a local web dashboard. The BSEC library is used with the BME680 sensor to get final air quality values such as IAQ, CO2 equivalent, and VOC equivalent. The Adafruit GFX and Adafruit SSD1306 libraries are used to control the OLED display.

In the Wi-Fi section, the SSID and password are added so the ESP32 can connect to the local network. After the connection is successful, the ESP32 prints its IP address on the Serial Monitor and also shows it on the OLED display. This IP address can be opened in a browser to view the live air quality dashboard.

The main loop continuously reads data from the PMS7003 and BME680 sensors. The PMS7003 provides PM1.0, PM2.5, and PM10 values, while the BME680 provides temperature, humidity, IAQ, CO2, and VOC data. These readings are displayed on the OLED screen, printed on the Serial Monitor, and sent to the web dashboard as JSON data through the /api/readings route.

The code is divided into two sections one with the main .ino code and other with the webpage header file.

Main ino code

Copy the following code and paste it to your Arduino IDE editor window.

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
#include <Arduino.h>
#include <Wire.h>
#include <WiFi.h>
#include <WebServer.h>
#include "bsec.h"
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include "webpage.h"
 
// -------- WiFi --------
const char* ssid = "*****************";
const char* password = "*****************";
 
// -------- Webserver --------
WebServer server(80);
 
// -------- OLED --------
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
#define OLED_ADDR 0x3C
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
 
// -------- PMS7003 --------
#define PMS_RX 16
#define PMS_TX 17
HardwareSerial pmsSerial(2);
 
// -------- BME680 I2C --------
#define I2C_SDA 21
#define I2C_SCL 22
 
#ifndef LED_BUILTIN
#define LED_BUILTIN 2
#endif
 
Bsec iaqSensor;
 
struct PMS7003Data {
  uint16_t pm1_0_atm;
  uint16_t pm2_5_atm;
  uint16_t pm10_atm;
};
 
PMS7003Data pmsData;
 
uint16_t pm1_0 = 0;
uint16_t pm2_5 = 0;
uint16_t pm10 = 0;
 
float temperatureC = 0;
float humidityRH = 0;
float iaqValue = 0;
float co2Equivalent = 0;
float vocEquivalent = 0;
uint8_t iaqAccuracy = 0;
 
unsigned long lastSerialPrintTime = 0;
unsigned long lastDisplayUpdateTime = 0;
 
const unsigned long serialPrintInterval = 3000;
const unsigned long displayUpdateInterval = 500;
const unsigned long pageSwitchInterval = 5000;
 
bool readPMS7003(PMS7003Data &data);
void checkIaqSensorStatus();
void errLeds();
String getAccuracyText(uint8_t accuracy);
String getAirQualityStatus(float iaq);
String getJsonReadings();
void updateOLED();
void showPage1();
void showPage2();
 
void handleRoot() {
  server.send_P(200, "text/html", INDEX_HTML);
}
 
void handleReadings() {
  server.sendHeader("Access-Control-Allow-Origin", "*");
  server.send(200, "application/json", getJsonReadings());
}
 
void handleNotFound() {
  server.send(404, "text/plain", "404 Not Found");
}
 
void setup() {
  Serial.begin(115200);
  delay(1000);
 
  Serial.println("\nESP32 PMS7003 + BME680 + OLED + Webserver");
 
  Wire.begin(I2C_SDA, I2C_SCL);
 
  if (!display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR)) {
    Serial.println("OLED not found.");
  } else {
    display.clearDisplay();
    display.setTextColor(SSD1306_WHITE);
    display.setTextSize(1);
    display.setCursor(0, 0);
    display.println("Air Quality");
    display.println("Starting...");
    display.display();
  }
 
  pmsSerial.begin(9600, SERIAL_8N1, PMS_RX, PMS_TX);
 
  // BME680 address 0x77
  iaqSensor.begin(BME68X_I2C_ADDR_HIGH, Wire);
  checkIaqSensorStatus();
 
  bsec_virtual_sensor_t sensorList[5] = {
    BSEC_OUTPUT_IAQ,
    BSEC_OUTPUT_CO2_EQUIVALENT,
    BSEC_OUTPUT_BREATH_VOC_EQUIVALENT,
    BSEC_OUTPUT_SENSOR_HEAT_COMPENSATED_TEMPERATURE,
    BSEC_OUTPUT_SENSOR_HEAT_COMPENSATED_HUMIDITY
  };
 
  iaqSensor.updateSubscription(sensorList, 5, BSEC_SAMPLE_RATE_LP);
  checkIaqSensorStatus();
 
  display.clearDisplay();
  display.setCursor(0, 0);
  display.println("Connecting WiFi");
  display.display();
 
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
 
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
 
  Serial.println();
  Serial.print("Dashboard IP: ");
  Serial.println(WiFi.localIP());
 
  display.clearDisplay();
  display.setCursor(0, 0);
  display.println("WiFi Connected");
  display.println(WiFi.localIP());
  display.display();
  delay(1500);
 
  server.on("/", HTTP_GET, handleRoot);
  server.on("/api/readings", HTTP_GET, handleReadings);
  server.onNotFound(handleNotFound);
  server.begin();
 
  Serial.println("Webserver started.");
}
 
void loop() {
  server.handleClient();
 
  if (readPMS7003(pmsData)) {
    pm1_0 = pmsData.pm1_0_atm;
    pm2_5 = pmsData.pm2_5_atm;
    pm10 = pmsData.pm10_atm;
  }
 
  if (iaqSensor.run()) {
    temperatureC = iaqSensor.temperature;
    humidityRH = iaqSensor.humidity;
    iaqValue = iaqSensor.iaq;
    co2Equivalent = iaqSensor.co2Equivalent;
    vocEquivalent = iaqSensor.breathVocEquivalent;
    iaqAccuracy = iaqSensor.iaqAccuracy;
  } else {
    checkIaqSensorStatus();
  }
 
  if (millis() - lastDisplayUpdateTime >= displayUpdateInterval) {
    lastDisplayUpdateTime = millis();
    updateOLED();
  }
 
  if (millis() - lastSerialPrintTime >= serialPrintInterval) {
    lastSerialPrintTime = millis();
 
    Serial.println("================================");
    Serial.print("PM1.0: "); Serial.print(pm1_0); Serial.println(" ug/m3");
    Serial.print("PM2.5: "); Serial.print(pm2_5); Serial.println(" ug/m3");
    Serial.print("PM10 : "); Serial.print(pm10); Serial.println(" ug/m3");
    Serial.print("Temp : "); Serial.print(temperatureC, 2); Serial.println(" C");
    Serial.print("Hum  : "); Serial.print(humidityRH, 2); Serial.println(" %");
    Serial.print("IAQ  : "); Serial.print(iaqValue, 2);
    Serial.print(" | Accuracy: "); Serial.print(iaqAccuracy);
    Serial.print(" - "); Serial.println(getAccuracyText(iaqAccuracy));
    Serial.print("CO2  : "); Serial.print(co2Equivalent, 2); Serial.println(" ppm");
    Serial.print("VOC  : "); Serial.print(vocEquivalent, 2); Serial.println(" ppm");
    Serial.print("Web  : http://"); Serial.println(WiFi.localIP());
    Serial.println("================================\n");
  }
}
 
String getJsonReadings() {
  String json = "{";
  json += "\"pm1\":" + String(pm1_0) + ",";
  json += "\"pm25\":" + String(pm2_5) + ",";
  json += "\"pm10\":" + String(pm10) + ",";
  json += "\"temperature\":" + String(temperatureC, 2) + ",";
  json += "\"humidity\":" + String(humidityRH, 2) + ",";
  json += "\"iaq\":" + String(iaqValue, 2) + ",";
  json += "\"iaqAccuracy\":" + String(iaqAccuracy) + ",";
  json += "\"iaqAccuracyText\":\"" + getAccuracyText(iaqAccuracy) + "\",";
  json += "\"co2\":" + String(co2Equivalent, 2) + ",";
  json += "\"voc\":" + String(vocEquivalent, 2) + ",";
  json += "\"status\":\"" + getAirQualityStatus(iaqValue) + "\",";
  json += "\"calibrating\":" + String(iaqAccuracy == 0 ? "true" : "false") + ",";
  json += "\"ip\":\"" + WiFi.localIP().toString() + "\",";
  json += "\"uptime\":" + String(millis() / 1000);
  json += "}";
  return json;
}
 
void updateOLED() {
  if (((millis() / pageSwitchInterval) % 2) == 0) showPage1();
  else showPage2();
}
 
void showPage1() {
  display.clearDisplay();
  display.setTextColor(SSD1306_WHITE);
  display.setTextSize(1);
 
  display.setCursor(0, 0);
  display.print("PM1.0 : ");
  display.setTextSize(2);
  display.print(pm1_0);
  display.setTextSize(1);
  display.println(" ug");
 
  display.setCursor(0, 22);
  display.print("PM2.5 : ");
  display.setTextSize(2);
  display.print(pm2_5);
  display.setTextSize(1);
  display.println(" ug");
 
  display.setCursor(0, 44);
  display.print("PM10  : ");
  display.setTextSize(2);
  display.print(pm10);
  display.setTextSize(1);
  display.print(" ug");
 
  display.display();
}
 
void showPage2() {
  display.clearDisplay();
  display.setTextColor(SSD1306_WHITE);
  display.setTextSize(1);
 
  if (iaqAccuracy == 0) {
    display.setCursor(82, 0);
    display.print("CAL...");
  }
 
  display.setCursor(0, 0);
  display.print("Temp: ");
  display.print(temperatureC, 1);
  display.print(" C");
 
  display.setCursor(0, 13);
  display.print("Hum : ");
  display.print(humidityRH, 1);
  display.print(" %");
 
  display.setCursor(0, 26);
  display.print("IAQ : ");
  display.print(iaqValue, 1);
 
  display.setCursor(0, 39);
  display.print("CO2 : ");
  display.print(co2Equivalent, 0);
  display.print(" ppm");
 
  display.setCursor(0, 52);
  display.print("VOC : ");
  display.print(vocEquivalent, 2);
  display.print(" ppm");
 
  display.display();
}
 
bool readPMS7003(PMS7003Data &data) {
  if (pmsSerial.available() < 32) return false;
 
  while (pmsSerial.available() >= 32) {
    if (pmsSerial.read() == 0x42) {
      if (pmsSerial.peek() == 0x4D) break;
    }
  }
 
  if (pmsSerial.available() < 31) return false;
 
  uint8_t buffer[32];
  buffer[0] = 0x42;
  buffer[1] = pmsSerial.read();
 
  for (int i = 2; i < 32; i++) {
    buffer[i] = pmsSerial.read();
  }
 
  if (buffer[0] != 0x42 || buffer[1] != 0x4D) return false;
 
  uint16_t frameLength = (buffer[2] << 8) | buffer[3];
  if (frameLength != 28) return false;
 
  uint16_t sum = 0;
  for (int i = 0; i < 30; i++) {
    sum += buffer[i];
  }
 
  uint16_t checksum = (buffer[30] << 8) | buffer[31];
  if (sum != checksum) return false;
 
  data.pm1_0_atm = (buffer[10] << 8) | buffer[11];
  data.pm2_5_atm = (buffer[12] << 8) | buffer[13];
  data.pm10_atm  = (buffer[14] << 8) | buffer[15];
 
  return true;
}
 
String getAccuracyText(uint8_t accuracy) {
  if (accuracy == 0) return "Calibrating";
  if (accuracy == 1) return "Low";
  if (accuracy == 2) return "Medium";
  if (accuracy == 3) return "High";
  return "Unknown";
}
 
String getAirQualityStatus(float iaq) {
  if (iaq <= 50) return "Good";
  if (iaq <= 100) return "Moderate";
  if (iaq <= 150) return "Poor";
  if (iaq <= 200) return "Unhealthy";
  if (iaq <= 300) return "Very Unhealthy";
  return "Hazardous";
}
 
void checkIaqSensorStatus() {
  if (iaqSensor.bsecStatus != BSEC_OK) {
    if (iaqSensor.bsecStatus < BSEC_OK) {
      Serial.print("BSEC error code: ");
      Serial.println(iaqSensor.bsecStatus);
      while (1) errLeds();
    } else {
      Serial.print("BSEC warning code: ");
      Serial.println(iaqSensor.bsecStatus);
    }
  }
 
  if (iaqSensor.bme68xStatus != BME68X_OK) {
    if (iaqSensor.bme68xStatus < BME68X_OK) {
      Serial.print("BME68X error code: ");
      Serial.println(iaqSensor.bme68xStatus);
      while (1) errLeds();
    } else {
      Serial.print("BME68X warning code: ");
      Serial.println(iaqSensor.bme68xStatus);
    }
  }
}
 
void errLeds() {
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(100);
  digitalWrite(LED_BUILTIN, LOW);
  delay(100);
}

From the following lines, change the WiFi SSID and Password.

C++
1
2
3
// -------- WiFi --------
const char* ssid = "*****************";
const char* password = "*****************";

After replacing the WiFi SSID and password, you are good to go.



webpage.h file

Here is the header file for the project. You need to create another tab on Arduino IDE editor window and paste the following code that consist of webpage files.

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
#ifndef WEBPAGE_H
#define WEBPAGE_H
 
const char INDEX_HTML[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>AeroSense IoT</title>
 
<style>
:root{
  --dark:#0f172a;
  --dark2:#111827;
  --text:#172033;
  --muted:#667085;
  --line:#e5e7eb;
  --blue:#2563eb;
  --cyan:#06b6d4;
  --green:#16a34a;
  --orange:#f97316;
  --red:#ef4444;
  --purple:#7c3aed;
  --yellow:#eab308;
  --shadow:0 18px 45px rgba(15,23,42,.10);
  --radius:24px;
}
 
*{
  box-sizing:border-box;
}
 
body{
  margin:0;
  font-family:Arial,Helvetica,sans-serif;
  color:var(--text);
  background:
    radial-gradient(circle at top left,rgba(6,182,212,.18),transparent 30%),
    radial-gradient(circle at top right,rgba(37,99,235,.14),transparent 30%),
    linear-gradient(135deg,#f0f9ff,#f8fafc 45%,#ecfdf5);
}
 
.app{
  display:grid;
  grid-template-columns:280px 1fr;
  min-height:100vh;
}
 
.sidebar{
  position:sticky;
  top:0;
  height:100vh;
  padding:24px 20px;
  background:
    radial-gradient(circle at 20% 0%,rgba(6,182,212,.24),transparent 30%),
    linear-gradient(180deg,var(--dark),var(--dark2));
  color:white;
}
 
.brand{
  display:flex;
  align-items:center;
  gap:14px;
  margin-bottom:34px;
}
 
.brand-icon{
  width:52px;
  height:52px;
  border-radius:18px;
  display:grid;
  place-items:center;
  background:linear-gradient(135deg,#22d3ee,#2563eb,#16a34a);
  font-size:25px;
  box-shadow:0 16px 36px rgba(6,182,212,.25);
}
 
.brand h1{
  margin:0;
  font-size:19px;
  line-height:1.1;
}
 
.brand p{
  margin:5px 0 0;
  color:#94a3b8;
  font-size:12px;
}
 
.nav-title{
  margin:22px 8px 10px;
  color:#64748b;
  font-size:11px;
  font-weight:800;
  letter-spacing:.12em;
  text-transform:uppercase;
}
 
.nav button{
  width:100%;
  display:flex;
  align-items:center;
  gap:12px;
  padding:13px 14px;
  margin:7px 0;
  color:#cbd5e1;
  background:transparent;
  border:0;
  text-align:left;
  border-radius:16px;
  font-size:14px;
  cursor:pointer;
  transition:.2s;
}
 
.nav button:hover,
.nav button.active{
  color:white;
  background:rgba(255,255,255,.10);
  transform:translateX(4px);
}
 
.sidebar-footer{
  position:absolute;
  left:20px;
  right:20px;
  bottom:24px;
  padding:16px;
  border-radius:20px;
  background:rgba(255,255,255,.08);
  border:1px solid rgba(255,255,255,.12);
}
 
.online{
  display:flex;
  align-items:center;
  gap:8px;
  color:#bbf7d0;
  font-weight:800;
  font-size:13px;
  margin-bottom:8px;
}
 
.dot{
  width:10px;
  height:10px;
  border-radius:50%;
  background:#22c55e;
  box-shadow:0 0 0 6px rgba(34,197,94,.16);
}
 
.sidebar-footer strong{
  display:block;
  font-size:16px;
  margin-bottom:5px;
}
 
.sidebar-footer span{
  color:#94a3b8;
  font-size:12px;
  line-height:1.5;
}
 
.content{
  padding:28px;
  min-width:0;
}
 
.page{
  display:none;
  animation:fadeIn .22s ease;
}
 
.page.active{
  display:block;
}
 
@keyframes fadeIn{
  from{
    opacity:0;
    transform:translateY(8px);
  }
  to{
    opacity:1;
    transform:translateY(0);
  }
}
 
.topbar{
  display:flex;
  justify-content:space-between;
  align-items:center;
  gap:18px;
  margin-bottom:22px;
}
 
.topbar h2{
  margin:0;
  font-size:clamp(26px,3vw,38px);
  letter-spacing:-.04em;
  color:#0f172a;
}
 
.topbar p{
  margin:8px 0 0;
  color:var(--muted);
}
 
.btn{
  border:0;
  border-radius:14px;
  padding:12px 15px;
  font-weight:800;
  box-shadow:var(--shadow);
  background:white;
  color:var(--text);
  cursor:pointer;
}
 
.btn-primary{
  background:linear-gradient(135deg,var(--cyan),var(--blue));
  color:white;
}
 
.btn-dark{
  background:#0f172a;
  color:white;
}
 
.btn-success{
  background:#dcfce7;
  color:#166534;
  box-shadow:none;
}
 
.btn-danger{
  background:#fee2e2;
  color:#991b1b;
  box-shadow:none;
}
 
/* ================= FIRST DASHBOARD PAGE ================= */
 
.dashboard-hero{
  display:grid;
  grid-template-columns:360px 1fr;
  gap:22px;
  margin-bottom:22px;
}
 
.iaq-priority-card{
  min-height:420px;
  border-radius:34px;
  padding:28px;
  color:white;
  background:
    radial-gradient(circle at 80% 15%,rgba(34,211,238,.38),transparent 34%),
    linear-gradient(135deg,#0f172a,#1e3a8a);
  box-shadow:var(--shadow);
  position:relative;
  overflow:hidden;
}
 
.iaq-priority-card::after{
  content:"";
  position:absolute;
  width:220px;
  height:220px;
  border-radius:50%;
  right:-80px;
  bottom:-80px;
  background:rgba(255,255,255,.08);
}
 
.iaq-label{
  color:#bae6fd;
  font-size:13px;
  font-weight:900;
  letter-spacing:.14em;
  text-transform:uppercase;
}
 
.iaq-gauge-wrap{
  display:flex;
  justify-content:center;
  align-items:center;
  margin:26px 0 18px;
}
 
.iaq-gauge{
  width:210px;
  height:210px;
  border-radius:50%;
  display:grid;
  place-items:center;
  position:relative;
  background:conic-gradient(#16a34a 0deg,#1e293b 0deg);
  box-shadow:
    0 22px 50px rgba(0,0,0,.22),
    inset 0 0 0 1px rgba(255,255,255,.12);
}
 
.iaq-gauge::before{
  content:"";
  position:absolute;
  inset:18px;
  border-radius:50%;
  background:
    radial-gradient(circle at 30% 20%,rgba(255,255,255,.12),transparent 34%),
    #172554;
  box-shadow:inset 0 0 0 1px rgba(255,255,255,.08);
}
 
.iaq-gauge-center{
  position:relative;
  z-index:1;
  text-align:center;
}
 
.iaq-number{
  font-size:58px;
  line-height:.9;
  letter-spacing:-.08em;
  font-weight:950;
}
 
.iaq-unit{
  margin-top:6px;
  color:#bae6fd;
  font-size:13px;
  font-weight:900;
  letter-spacing:.16em;
}
 
.iaq-status-main{
  text-align:center;
  font-size:28px;
  font-weight:900;
  letter-spacing:-.04em;
  margin-bottom:12px;
}
 
.iaq-desc{
  color:#dbeafe;
  line-height:1.6;
  font-size:14px;
  max-width:280px;
  margin:0 auto;
  text-align:center;
}
 
.iaq-badge{
  display:flex;
  align-items:center;
  justify-content:center;
  gap:8px;
  margin:22px auto 0;
  width:max-content;
  padding:11px 14px;
  border-radius:999px;
  background:rgba(255,255,255,.12);
  border:1px solid rgba(255,255,255,.16);
  color:#e0f2fe;
  font-size:13px;
  font-weight:900;
}
 
.dashboard-readings-wrap{
  display:grid;
  gap:18px;
}
 
.dashboard-row{
  display:grid;
  gap:18px;
}
 
.dashboard-row.pm-row{
  grid-template-columns:repeat(3,1fr);
}
 
.dashboard-row.env-row{
  grid-template-columns:repeat(4,1fr);
}
 
.reading-tile{
  background:
    radial-gradient(circle at 92% 0%,color-mix(in srgb,var(--accent) 18%,transparent) 0 66px,transparent 68px),
    linear-gradient(180deg,rgba(255,255,255,.98),rgba(251,252,253,.94));
  border-radius:26px;
  padding:22px;
  box-shadow:0 22px 55px rgba(15,23,42,.10),inset 0 1px 0 rgba(255,255,255,.85);
  border:1px solid rgba(255,255,255,.92);
  min-height:201px;
  position:relative;
  overflow:hidden;
}
 
.tile-icon{
  width:50px;
  height:50px;
  border-radius:17px;
  display:grid;
  place-items:center;
  background:linear-gradient(180deg,rgba(255,255,255,.96),rgba(245,248,252,.90));
  color:var(--accent);
  font-weight:950;
  border:1px solid color-mix(in srgb,var(--accent) 20%,rgba(255,255,255,.8));
  box-shadow:0 10px 24px rgba(15,23,42,.08),inset 0 1px 0 rgba(255,255,255,.95);
  margin-bottom:16px;
}
 
.tile-title{
  color:#50627a;
  font-size:16px;
  font-weight:900;
  margin-bottom:10px;
}
 
.tile-value-row{
  display:flex;
  align-items:flex-end;
  gap:8px;
  flex-wrap:wrap;
}
 
.tile-value{
  font-size:42px;
  line-height:.92;
  letter-spacing:-.08em;
  color:#020617;
  font-weight:950;
}
 
.tile-unit{
  font-size:14px;
  color:#475569;
  font-weight:900;
  line-height:1.1;
  margin-bottom:4px;
  white-space:nowrap;
}
 
.tile-badge{
  display:inline-flex;
  margin-top:14px;
  padding:8px 13px;
  border-radius:999px;
  font-size:13px;
  font-weight:900;
}
 
.good{
  background:#dcfce7;
  color:#166534;
}
 
.moderate{
  background:#fef3c7;
  color:#92400e;
}
 
.danger{
  background:#fee2e2;
  color:#991b1b;
}
 
.summary-strip{
  margin-top:22px;
  display:grid;
  grid-template-columns:repeat(4,1fr);
  gap:16px;
}
 
.summary-box{
  background:white;
  border-radius:20px;
  padding:16px 18px;
  box-shadow:var(--shadow);
  border:1px solid rgba(229,231,235,.85);
}
 
.summary-box span{
  display:block;
  color:var(--muted);
  font-size:12px;
  font-weight:900;
  text-transform:uppercase;
  letter-spacing:.06em;
  margin-bottom:8px;
}
 
.summary-box strong{
  color:#0f172a;
  font-size:20px;
}
 
/* ================= ICONS ================= */
 
.pm-icon svg,
.air-icon svg{
  width:28px;
  height:28px;
  stroke:currentColor;
  stroke-width:2.35;
  fill:none;
  stroke-linecap:round;
  stroke-linejoin:round;
}
 
.wide-icon.pm-icon svg{
  width:36px;
  height:36px;
}
 
/* ================= SHARED PAGES ================= */
 
.panel{
  background:white;
  border-radius:var(--radius);
  box-shadow:var(--shadow);
  border:1px solid rgba(229,231,235,.85);
  overflow:hidden;
}
 
.panel-header{
  padding:20px 22px;
  border-bottom:1px solid var(--line);
  display:flex;
  justify-content:space-between;
  align-items:center;
  gap:14px;
  flex-wrap:wrap;
}
 
.panel-header h3{
  margin:0;
  font-size:19px;
  color:#0f172a;
}
 
.panel-header p{
  margin:5px 0 0;
  color:var(--muted);
  font-size:13px;
}
 
.pm-reading-cards,
.environment-reading-cards{
  display:grid;
  grid-template-columns:repeat(3,1fr);
  gap:24px;
  margin-bottom:22px;
  width:100%;
}
 
.environment-reading-cards{
  padding:20px;
}
 
.wide-card{
  background:
    radial-gradient(circle at 88% 0%,color-mix(in srgb,var(--accent) 20%,transparent) 0 70px,transparent 72px),
    linear-gradient(180deg,rgba(255,255,255,.98),rgba(251,252,253,.94));
  border-radius:26px;
  padding:28px 30px;
  min-height:205px;
  display:grid;
  grid-template-columns:78px 1fr auto;
  align-items:center;
  column-gap:20px;
  box-shadow:var(--shadow);
  border:1px solid rgba(255,255,255,.92);
  overflow:hidden;
}
 
.wide-icon{
  width:74px;
  height:74px;
  border-radius:24px;
  display:grid;
  place-items:center;
  background:white;
  color:var(--accent);
  font-weight:950;
  font-size:22px;
  border:1px solid color-mix(in srgb,var(--accent) 20%,rgba(255,255,255,.8));
}
 
.wide-main p{
  margin:0 0 12px;
  font-size:20px;
  color:#50627a;
  font-weight:900;
}
 
.wide-reading-row{
  display:flex;
  align-items:flex-end;
  gap:10px;
  flex-wrap:wrap;
}
 
.wide-value{
  font-size:50px;
  line-height:.92;
  letter-spacing:-.08em;
  color:#020617;
  font-weight:950;
}
 
.wide-unit{
  font-size:18px;
  color:#475569;
  font-weight:900;
  line-height:1.05;
  margin-bottom:5px;
  white-space:nowrap;
}
 
.wide-main h3{
  margin:0;
  font-size:50px;
  line-height:1;
  letter-spacing:-.08em;
  color:#020617;
}
 
.wide-main .unit{
  font-size:20px;
  color:#475569;
  font-weight:900;
  margin-left:6px;
}
 
.wide-badge{
  align-self:end;
  justify-self:end;
  padding:11px 18px;
  border-radius:999px;
  font-size:16px;
  font-weight:900;
  white-space:nowrap;
}
 
.chart{
  height:430px;
  margin:22px;
  border-radius:20px;
  border:1px solid var(--line);
  background:
    linear-gradient(to top,rgba(148,163,184,.18) 1px,transparent 1px),
    linear-gradient(to right,rgba(148,163,184,.12) 1px,transparent 1px);
  background-size:100% 72px,78px 100%;
  overflow:hidden;
}
 
.chart svg{
  width:100%;
  height:100%;
  display:block;
}
 
.legend{
  display:flex;
  gap:14px;
  flex-wrap:wrap;
  padding:0 22px 22px;
}
 
.legend span{
  display:flex;
  align-items:center;
  gap:8px;
  color:var(--muted);
  font-weight:800;
  font-size:13px;
}
 
.legend i{
  width:10px;
  height:10px;
  border-radius:50%;
  background:var(--c);
}
 
.range-controls{
  display:flex;
  gap:8px;
  flex-wrap:wrap;
}
 
.range-btn{
  border:1px solid var(--line);
  background:white;
  color:#475569;
  padding:9px 12px;
  border-radius:999px;
  font-size:12px;
  font-weight:900;
  cursor:pointer;
}
 
.range-btn.active,
.range-btn:hover{
  background:linear-gradient(135deg,var(--cyan),var(--blue));
  color:white;
  border-color:transparent;
}
 
.interactive-chart{
  position:relative;
}
 
.chart-tooltip{
  position:absolute;
  min-width:178px;
  padding:12px 13px;
  border-radius:14px;
  background:#0f172a;
  color:white;
  box-shadow:0 18px 40px rgba(15,23,42,.26);
  pointer-events:none;
  opacity:0;
  transform:translate(-50%,-110%);
  z-index:5;
  font-size:12px;
}
 
.chart-tooltip.show{
  opacity:1;
}
 
.chart-tooltip strong{
  display:block;
  font-size:13px;
  margin-bottom:8px;
  color:#e0f2fe;
}
 
.tooltip-row{
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:18px;
  margin:5px 0;
}
 
.tooltip-label{
  display:inline-flex;
  align-items:center;
  gap:6px;
  color:#cbd5e1;
}
 
.tooltip-dot{
  width:8px;
  height:8px;
  border-radius:50%;
  background:var(--dot);
}
 
.hover-line{
  stroke:#0f172a;
  stroke-width:1.5;
  stroke-dasharray:5 5;
  opacity:0;
  pointer-events:none;
}
 
.hover-point{
  opacity:0;
  pointer-events:none;
  stroke:white;
  stroke-width:3;
}
 
.interactive-chart.active-hover .hover-line,
.interactive-chart.active-hover .hover-point{
  opacity:1;
}
 
.comfort{
  padding:26px;
}
 
.comfort-layout{
  display:grid;
  grid-template-columns:320px 1fr;
  gap:24px;
  align-items:center;
}
 
.comfort-left{
  display:flex;
  flex-direction:column;
  align-items:center;
  justify-content:center;
  text-align:center;
  padding:6px 10px;
}
 
.comfort-meter{
  width:200px;
  height:200px;
  margin:0 0 20px;
  border-radius:50%;
  display:grid;
  place-items:center;
  background:conic-gradient(#16a34a 0 260deg,#e5e7eb 260deg 360deg);
  position:relative;
}
 
.comfort-meter::before{
  content:"";
  position:absolute;
  inset:16px;
  background:white;
  border-radius:50%;
}
 
.comfort-meter strong{
  position:relative;
  z-index:1;
  font-size:44px;
  letter-spacing:-.05em;
}
 
.comfort h4{
  text-align:center;
  margin:0 0 10px;
  font-size:23px;
}
 
.comfort p{
  text-align:center;
  margin:0;
  color:var(--muted);
  line-height:1.6;
  font-size:15px;
  max-width:260px;
}
 
.mini-grid{
  display:grid;
  grid-template-columns:1fr 1fr;
  gap:16px;
}
 
.mini{
  min-height:112px;
  padding:18px;
  border-radius:18px;
  background:#f8fafc;
  border:1px solid var(--line);
  display:flex;
  flex-direction:column;
  justify-content:center;
}
 
.mini span{
  color:var(--muted);
  font-size:12px;
  font-weight:900;
}
 
.mini strong{
  display:block;
  margin-top:10px;
  font-size:24px;
  color:#0f172a;
}
 
.table-wrap{
  overflow-x:auto;
}
 
table{
  width:100%;
  border-collapse:collapse;
  min-width:820px;
}
 
th,td{
  padding:15px 22px;
  text-align:left;
  border-bottom:1px solid var(--line);
  font-size:14px;
}
 
th{
  background:#f8fafc;
  color:var(--muted);
  font-size:11px;
  text-transform:uppercase;
  letter-spacing:.08em;
}
 
.logger-toolbar{
  display:grid;
  grid-template-columns:repeat(4,minmax(160px,1fr));
  gap:14px;
  padding:20px;
  border-bottom:1px solid var(--line);
  background:#f8fafc;
}
 
.logger-control{
  background:white;
  border:1px solid var(--line);
  border-radius:18px;
  padding:14px;
}
 
.logger-control span{
  display:block;
  color:var(--muted);
  font-size:12px;
  font-weight:900;
  margin-bottom:8px;
}
 
.logger-control select,
.logger-control input{
  width:100%;
  box-shadow:none;
  border:1px solid var(--line);
  padding:10px;
  border-radius:12px;
  background:white;
  font-weight:800;
}
 
.logger-actions{
  display:flex;
  gap:10px;
  flex-wrap:wrap;
}
 
.logger-status{
  display:inline-flex;
  align-items:center;
  gap:8px;
  padding:9px 12px;
  border-radius:999px;
  font-size:13px;
  font-weight:900;
  background:#fee2e2;
  color:#991b1b;
}
 
.logger-status.running{
  background:#dcfce7;
  color:#166534;
}
 
.logger-dot{
  width:9px;
  height:9px;
  border-radius:50%;
  background:currentColor;
}
 
/* ================= ALERTS PAGE ================= */
 
.alert-dashboard-grid{
  display:grid;
  grid-template-columns:1.1fr .9fr;
  gap:20px;
}
 
.alerts{
  display:grid;
  gap:14px;
  padding:20px;
}
 
.alert{
  display:grid;
  grid-template-columns:46px 1fr auto;
  gap:14px;
  padding:16px;
  border-radius:20px;
  background:#f8fafc;
  border:1px solid var(--line);
  align-items:center;
}
 
.alert-icon{
  width:46px;
  height:46px;
  border-radius:16px;
  display:grid;
  place-items:center;
  background:#fef3c7;
  color:#92400e;
  font-size:20px;
}
 
.alert strong{
  display:block;
  margin-bottom:4px;
  color:#0f172a;
}
 
.alert span{
  color:var(--muted);
  font-size:13px;
  line-height:1.5;
}
 
.alert-level{
  padding:8px 12px;
  border-radius:999px;
  font-size:12px;
  font-weight:900;
  white-space:nowrap;
}
 
.level-info{
  background:#dbeafe;
  color:#1d4ed8;
}
 
.level-warning{
  background:#fef3c7;
  color:#92400e;
}
 
.level-danger{
  background:#fee2e2;
  color:#991b1b;
}
 
.level-good{
  background:#dcfce7;
  color:#166534;
}
 
.alert-settings{
  padding:20px;
  display:grid;
  gap:14px;
}
 
.settings-grid{
  display:grid;
  grid-template-columns:1fr 1fr;
  gap:14px;
}
 
.setting-card{
  padding:14px;
  border-radius:18px;
  background:#f8fafc;
  border:1px solid var(--line);
}
 
.setting-card label{
  display:block;
  color:#475569;
  font-size:12px;
  font-weight:900;
  margin-bottom:8px;
}
 
.setting-card input{
  width:100%;
  border:1px solid var(--line);
  border-radius:12px;
  padding:10px;
  font-size:14px;
  font-weight:800;
  outline:none;
}
 
.alert-summary{
  display:grid;
  grid-template-columns:repeat(3,1fr);
  gap:14px;
  margin-bottom:20px;
}
 
.alert-metric{
  background:white;
  border:1px solid var(--line);
  box-shadow:var(--shadow);
  border-radius:22px;
  padding:18px;
}
 
.alert-metric span{
  color:var(--muted);
  font-size:12px;
  font-weight:900;
  text-transform:uppercase;
  letter-spacing:.06em;
}
 
.alert-metric strong{
  display:block;
  margin-top:8px;
  font-size:26px;
  color:#0f172a;
}
 
@media(max-width:1250px){
  .dashboard-hero{
    grid-template-columns:1fr;
  }
 
  .dashboard-row.pm-row,
  .dashboard-row.env-row{
    grid-template-columns:repeat(2,1fr);
  }
 
  .summary-strip,
  .alert-summary{
    grid-template-columns:repeat(2,1fr);
  }
 
  .pm-reading-cards,
  .environment-reading-cards{
    grid-template-columns:1fr;
  }
 
  .wide-card{
    grid-template-columns:70px 1fr;
    row-gap:16px;
  }
 
  .wide-badge{
    grid-column:1/-1;
    justify-self:start;
  }
 
  .comfort-layout{
    grid-template-columns:1fr;
  }
 
  .logger-toolbar,
  .settings-grid{
    grid-template-columns:repeat(2,1fr);
  }
 
  .alert-dashboard-grid{
    grid-template-columns:1fr;
  }
}
 
@media(max-width:900px){
  .app{
    grid-template-columns:1fr;
  }
 
  .sidebar{
    position:static;
    height:auto;
  }
 
  .sidebar-footer{
    position:static;
    margin-top:24px;
  }
 
  .topbar{
    align-items:flex-start;
    flex-direction:column;
  }
}
 
@media(max-width:620px){
  .content{
    padding:18px;
  }
 
  .dashboard-row.pm-row,
  .dashboard-row.env-row,
  .summary-strip,
  .mini-grid,
  .logger-toolbar,
  .settings-grid,
  .alert-summary{
    grid-template-columns:1fr;
  }
 
  .iaq-gauge{
    width:190px;
    height:190px;
  }
 
  .iaq-number{
    font-size:52px;
  }
 
  .tile-value{
    font-size:38px;
  }
 
  .wide-value{
    font-size:42px;
  }
 
  .alert{
    grid-template-columns:46px 1fr;
  }
 
  .alert-level{
    grid-column:1/-1;
    justify-self:start;
  }
}
</style>
</head>
 
<body>
<div class="app">
 
<aside class="sidebar">
  <div class="brand">
    <div class="brand-icon">◌</div>
    <div>
      <h1>AeroSense IoT</h1>
      <p>PM & air quality monitor</p>
    </div>
  </div>
 
  <div class="nav-title">Pages</div>
  <nav class="nav">
    <button class="active" onclick="showPage('dashboard',this)">🌫 Dashboard</button>
    <button onclick="showPage('pm',this)">📊 PM Readings</button>
    <button onclick="showPage('environment',this)">🌡 Environment</button>
    <button onclick="showPage('history',this)">🕒 History</button>
    <button onclick="showPage('alerts',this)">⚠ Alerts</button>
  </nav>
 
  <div class="sidebar-footer">
    <div class="online"><span class="dot"></span> Device Online</div>
    <strong>AQ-MONITOR-01</strong>
    <span>ESP32 · PMS7003 · BME680<br>IP: <span id="deviceIp">--</span></span>
  </div>
</aside>
 
<main class="content">
 
<section id="page-dashboard" class="page active">
  <header class="topbar">
    <div>
      <h2>PM & Air Quality Monitoring</h2>
    </div>
    <button class="btn btn-primary" onclick="fetchReadings()">Refresh Data</button>
  </header>
 
  <div class="dashboard-hero">
    <div class="iaq-priority-card">
      <div class="iaq-label">Indoor Air Quality</div>
 
      <div class="iaq-gauge-wrap">
        <div class="iaq-gauge" id="iaqGauge">
          <div class="iaq-gauge-center">
            <div class="iaq-number" id="aqiValue">--</div>
            <div class="iaq-unit">IAQ</div>
          </div>
        </div>
      </div>
 
      <div class="iaq-status-main" id="aqiLabel">Loading...</div>
      <div class="iaq-desc" id="aqiMessage">Waiting for ESP32 sensor readings.</div>
      <div class="iaq-badge" id="aqiStatus">● Connecting</div>
    </div>
 
    <div class="dashboard-readings-wrap">
      <div class="dashboard-row pm-row">
        <div class="reading-tile" style="--accent:#22c55e">
          <div class="tile-icon pm-icon">
            <svg viewBox="0 0 24 24">
              <path d="M4 8c1.5-1.4 3-1.4 4.5 0s3 1.4 4.5 0 3-1.4 4.5 0"/>
              <path d="M4 12c1.5-1.4 3-1.4 4.5 0s3 1.4 4.5 0 3-1.4 4.5 0"/>
              <path d="M4 16c1.5-1.4 3-1.4 4.5 0s3 1.4 4.5 0 3-1.4 4.5 0"/>
            </svg>
          </div>
          <div class="tile-title">PM1.0</div>
          <div class="tile-value-row">
            <div class="tile-value" id="dashPm1">--</div>
            <div class="tile-unit">µg/m³</div>
          </div>
          <div class="tile-badge good">Fine</div>
        </div>
 
        <div class="reading-tile" style="--accent:#f97316">
          <div class="tile-icon pm-icon">
            <svg viewBox="0 0 24 24">
              <path d="M4 8c1.5-1.4 3-1.4 4.5 0s3 1.4 4.5 0 3-1.4 4.5 0"/>
              <path d="M4 12c1.5-1.4 3-1.4 4.5 0s3 1.4 4.5 0 3-1.4 4.5 0"/>
              <path d="M4 16c1.5-1.4 3-1.4 4.5 0s3 1.4 4.5 0 3-1.4 4.5 0"/>
            </svg>
          </div>
          <div class="tile-title">PM2.5</div>
          <div class="tile-value-row">
            <div class="tile-value" id="dashPm25">--</div>
            <div class="tile-unit">µg/m³</div>
          </div>
          <div class="tile-badge moderate" id="pm25Status">--</div>
        </div>
 
        <div class="reading-tile" style="--accent:#ef4444">
          <div class="tile-icon pm-icon">
            <svg viewBox="0 0 24 24">
              <path d="M4 8c1.5-1.4 3-1.4 4.5 0s3 1.4 4.5 0 3-1.4 4.5 0"/>
              <path d="M4 12c1.5-1.4 3-1.4 4.5 0s3 1.4 4.5 0 3-1.4 4.5 0"/>
              <path d="M4 16c1.5-1.4 3-1.4 4.5 0s3 1.4 4.5 0 3-1.4 4.5 0"/>
            </svg>
          </div>
          <div class="tile-title">PM10</div>
          <div class="tile-value-row">
            <div class="tile-value" id="dashPm10">--</div>
            <div class="tile-unit">µg/m³</div>
          </div>
          <div class="tile-badge danger">Dust</div>
        </div>
      </div>
 
      <div class="dashboard-row env-row">
        <div class="reading-tile" style="--accent:#f97316">
          <div class="tile-icon">°C</div>
          <div class="tile-title">Temp</div>
          <div class="tile-value-row">
            <div class="tile-value" id="dashTemp">--</div>
            <div class="tile-unit">°C</div>
          </div>
          <div class="tile-badge good">Stable</div>
        </div>
 
        <div class="reading-tile" style="--accent:#16a34a">
          <div class="tile-icon">%</div>
          <div class="tile-title">Hum</div>
          <div class="tile-value-row">
            <div class="tile-value" id="dashHum">--</div>
            <div class="tile-unit">%</div>
          </div>
          <div class="tile-badge good">Comfort</div>
        </div>
 
        <div class="reading-tile" style="--accent:#0ea5e9">
          <div class="tile-icon">CO2</div>
          <div class="tile-title">CO2</div>
          <div class="tile-value-row">
            <div class="tile-value" id="dashCo2">--</div>
            <div class="tile-unit">ppm</div>
          </div>
          <div class="tile-badge good">BSEC</div>
        </div>
 
        <div class="reading-tile" style="--accent:#14b8a6">
          <div class="tile-icon">VOC</div>
          <div class="tile-title">VOC</div>
          <div class="tile-value-row">
            <div class="tile-value" id="dashVoc">--</div>
            <div class="tile-unit">ppm</div>
          </div>
          <div class="tile-badge good">BSEC</div>
        </div>
      </div>
    </div>
  </div>
 
  <div class="summary-strip">
    <div class="summary-box">
      <span>Device</span>
      <strong id="deviceState">Online</strong>
    </div>
    <div class="summary-box">
      <span>PMS7003</span>
      <strong>Active</strong>
    </div>
    <div class="summary-box">
      <span>BME680</span>
      <strong id="calState">--</strong>
    </div>
    <div class="summary-box">
      <span>Last Update</span>
      <strong id="lastUpdate">--</strong>
    </div>
  </div>
</section>
 
<section id="page-pm" class="page">
  <header class="topbar">
    <div>
      <h2>PM Readings</h2>
      <p>Live PMS7003 readings with trend graph.</p>
    </div>
    <button class="btn btn-primary" onclick="fetchReadings()">Refresh PM Data</button>
  </header>
 
  <div class="pm-reading-cards">
    <div class="wide-card" style="--accent:#22c55e">
      <div class="wide-icon pm-icon">
        <svg viewBox="0 0 24 24">
          <path d="M4 8c1.5-1.4 3-1.4 4.5 0s3 1.4 4.5 0 3-1.4 4.5 0"/>
          <path d="M4 12c1.5-1.4 3-1.4 4.5 0s3 1.4 4.5 0 3-1.4 4.5 0"/>
          <path d="M4 16c1.5-1.4 3-1.4 4.5 0s3 1.4 4.5 0 3-1.4 4.5 0"/>
        </svg>
      </div>
      <div class="wide-main">
        <p>PM1.0</p>
        <div class="wide-reading-row">
          <div class="wide-value" id="pm1PageValue">--</div>
          <div class="wide-unit">µg/m³</div>
        </div>
      </div>
      <span class="wide-badge good">Fine particles</span>
    </div>
 
    <div class="wide-card" style="--accent:#f97316">
      <div class="wide-icon pm-icon">
        <svg viewBox="0 0 24 24">
          <path d="M4 8c1.5-1.4 3-1.4 4.5 0s3 1.4 4.5 0 3-1.4 4.5 0"/>
          <path d="M4 12c1.5-1.4 3-1.4 4.5 0s3 1.4 4.5 0 3-1.4 4.5 0"/>
          <path d="M4 16c1.5-1.4 3-1.4 4.5 0s3 1.4 4.5 0 3-1.4 4.5 0"/>
        </svg>
      </div>
      <div class="wide-main">
        <p>PM2.5</p>
        <div class="wide-reading-row">
          <div class="wide-value" id="pm25PageValue">--</div>
          <div class="wide-unit">µg/m³</div>
        </div>
      </div>
      <span class="wide-badge moderate">Moderate</span>
    </div>
 
    <div class="wide-card" style="--accent:#ef4444">
      <div class="wide-icon pm-icon">
        <svg viewBox="0 0 24 24">
          <path d="M4 8c1.5-1.4 3-1.4 4.5 0s3 1.4 4.5 0 3-1.4 4.5 0"/>
          <path d="M4 12c1.5-1.4 3-1.4 4.5 0s3 1.4 4.5 0 3-1.4 4.5 0"/>
          <path d="M4 16c1.5-1.4 3-1.4 4.5 0s3 1.4 4.5 0 3-1.4 4.5 0"/>
        </svg>
      </div>
      <div class="wide-main">
        <p>PM10</p>
        <div class="wide-reading-row">
          <div class="wide-value" id="pm10PageValue">--</div>
          <div class="wide-unit">µg/m³</div>
        </div>
      </div>
      <span class="wide-badge danger">Dust level</span>
    </div>
  </div>
 
  <div class="panel">
    <div class="panel-header">
      <div>
        <h3>Particle Matter Trend</h3>
        <p>Hover to see PM values.</p>
      </div>
      <div class="range-controls">
        <button class="range-btn active" onclick="setPmRange('15m',this)">15 min</button>
        <button class="range-btn" onclick="setPmRange('1h',this)">1 hour</button>
        <button class="range-btn" onclick="setPmRange('3h',this)">3 hours</button>
        <button class="range-btn" onclick="setPmRange('6h',this)">6 hours</button>
        <button class="range-btn" onclick="setPmRange('12h',this)">12 hours</button>
        <button class="range-btn" onclick="setPmRange('24h',this)">24 hours</button>
      </div>
    </div>
 
    <div class="chart interactive-chart" id="pmChart">
      <div class="chart-tooltip" id="pmTooltip"></div>
      <svg viewBox="0 0 900 430" preserveAspectRatio="none" id="pmSvg">
        <defs>
          <linearGradient id="pm25Fill" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stop-color="#f97316" stop-opacity=".30"/>
            <stop offset="100%" stop-color="#f97316" stop-opacity="0"/>
          </linearGradient>
          <linearGradient id="pm10Fill" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stop-color="#ef4444" stop-opacity=".24"/>
            <stop offset="100%" stop-color="#ef4444" stop-opacity="0"/>
          </linearGradient>
        </defs>
 
        <path id="pm25Area" fill="url(#pm25Fill)"/>
        <path id="pm10Area" fill="url(#pm10Fill)"/>
 
        <path id="pm1Line" fill="none" stroke="#22c55e" stroke-width="5" stroke-linecap="round"/>
        <path id="pm25Line" fill="none" stroke="#f97316" stroke-width="5" stroke-linecap="round"/>
        <path id="pm10Line" fill="none" stroke="#ef4444" stroke-width="5" stroke-linecap="round"/>
 
        <line id="hoverLine" class="hover-line" y1="24" y2="406"/>
        <circle id="hoverPm1" class="hover-point" r="6" fill="#22c55e"/>
        <circle id="hoverPm25" class="hover-point" r="6" fill="#f97316"/>
        <circle id="hoverPm10" class="hover-point" r="6" fill="#ef4444"/>
      </svg>
    </div>
 
    <div class="legend">
      <span><i style="--c:#22c55e"></i> PM1.0</span>
      <span><i style="--c:#f97316"></i> PM2.5</span>
      <span><i style="--c:#ef4444"></i> PM10</span>
    </div>
  </div>
</section>
 
<section id="page-environment" class="page">
  <header class="topbar">
    <div>
      <h2>Environment</h2>
      <p>BME680 final readings from BSEC.</p>
    </div>
    <button class="btn btn-primary" onclick="fetchReadings()">Refresh Environment</button>
  </header>
 
  <div class="panel">
    <div class="panel-header">
      <div>
        <h3>BME680 Air Quality Data</h3>
        <p>Temperature, humidity, IAQ, CO2 and VOC.</p>
      </div>
    </div>
 
    <div class="environment-reading-cards">
      <div class="wide-card" style="--accent:#f97316">
        <div class="wide-icon">°C</div>
        <div class="wide-main">
          <p>Temperature</p>
          <h3 id="envTemp">--<span class="unit">°C</span></h3>
        </div>
        <span class="wide-badge good">Stable</span>
      </div>
 
      <div class="wide-card" style="--accent:#16a34a">
        <div class="wide-icon">%</div>
        <div class="wide-main">
          <p>Humidity</p>
          <h3 id="envHumidity">--<span class="unit">%</span></h3>
        </div>
        <span class="wide-badge good">Comfort</span>
      </div>
 
      <div class="wide-card" style="--accent:#0ea5e9">
        <div class="wide-icon">IAQ</div>
        <div class="wide-main">
          <p>IAQ</p>
          <h3 id="envIaq">--</h3>
        </div>
        <span class="wide-badge moderate" id="envAccuracy">--</span>
      </div>
    </div>
  </div>
 
  <div class="panel" style="margin-top:20px">
    <div class="comfort">
      <div class="comfort-layout">
        <div class="comfort-left">
          <div class="comfort-meter">
            <strong id="comfortScore">--</strong>
          </div>
          <h4 id="comfortLabel">Loading</h4>
          <p id="comfortText">Waiting for BME680 readings.</p>
        </div>
 
        <div class="mini-grid">
          <div class="mini"><span>CO2 EQUIVALENT</span><strong id="co2Mini">-- ppm</strong></div>
          <div class="mini"><span>VOC EQUIVALENT</span><strong id="vocMini">-- ppm</strong></div>
          <div class="mini"><span>CALIBRATION</span><strong id="calMini">--</strong></div>
          <div class="mini"><span>UPTIME</span><strong id="uptimeMini">--</strong></div>
        </div>
      </div>
    </div>
  </div>
</section>
 
<section id="page-history" class="page">
  <header class="topbar">
    <div>
      <h2>History & Data Logger</h2>
      <p>Log readings and export as Excel.</p>
    </div>
    <div>
      <button class="btn btn-primary" onclick="addLog()">Add Log</button>
      <button class="btn btn-dark" onclick="exportExcel()">Export Excel</button>
    </div>
  </header>
 
  <div class="panel">
    <div class="panel-header">
      <div>
        <h3>Data Logger Controls</h3>
        <p>Start automatic logging, choose interval, clear logs, or download records.</p>
      </div>
      <div id="loggerStatus" class="logger-status">
        <span class="logger-dot"></span> Logger Stopped
      </div>
    </div>
 
    <div class="logger-toolbar">
      <div class="logger-control">
        <span>Logging Interval</span>
        <select id="loggingInterval">
          <option value="2000">Every 2 seconds</option>
          <option value="5000" selected>Every 5 seconds</option>
          <option value="10000">Every 10 seconds</option>
          <option value="30000">Every 30 seconds</option>
          <option value="60000">Every 1 minute</option>
        </select>
      </div>
 
      <div class="logger-control">
        <span>Total Records</span>
        <strong id="recordCount">0</strong>
      </div>
 
      <div class="logger-control">
        <span>File Name</span>
        <input id="exportFileName" type="text" value="air_quality_log">
      </div>
 
      <div class="logger-control">
        <span>Actions</span>
        <div class="logger-actions">
          <button class="btn btn-success" onclick="startLogger()">Start</button>
          <button class="btn btn-danger" onclick="stopLogger()">Stop</button>
          <button class="btn" onclick="clearLogs()">Clear</button>
        </div>
      </div>
    </div>
 
    <div class="table-wrap">
      <table>
        <thead>
          <tr>
            <th>Time</th>
            <th>PM1.0</th>
            <th>PM2.5</th>
            <th>PM10</th>
            <th>Temp</th>
            <th>Humidity</th>
            <th>IAQ</th>
            <th>CO2</th>
            <th>VOC</th>
            <th>Accuracy</th>
          </tr>
        </thead>
        <tbody id="logBody"></tbody>
      </table>
    </div>
  </div>
</section>
 
<section id="page-alerts" class="page">
  <header class="topbar">
    <div>
      <h2>Alerts & Settings</h2>
      <p>Live safety warnings with adjustable threshold settings.</p>
    </div>
    <button class="btn btn-primary" onclick="saveAlertSettings()">Save Alert Settings</button>
  </header>
 
  <div class="alert-summary">
    <div class="alert-metric">
      <span>Active Alerts</span>
      <strong id="activeAlertCount">0</strong>
    </div>
    <div class="alert-metric">
      <span>Highest Level</span>
      <strong id="highestAlertLevel">Normal</strong>
    </div>
    <div class="alert-metric">
      <span>Last Check</span>
      <strong id="alertLastCheck">--</strong>
    </div>
  </div>
 
  <div class="alert-dashboard-grid">
    <div class="panel">
      <div class="panel-header">
        <div>
          <h3>Smart Air Quality Alerts</h3>
          <p>Generated from PM, IAQ, CO2, VOC, temperature, humidity, calibration and device status.</p>
        </div>
      </div>
 
      <div class="alerts" id="alertsBox">
        <div class="alert">
          <div class="alert-icon">📡</div>
          <div>
            <strong>Waiting for data</strong>
            <span>Dashboard is connecting to ESP32.</span>
          </div>
          <div class="alert-level level-info">Info</div>
        </div>
      </div>
    </div>
 
    <div class="panel">
      <div class="panel-header">
        <div>
          <h3>Alert Threshold Settings</h3>
          <p>Change these values to control when alerts appear.</p>
        </div>
      </div>
 
      <div class="alert-settings">
        <div class="settings-grid">
          <div class="setting-card">
            <label>PM2.5 warning</label>
            <input id="setPm25Warn" type="number" value="35">
          </div>
 
          <div class="setting-card">
            <label>PM2.5 danger</label>
            <input id="setPm25Danger" type="number" value="55">
          </div>
 
          <div class="setting-card">
            <label>PM10 warning</label>
            <input id="setPm10Warn" type="number" value="80">
          </div>
 
          <div class="setting-card">
            <label>PM10 danger</label>
            <input id="setPm10Danger" type="number" value="150">
          </div>
 
          <div class="setting-card">
            <label>IAQ warning</label>
            <input id="setIaqWarn" type="number" value="100">
          </div>
 
          <div class="setting-card">
            <label>IAQ danger</label>
            <input id="setIaqDanger" type="number" value="200">
          </div>
 
          <div class="setting-card">
            <label>CO2 warning ppm</label>
            <input id="setCo2Warn" type="number" value="1000">
          </div>
 
          <div class="setting-card">
            <label>CO2 danger ppm</label>
            <input id="setCo2Danger" type="number" value="2000">
          </div>
 
          <div class="setting-card">
            <label>VOC warning ppm</label>
            <input id="setVocWarn" type="number" step="0.01" value="1.00">
          </div>
 
          <div class="setting-card">
            <label>VOC danger ppm</label>
            <input id="setVocDanger" type="number" step="0.01" value="2.00">
          </div>
 
          <div class="setting-card">
            <label>Min comfort humidity %</label>
            <input id="setHumMin" type="number" value="30">
          </div>
 
          <div class="setting-card">
            <label>Max comfort humidity %</label>
            <input id="setHumMax" type="number" value="70">
          </div>
 
          <div class="setting-card">
            <label>Min comfort temp °C</label>
            <input id="setTempMin" type="number" value="18">
          </div>
 
          <div class="setting-card">
            <label>Max comfort temp °C</label>
            <input id="setTempMax" type="number" value="32">
          </div>
        </div>
 
        <button class="btn btn-dark" onclick="resetAlertSettings()">Reset Defaults</button>
      </div>
    </div>
  </div>
</section>
 
</main>
</div>
 
<script>
let latest=null;
let loggerTimer=null;
let pmHistory=[];
 
const defaultAlertSettings={
  pm25Warn:35,
  pm25Danger:55,
  pm10Warn:80,
  pm10Danger:150,
  iaqWarn:100,
  iaqDanger:200,
  co2Warn:1000,
  co2Danger:2000,
  vocWarn:1.00,
  vocDanger:2.00,
  humMin:30,
  humMax:70,
  tempMin:18,
  tempMax:32
};
 
let alertSettings={...defaultAlertSettings};
 
function showPage(page,button){
  document.querySelectorAll(".page").forEach(s=>s.classList.remove("active"));
  document.getElementById("page-"+page).classList.add("active");
 
  document.querySelectorAll(".nav button").forEach(x=>x.classList.remove("active"));
  button.classList.add("active");
}
 
function cls(status){
  return status==="Good" ? "good" :
         status==="Unhealthy" || status==="Very Unhealthy" || status==="Hazardous" ? "danger" :
         "moderate";
}
 
function setHTML(id,value){
  const e=document.getElementById(id);
  if(e)e.innerHTML=value;
}
 
function setText(id,value){
  const e=document.getElementById(id);
  if(e)e.textContent=value;
}
 
function pm25Status(v){
  if(v<=12)return "Good";
  if(v<=35)return "Moderate";
  if(v<=55)return "Poor";
  return "Unhealthy";
}
 
function getIaqColor(iaq){
  if(iaq<=50)return "#16a34a";
  if(iaq<=100)return "#84cc16";
  if(iaq<=150)return "#eab308";
  if(iaq<=200)return "#f97316";
  if(iaq<=300)return "#ef4444";
  return "#991b1b";
}
 
function updateIaqGauge(iaq){
  const gauge=document.getElementById("iaqGauge");
  if(!gauge)return;
 
  const value=Math.max(0,Math.min(500,Number(iaq)));
  const degrees=(value/500)*360;
  const color=getIaqColor(value);
 
  gauge.style.background=`conic-gradient(${color} 0deg ${degrees}deg, rgba(255,255,255,.16) ${degrees}deg 360deg)`;
  gauge.style.boxShadow=`0 22px 50px rgba(0,0,0,.22), 0 0 34px ${color}55, inset 0 0 0 1px rgba(255,255,255,.12)`;
}
 
function updateUI(d){
  latest=d;
 
  const status=d.status || "Loading";
  const now=new Date().toLocaleTimeString([],{
    hour:"2-digit",
    minute:"2-digit",
    second:"2-digit"
  });
 
  setText("dashPm1",d.pm1);
  setText("dashPm25",d.pm25);
  setText("dashPm10",d.pm10);
  setText("dashTemp",Number(d.temperature).toFixed(1));
  setText("dashHum",Number(d.humidity).toFixed(0));
  setText("dashCo2",Number(d.co2).toFixed(0));
  setText("dashVoc",Number(d.voc).toFixed(2));
 
  setText("pm1PageValue",d.pm1);
  setText("pm25PageValue",d.pm25);
  setText("pm10PageValue",d.pm10);
 
  setHTML("envTemp",`${Number(d.temperature).toFixed(1)}<span class="unit">°C</span>`);
  setHTML("envHumidity",`${Number(d.humidity).toFixed(1)}<span class="unit">%</span>`);
  setHTML("envIaq",`${Number(d.iaq).toFixed(0)}`);
 
  setText("aqiValue",Number(d.iaq).toFixed(0));
  setText("aqiLabel",`${status} Air Quality`);
  setText("aqiStatus",`● Current status: ${status}`);
 
  updateIaqGauge(d.iaq);
 
  if(d.calibrating){
    setText("aqiMessage","BME680 is calibrating. IAQ, CO2, and VOC will improve after calibration.");
  }else{
    setText("aqiMessage","Live IAQ reading from BME680 BSEC output.");
  }
 
  const pms=pm25Status(Number(d.pm25));
  const pmBadge=document.getElementById("pm25Status");
  if(pmBadge){
    pmBadge.className="tile-badge "+cls(pms);
    pmBadge.textContent=pms;
  }
 
  setText("deviceIp",d.ip || "--");
  setText("lastUpdate",now);
  setText("deviceState","Online");
  setText("calState",d.iaqAccuracyText || "--");
  setText("envAccuracy",d.iaqAccuracyText || "--");
 
  setText("co2Mini",`${Number(d.co2).toFixed(0)} ppm`);
  setText("vocMini",`${Number(d.voc).toFixed(2)} ppm`);
  setText("calMini",d.iaqAccuracyText || "--");
  setText("uptimeMini",`${d.uptime}s`);
 
  const comfort=Math.max(
    45,
    Math.min(
      96,
      100-Math.abs(d.temperature-25)*5-Math.abs(d.humidity-50)*.6
    )
  );
 
  setText("comfortScore",Math.round(comfort)+"%");
  setText("comfortLabel",comfort>75 ? "Very Comfortable" : comfort>60 ? "Comfortable" : "Needs Improvement");
 
  if(d.calibrating){
    setText("comfortText","Sensor calibration is in progress.");
  }else{
    setText("comfortText","Temperature and humidity are within measured range.");
  }
 
  updateAlerts(d);
  pushPmHistory(d);
  renderPmChart();
}
 
function getAlertSettingsFromInputs(){
  alertSettings={
    pm25Warn:Number(document.getElementById("setPm25Warn").value),
    pm25Danger:Number(document.getElementById("setPm25Danger").value),
    pm10Warn:Number(document.getElementById("setPm10Warn").value),
    pm10Danger:Number(document.getElementById("setPm10Danger").value),
    iaqWarn:Number(document.getElementById("setIaqWarn").value),
    iaqDanger:Number(document.getElementById("setIaqDanger").value),
    co2Warn:Number(document.getElementById("setCo2Warn").value),
    co2Danger:Number(document.getElementById("setCo2Danger").value),
    vocWarn:Number(document.getElementById("setVocWarn").value),
    vocDanger:Number(document.getElementById("setVocDanger").value),
    humMin:Number(document.getElementById("setHumMin").value),
    humMax:Number(document.getElementById("setHumMax").value),
    tempMin:Number(document.getElementById("setTempMin").value),
    tempMax:Number(document.getElementById("setTempMax").value)
  };
}
 
function loadAlertSettings(){
  const saved=localStorage.getItem("aerosense_alert_settings");
  if(saved){
    try{
      alertSettings={...defaultAlertSettings,...JSON.parse(saved)};
    }catch(e){
      alertSettings={...defaultAlertSettings};
    }
  }
 
  document.getElementById("setPm25Warn").value=alertSettings.pm25Warn;
  document.getElementById("setPm25Danger").value=alertSettings.pm25Danger;
  document.getElementById("setPm10Warn").value=alertSettings.pm10Warn;
  document.getElementById("setPm10Danger").value=alertSettings.pm10Danger;
  document.getElementById("setIaqWarn").value=alertSettings.iaqWarn;
  document.getElementById("setIaqDanger").value=alertSettings.iaqDanger;
  document.getElementById("setCo2Warn").value=alertSettings.co2Warn;
  document.getElementById("setCo2Danger").value=alertSettings.co2Danger;
  document.getElementById("setVocWarn").value=alertSettings.vocWarn;
  document.getElementById("setVocDanger").value=alertSettings.vocDanger;
  document.getElementById("setHumMin").value=alertSettings.humMin;
  document.getElementById("setHumMax").value=alertSettings.humMax;
  document.getElementById("setTempMin").value=alertSettings.tempMin;
  document.getElementById("setTempMax").value=alertSettings.tempMax;
}
 
function saveAlertSettings(){
  getAlertSettingsFromInputs();
  localStorage.setItem("aerosense_alert_settings",JSON.stringify(alertSettings));
  if(latest) updateAlerts(latest);
  alert("Alert settings saved.");
}
 
function resetAlertSettings(){
  alertSettings={...defaultAlertSettings};
  localStorage.removeItem("aerosense_alert_settings");
  loadAlertSettings();
  if(latest) updateAlerts(latest);
}
 
function makeAlert(icon,title,message,level){
  const levelClass=level==="Danger" ? "level-danger" :
                   level==="Warning" ? "level-warning" :
                   level==="Good" ? "level-good" :
                   "level-info";
 
  return `
    <div class="alert">
      <div class="alert-icon">${icon}</div>
      <div>
        <strong>${title}</strong>
        <span>${message}</span>
      </div>
      <div class="alert-level ${levelClass}">${level}</div>
    </div>
  `;
}
 
function updateAlerts(d){
  getAlertSettingsFromInputs();
 
  let h="";
  let count=0;
  let highest="Normal";
 
  function add(icon,title,msg,level){
    h+=makeAlert(icon,title,msg,level);
    if(level==="Warning" || level==="Danger") count++;
    if(level==="Danger") highest="Danger";
    else if(level==="Warning" && highest!=="Danger") highest="Warning";
  }
 
  if(d.calibrating){
    add("⏳","BME680 calibration in progress","IAQ accuracy is "+d.iaqAccuracy+". Keep the sensor running for better IAQ, CO2 and VOC readings.","Warning");
  }
 
  if(Number(d.pm25)>=alertSettings.pm25Danger){
    add("🚨","PM2.5 danger level","PM2.5 is "+d.pm25+" µg/m³. Consider filtration and ventilation.","Danger");
  }else if(Number(d.pm25)>=alertSettings.pm25Warn){
    add("⚠️","PM2.5 warning","PM2.5 is "+d.pm25+" µg/m³. Air quality is becoming unhealthy.","Warning");
  }
 
  if(Number(d.pm10)>=alertSettings.pm10Danger){
    add("🌪️","PM10 danger level","PM10 is "+d.pm10+" µg/m³. Dust level is high.","Danger");
  }else if(Number(d.pm10)>=alertSettings.pm10Warn){
    add("🌫️","PM10 warning","PM10 is "+d.pm10+" µg/m³. Dust level is above your warning limit.","Warning");
  }
 
  if(Number(d.iaq)>=alertSettings.iaqDanger){
    add("🛑","IAQ danger level","IAQ is "+Number(d.iaq).toFixed(0)+". Indoor air quality is unhealthy.","Danger");
  }else if(Number(d.iaq)>=alertSettings.iaqWarn){
    add("⚠️","IAQ warning","IAQ is "+Number(d.iaq).toFixed(0)+". Air quality needs attention.","Warning");
  }
 
  if(Number(d.co2)>=alertSettings.co2Danger){
    add("🫁","CO2 danger level","CO2 equivalent is "+Number(d.co2).toFixed(0)+" ppm. Improve ventilation immediately.","Danger");
  }else if(Number(d.co2)>=alertSettings.co2Warn){
    add("💨","CO2 warning","CO2 equivalent is "+Number(d.co2).toFixed(0)+" ppm. Ventilation may be low.","Warning");
  }
 
  if(Number(d.voc)>=alertSettings.vocDanger){
    add("🧪","VOC danger level","VOC equivalent is "+Number(d.voc).toFixed(2)+" ppm. Possible chemical or odor source nearby.","Danger");
  }else if(Number(d.voc)>=alertSettings.vocWarn){
    add("🧴","VOC warning","VOC equivalent is "+Number(d.voc).toFixed(2)+" ppm. Check for perfumes, smoke, cleaners or solvents.","Warning");
  }
 
  if(Number(d.humidity)<alertSettings.humMin){
    add("💧","Low humidity","Humidity is "+Number(d.humidity).toFixed(0)+"%. Air may feel dry.","Warning");
  }else if(Number(d.humidity)>alertSettings.humMax){
    add("💦","High humidity","Humidity is "+Number(d.humidity).toFixed(0)+"%. Risk of discomfort or moisture buildup.","Warning");
  }
 
  if(Number(d.temperature)<alertSettings.tempMin){
    add("❄️","Low temperature","Temperature is "+Number(d.temperature).toFixed(1)+" °C. Room is below comfort limit.","Warning");
  }else if(Number(d.temperature)>alertSettings.tempMax){
    add("🔥","High temperature","Temperature is "+Number(d.temperature).toFixed(1)+" °C. Room is above comfort limit.","Warning");
  }
 
  if(h===""){
    h+=makeAlert("✅","All readings normal","PM, IAQ, CO2, VOC, temperature and humidity are within the configured limits.","Good");
  }
 
  h+=makeAlert("📡","Device online","ESP32 webserver is serving live readings from PMS7003 and BME680.","Info");
 
  document.getElementById("alertsBox").innerHTML=h;
  setText("activeAlertCount",count);
  setText("highestAlertLevel",highest);
  setText("alertLastCheck",new Date().toLocaleTimeString([],{
    hour:"2-digit",
    minute:"2-digit",
    second:"2-digit"
  }));
}
 
async function fetchReadings(){
  try{
    const r=await fetch("/api/readings");
    const d=await r.json();
    updateUI(d);
  }catch(e){
    setText("deviceState","Offline");
  }
}
 
function addLog(d=latest){
  if(!d)return;
 
  const row=document.createElement("tr");
  const now=new Date().toLocaleTimeString([],{
    hour:"2-digit",
    minute:"2-digit",
    second:"2-digit"
  });
 
  row.innerHTML=`
    <td>${now}</td>
    <td>${d.pm1}</td>
    <td>${d.pm25}</td>
    <td>${d.pm10}</td>
    <td>${Number(d.temperature).toFixed(1)}°C</td>
    <td>${Number(d.humidity).toFixed(1)}%</td>
    <td>${Number(d.iaq).toFixed(1)}</td>
    <td>${Number(d.co2).toFixed(0)}</td>
    <td>${Number(d.voc).toFixed(2)}</td>
    <td>${d.iaqAccuracyText}</td>
  `;
 
  document.getElementById("logBody").prepend(row);
  updateRecordCount();
}
 
function updateRecordCount(){
  setText("recordCount",document.querySelectorAll("#logBody tr").length);
}
 
function startLogger(){
  if(loggerTimer)return;
 
  const interval=Number(document.getElementById("loggingInterval").value);
  const s=document.getElementById("loggerStatus");
 
  s.classList.add("running");
  s.innerHTML='<span class="logger-dot"></span> Logger Running';
 
  loggerTimer=setInterval(()=>addLog(),interval);
}
 
function stopLogger(){
  if(loggerTimer){
    clearInterval(loggerTimer);
    loggerTimer=null;
  }
 
  const s=document.getElementById("loggerStatus");
  s.classList.remove("running");
  s.innerHTML='<span class="logger-dot"></span> Logger Stopped';
}
 
function clearLogs(){
  if(confirm("Clear all logged records?")){
    document.getElementById("logBody").innerHTML="";
    updateRecordCount();
  }
}
 
function exportExcel(){
  const table=document.querySelector("#page-history table");
 
  let html="<html><head><meta charset='UTF-8'></head><body><table border='1'><tr><th colspan='10'>IoT PM and Air Quality Monitoring Data Log</th></tr>";
 
  table.querySelectorAll("tr").forEach(r=>{
    html+="<tr>";
    r.querySelectorAll("th,td").forEach(c=>{
      html+=`<td>${c.innerText}</td>`;
    });
    html+="</tr>";
  });
 
  html+="</table></body></html>";
 
  const blob=new Blob([html],{
    type:"application/vnd.ms-excel"
  });
 
  const name=(document.getElementById("exportFileName").value || "air_quality_log").replace(/[^a-z0-9_-]/gi,"_");
 
  const a=document.createElement("a");
  a.href=URL.createObjectURL(blob);
  a.download=name+".xls";
  a.click();
}
 
function pushPmHistory(d){
  pmHistory.push({
    time:new Date(),
    label:new Date().toLocaleTimeString([],{
      hour:"2-digit",
      minute:"2-digit"
    }),
    pm1:Number(d.pm1),
    pm25:Number(d.pm25),
    pm10:Number(d.pm10)
  });
 
  if(pmHistory.length>80){
    pmHistory.shift();
  }
}
 
function yVal(v,max){
  return 394-(v/max)*(394-34);
}
 
function path(points){
  if(!points.length)return "";
 
  let d=`M${points[0].x},${points[0].y}`;
 
  for(let i=1;i<points.length;i++){
    let p=points[i-1];
    let c=points[i];
    let m=(p.x+c.x)/2;
    d+=` C${m},${p.y} ${m},${c.y} ${c.x},${c.y}`;
  }
 
  return d;
}
 
function setPmRange(k,b){
  document.querySelectorAll(".range-btn").forEach(x=>x.classList.remove("active"));
  b.classList.add("active");
  renderPmChart();
}
 
function renderPmChart(){
  const data=pmHistory.length<2
    ? Array.from({length:30},()=>({label:"--",pm1:0,pm25:0,pm10:0}))
    : pmHistory.slice(-30);
 
  const max=Math.max(1,...data.flatMap(x=>[x.pm1,x.pm25,x.pm10]))*1.15;
 
  const pts=data.map((d,i)=>{
    let x=24+(i/(data.length-1))*852;
    return {
      ...d,
      x,
      y1:yVal(d.pm1,max),
      y25:yVal(d.pm25,max),
      y10:yVal(d.pm10,max)
    };
  });
 
  const p1=path(pts.map(p=>({x:p.x,y:p.y1})));
  const p25=path(pts.map(p=>({x:p.x,y:p.y25})));
  const p10=path(pts.map(p=>({x:p.x,y:p.y10})));
 
  [
    ["pm1Line",p1],
    ["pm25Line",p25],
    ["pm10Line",p10]
  ].forEach(item=>{
    let e=document.getElementById(item[0]);
    if(e)e.setAttribute("d",item[1]);
  });
 
  const a25=document.getElementById("pm25Area");
  const a10=document.getElementById("pm10Area");
 
  if(a25)a25.setAttribute("d",`${p25} L876,394 L24,394 Z`);
  if(a10)a10.setAttribute("d",`${p10} L876,394 L24,394 Z`);
 
  setupHover(pts);
}
 
function setupHover(points){
  const chart=document.getElementById("pmChart");
  if(!chart)return;
 
  const svg=document.getElementById("pmSvg");
  const tip=document.getElementById("pmTooltip");
 
  chart.onmousemove=e=>{
    const r=svg.getBoundingClientRect();
    const x=((e.clientX-r.left)/r.width)*900;
 
    let n=points[0];
    let m=Math.abs(points[0].x-x);
 
    points.forEach(p=>{
      let dd=Math.abs(p.x-x);
      if(dd<m){
        m=dd;
        n=p;
      }
    });
 
    const hl=document.getElementById("hoverLine");
    hl.setAttribute("x1",n.x);
    hl.setAttribute("x2",n.x);
 
    [
      ["hoverPm1",n.y1],
      ["hoverPm25",n.y25],
      ["hoverPm10",n.y10]
    ].forEach(a=>{
      let el=document.getElementById(a[0]);
      el.setAttribute("cx",n.x);
      el.setAttribute("cy",a[1]);
    });
 
    tip.innerHTML=`
      <strong>${n.label}</strong>
      <div class="tooltip-row">
        <span class="tooltip-label"><span class="tooltip-dot" style="--dot:#22c55e"></span>PM1.0</span>
        <b>${n.pm1}</b>
      </div>
      <div class="tooltip-row">
        <span class="tooltip-label"><span class="tooltip-dot" style="--dot:#f97316"></span>PM2.5</span>
        <b>${n.pm25}</b>
      </div>
      <div class="tooltip-row">
        <span class="tooltip-label"><span class="tooltip-dot" style="--dot:#ef4444"></span>PM10</span>
        <b>${n.pm10}</b>
      </div>
    `;
 
    tip.style.left=(n.x/900*r.width)+"px";
    tip.style.top=Math.max(80,Math.min(n.y1,n.y25,n.y10)/430*r.height)+"px";
 
    chart.classList.add("active-hover");
    tip.classList.add("show");
  };
 
  chart.onmouseleave=()=>{
    chart.classList.remove("active-hover");
    tip.classList.remove("show");
  };
}
 
window.addEventListener("load",()=>{
  loadAlertSettings();
});
 
setInterval(fetchReadings,2000);
fetchReadings();
renderPmChart();
</script>
 
</body>
</html>
)rawliteral";
 
#endif


Testing & Results of ESP32 based IoT Air Quality Monitoring Device

After uploading the code to the ESP32, the device starts initializing all the connected modules. First, the OLED display turns on and shows the startup message. After that, the ESP32 connects to the Wi-Fi network and displays the local IP address on the OLED screen. This IP address is used to open the web dashboard on a mobile phone or computer. You can watch it on Serial Monitor as well.

The OLED display shows the sensor readings on two different pages. On the first page, it displays the PMS7003 particulate matter readings, including PM1.0, PM2.5, and PM10 values.

IoT ESP32 BME680 Air Quality Monitor

On the second page, it displays the BME680 readings such as Temperature, Humidity, IAQ, CO2 equivalent, and VOC equivalent.

IoT ESP32 PMS7003 Air Quality Monitor

The display automatically switches between the two pages every few seconds. If the BME680 sensor is still calibrating, a small CAL… message appears on the OLED display. Once the sensor calibration improves, the readings become more stable and accurate.




Monitoring Air Quality and Paticulate Matter on IoT Dashboard

After uploading the code, the ESP32 connects to the Wi-Fi network and starts a local webserver. The IP address of the ESP32 is displayed on the OLED display and also printed on the Serial Monitor.

To open the IoT dashboard, connect your mobile phone or computer to the same Wi-Fi network and enter the ESP32 IP address in the browser. For example, in my case the dashboard was opened using 192.168.2.112.

The dashboard page displays the complete air quality data in a clean and professional layout. The main dashboard shows the IAQ value in a circular gauge, which changes color according to the air quality level. It also displays live values of PM1.0, PM2.5, PM10, temperature, humidity, CO2 equivalent, and VOC equivalent. At the bottom, it shows the device status, PMS7003 status, BME680 calibration level, and last update time.

The PM Readings page is used to monitor particulate matter data from the PMS7003 sensor. It shows separate cards for PM1.0, PM2.5, and PM10. Below these cards, a live graph displays the trend of particulate matter values over time. The graph has different time options such as 15 minutes, 1 hour, 3 hours, 6 hours, 12 hours, and 24 hours, which makes it easier to analyze air pollution changes.

The Environment page displays the BME680 sensor values. It shows temperature, humidity, and IAQ in large cards. Below that, it shows a comfort percentage gauge along with CO2 equivalent, VOC equivalent, calibration status, and uptime. This section helps to understand the indoor environment and air quality condition more clearly.

The History and Data Logger page is used to record sensor readings. It logs time, PM values, temperature, humidity, IAQ, CO2, VOC, and accuracy level. The data logger can be started or stopped from the dashboard, and the logged data can also be exported as an Excel file for later analysis.

The Alerts and Settings page shows air quality warnings based on the sensor readings. It can display alerts for high PM2.5, PM10, IAQ, CO2, VOC, temperature, and humidity levels. This page also includes threshold settings, so we can change the warning and danger limits according to our requirement.

This project successfully demonstrates an IoT based air quality monitoring system using ESP32, PMS7003, and BME680. It can monitor particulate matter, environmental values, and air quality in real time on both the OLED display and web dashboard.


Video Tutorial & Guide

DIY IoT Air Quality Monitor using ESP32, PMS7003 & BME680
Watch this video on YouTube.

Share. Facebook Twitter Pinterest LinkedIn Tumblr Email Reddit Telegram WhatsApp
Previous ArticleDIY ESP32 MLX90640 IR Thermal Camera with Live Web Display
Next Article ESP32 Fingerprint Attendance System with Live Web Dashboard

Related Posts

ESP32 Fingerprint Attendance System with Live Web Dashboard

ESP32 Fingerprint Attendance System with Live Web Dashboard

Updated:June 21, 2026
DIY ESP32 MLX90640 IR Thermal Camera with Live Web Display

DIY ESP32 MLX90640 IR Thermal Camera with Live Web Display

Updated:May 10, 20262K
IoT Activity Tracker with ESP32 & Accelerometer Gyroscope

IoT Activity Tracker with ESP32 & Accelerometer/Gyroscope

Updated:May 2, 2026

ESP32 IoT Vehicle Motion Analyzer with MPU6050 & LIS3MDL

Updated:April 27, 20261K
High-Accuracy Pitch, Roll, Yaw with ESP32 & BNO08x IMU

High-Accuracy Pitch, Roll, Yaw with ESP32 & BNO08x IMU

Updated:April 27, 20262K
DIY Colorimeter using AS7265x Spectroscopy Sensor & ESP32

DIY Colorimeter using AS7265x Spectroscopy Sensor & ESP32

Updated:February 1, 20261K
Add A Comment

CommentsCancel reply

Latest Posts
ESP32 Fingerprint Attendance System with Live Web Dashboard

ESP32 Fingerprint Attendance System with Live Web Dashboard

June 21, 2026
IoT Based PM & Air Quality Monitoring System using ESP32

IoT Based PM & Air Quality Monitoring System using ESP32

June 14, 2026
DIY ESP32 MLX90640 IR Thermal Camera with Live Web Display

DIY ESP32 MLX90640 IR Thermal Camera with Live Web Display

May 10, 2026
IoT Activity Tracker with ESP32 & Accelerometer Gyroscope

IoT Activity Tracker with ESP32 & Accelerometer/Gyroscope

May 2, 2026
A Guide to Sourcing Obsolete ICs for Vintage Projects

Beyond AliExpress: A Guide to Sourcing Obsolete ICs for Vintage Projects

April 21, 2026

ESP32 IoT Vehicle Motion Analyzer with MPU6050 & LIS3MDL

April 27, 2026
Building a Smart Sensor Node with a BLE Microcontroller

Building a Smart Sensor Node with a BLE Microcontroller

February 26, 2026
High-Accuracy Pitch, Roll, Yaw with ESP32 & BNO08x IMU

High-Accuracy Pitch, Roll, Yaw with ESP32 & BNO08x IMU

April 27, 2026
Top Posts & Pages
  • ESP32 Fingerprint Attendance System with Live Web Dashboard
    ESP32 Fingerprint Attendance System with Live Web Dashboard
  • ESP32 CAN Bus Tutorial | Interfacing MCP2515 CAN Module with ESP32
    ESP32 CAN Bus Tutorial | Interfacing MCP2515 CAN Module with ESP32
  • IoT AC Energy Meter with PZEM-004T & ESP32 WebServer
    IoT AC Energy Meter with PZEM-004T & ESP32 WebServer
  • 12V DC to 220V AC Inverter Circuit & PCB
    12V DC to 220V AC Inverter Circuit & PCB
  • LD2410 Sensor with ESP32 - Human Presence Detection
    LD2410 Sensor with ESP32 - Human Presence Detection
  • Buck Converter: Basics, Working, Design & Application
    Buck Converter: Basics, Working, Design & Application
  • IoT Based Patient Health Monitoring on ESP32 Web Server
    IoT Based Patient Health Monitoring on ESP32 Web Server
  • How to use INA226 DC Current Sensor with Arduino
    How to use INA226 DC Current Sensor with Arduino
Categories
  • Arduino Projects (197)
  • Articles (60)
    • Learn Electronics (19)
    • Product Review (15)
    • Tech Articles (28)
  • Electronics Circuits (46)
    • 555 Timer Projects (21)
    • Op-Amp Circuits (7)
    • Power Electronics (13)
  • IoT Projects (205)
    • ESP32 MicroPython (7)
    • ESP32 Projects (82)
    • ESP32-CAM Projects (15)
    • ESP8266 Projects (76)
    • LoRa/LoRaWAN Projects (22)
  • Microcontrollers (38)
    • AMB82-Mini IoT AI Camera (4)
    • BLE Projects (18)
    • STM32 Projects (19)
  • Raspberry Pi (93)
    • Raspberry Pi Pico Projects (57)
    • Raspberry Pi Pico W Projects (12)
    • Raspberry Pi Projects (24)
Follow Us
  • Facebook
  • Twitter
  • Pinterest
  • Instagram
  • YouTube
About Us

“‘How to Electronics’ is a vibrant community for electronics enthusiasts and professionals. We deliver latest insights in areas such as Embedded Systems, Power Electronics, AI, IoT, and Robotics. Our goal is to stimulate innovation and provide practical solutions for students, organizations, and industries. Join us to transform learning into a joyful journey of discovery and innovation.

Copyright © How To Electronics. All rights reserved.
  • About Us
  • Disclaimer
  • Privacy Policy
  • Contact Us
  • Advertise With Us

Type above and press Enter to search. Press Esc to cancel.

Ad Blocker Enabled!
Ad Blocker Enabled!
Looks like you're using an ad blocker. Please allow ads on our site. We rely on advertising to help fund our site.