Monitoring indoor air quality is important for maintaining a healthy living environment. In this tutorial, we will learn how to build a smart IoT-based air quality monitoring system using ESP32 and BME688 sensors that measure temperature, humidity, atmospheric pressure, and gas levels (IAQ—Indoor Air Quality). This system can send real-time data to a web dashboard for easy access from any device on your local network.
Unlike older sensors like BME280 and BME680, BME688 is an upgraded version with gas sensing capabilities, making it the best for Air quality detection, Weather station, and IoT applications. Checkout IoT Based Temperature Monitoring With Blynk 2.0 & Raspberry Pi
Components Required
You can purchase all these components from Amazon or AliExpress.
S.N | Component | Quantity | Purchase Link |
---|---|---|---|
1 | ESP32 Board | 1 | Amazon / AliExpress |
2 | BME688 Sensor | 1 | Amazon / AliExpress |
3 | Jumper Wires | 6-8 | Amazon / AliExpress |
4 | Breadboard | 1 | Amazon / AliExpress |
5 | Micro-USB Cable | 1 | Amazon / AliExpress |
BME688 Temperature, Humidity, Pressure, and Gas Sensor
The BME688 is an advanced environmental sensor from Bosch, capable of measuring temperature, humidity, pressure, and air quality. It builds on the BME280 and BMP280 by adding a MOX gas sensor, which detects volatile organic compounds (VOCs), ethanol, alcohol, and carbon monoxide—making it great for air quality monitoring.
The BME688 is Bosch’s latest environmental sensor with AI-based gas detection and air quality monitoring. It supports I2C/SPI communication with a voltage range of 1.71V to 3.6V. The sensor measures VOCs, CO2, temperature (±1°C), humidity (±3% RH), and pressure (±1 hPa).
BME688 Pinout & Wiring
Power Pins:
- VIN / VCC: 3V to 5V power supply
- GND: Ground
- 3Vo: 3.3V regulated output
SPI Pins (for fast data transfer):
- SDO: Data output
- CS: Chip Select
- SDI: Data input
- SCK: Clock signal
I2C Pins (for simple connections):
- SDA (SDI): Data line
- SCL (SCK): Clock line
- ADDR: Changes I2C address
Share SDI, SDO, and SCK for multiple sensors, but use a different CS pin.
Wiring: ESP32 & BME688 Sensor
Connect the BME688 sensor to the ESP32 using I2C:
BME688 Pin | ESP32 Pin |
---|---|
VCC | 3.3V |
GND | GND |
SCL | GPIO 22 |
SDA | GPIO 21 |
Note: The default I2C address of BME688 is 0x76. If needed, you can change it to 0x77 by connecting SDO to VDDIO instead of GND.
Power the ESP32 via USB or an external power supply.
Below is the connection diagram of the BME680 Sensor with the ESP32 Board. You can use the breadboard to assemble the circuit.
Programming ESP32 for BME688
To use BME688 with ESP32, we need to install some libraries.
Required Libraries
- Adafruit BME688 Library
- Adafruit Unified Sensor Library
Installing Libraries in Arduino IDE
- Open Arduino IDE
- Go to Sketch → Include Library → Manage Libraries
- Search for BME688 and install Adafruit BME688
- Search for Adafruit Unified Sensor and install it
Source Code – BME688 IoT Air Quality & Weather Monitoring with ESP32
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 |
#include <Wire.h> #include <SPI.h> #include <Adafruit_Sensor.h> #include <Adafruit_BME680.h> #include <WiFi.h> #include <WebServer.h> #include <SPIFFS.h> #include <ArduinoJson.h> #include <time.h> #define SEALEVELPRESSURE_HPA (1013.25) Adafruit_BME680 bme; // I2C // Environmental data structure struct SensorData { float temperature; float humidity; float pressure; float gasResistance; float altitude; float dewPoint; float airQualityIndex; String timestamp; unsigned long lastUpdate; }; SensorData sensorData; // Replace with your network credentials const char* ssid = "ESP"; const char* password = "aaaaaaaa"; // Time settings const char* ntpServer = "pool.ntp.org"; const long gmtOffset_sec = 0; const int daylightOffset_sec = 3600; // Create WebServer object on port 80 WebServer server(80); // Cached HTML content String cachedHTML; // Function prototypes void handleRoot(); void handleNotFound(); void handleData(); void readSensorData(); float calculateAirQualityIndex(float gas, float humidity); float dewPointCalculation(float temperature, float humidity); String getTimeString(); void setupTime(); String getHTML(); void reconnectWiFi(); void setup() { Serial.begin(115200); delay(100); Serial.println(F("BME688 Environmental Monitoring System - Initializing...")); if (!SPIFFS.begin(true)) { Serial.println("SPIFFS Mount Failed - will use embedded HTML"); } else { Serial.println("SPIFFS Mounted Successfully"); } if (!bme.begin()) { Serial.println("Could not find a valid BME688 sensor, check wiring!"); while (1) { delay(1000); } } bme.setTemperatureOversampling(BME680_OS_8X); bme.setHumidityOversampling(BME680_OS_4X); bme.setPressureOversampling(BME680_OS_4X); bme.setIIRFilterSize(BME680_FILTER_SIZE_3); bme.setGasHeater(320, 150); Serial.println("BME688 sensor configuration complete"); reconnectWiFi(); setupTime(); server.on("/", HTTP_GET, handleRoot); server.on("/data", HTTP_GET, handleData); server.onNotFound(handleNotFound); server.begin(); Serial.print("Web server started at http://"); Serial.println(WiFi.localIP()); readSensorData(); } void loop() { if (WiFi.status() != WL_CONNECTED) { reconnectWiFi(); } server.handleClient(); static unsigned long lastReadTime = 0; if (millis() - lastReadTime > 5000) { readSensorData(); lastReadTime = millis(); } } void reconnectWiFi() { if (WiFi.status() != WL_CONNECTED) { Serial.println("Connecting to WiFi..."); WiFi.begin(ssid, password); // Wait up to 20 seconds for connection int timeout = 0; while (WiFi.status() != WL_CONNECTED && timeout < 40) { delay(500); Serial.print("."); timeout++; } if (WiFi.status() == WL_CONNECTED) { Serial.println("\nWiFi connected!"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); } else { Serial.println("\nWiFi connection failed!"); } } } void setupTime() { configTime(gmtOffset_sec, daylightOffset_sec, ntpServer); struct tm timeinfo; if (!getLocalTime(&timeinfo)) { Serial.println("Failed to obtain time from NTP server"); } } String getTimeString() { struct tm timeinfo; if (!getLocalTime(&timeinfo)) { return "Time not available"; } char timeStr[20]; strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", &timeinfo); return String(timeStr); } void readSensorData() { unsigned long endTime = bme.beginReading(); if (endTime == 0) { Serial.println("Failed to begin reading :("); return; } delay(50); // Allow time for measurement if (!bme.endReading()) { Serial.println("Failed to complete reading :("); return; } sensorData.temperature = bme.temperature; sensorData.humidity = bme.humidity; sensorData.pressure = bme.pressure / 100.0F; sensorData.gasResistance = bme.gas_resistance / 1000.0; sensorData.altitude = bme.readAltitude(SEALEVELPRESSURE_HPA); sensorData.dewPoint = dewPointCalculation(sensorData.temperature, sensorData.humidity); sensorData.airQualityIndex = calculateAirQualityIndex(sensorData.gasResistance, sensorData.humidity); sensorData.timestamp = getTimeString(); sensorData.lastUpdate = millis(); Serial.println("New Sensor Readings:"); Serial.printf("Temperature: %.2f °C\n", sensorData.temperature); Serial.printf("Humidity: %.2f %%\n", sensorData.humidity); Serial.printf("Pressure: %.2f hPa\n", sensorData.pressure); Serial.printf("Gas: %.2f KOhms\n", sensorData.gasResistance); Serial.printf("Altitude: %.2f m\n", sensorData.altitude); Serial.printf("Dew Point: %.2f °C\n", sensorData.dewPoint); Serial.printf("Air Quality Index: %.2f (0-100)\n", sensorData.airQualityIndex); Serial.printf("Timestamp: %s\n", sensorData.timestamp.c_str()); } void handleRoot() { Serial.println("Root page requested"); if (cachedHTML.isEmpty()) { cachedHTML = getHTML(); } server.send(200, "text/html", cachedHTML); } void handleData() { Serial.println("Data endpoint requested"); server.sendHeader("Access-Control-Allow-Origin", "*"); server.sendHeader("Access-Control-Allow-Methods", "GET"); server.sendHeader("Access-Control-Allow-Headers", "Content-Type"); DynamicJsonDocument doc(1024); doc["temperature"] = sensorData.temperature; doc["humidity"] = sensorData.humidity; doc["pressure"] = sensorData.pressure; doc["gasResistance"] = sensorData.gasResistance; doc["altitude"] = sensorData.altitude; doc["dewPoint"] = sensorData.dewPoint; doc["airQuality"] = sensorData.airQualityIndex; doc["timestamp"] = sensorData.timestamp; doc["lastUpdate"] = sensorData.lastUpdate; String response; serializeJson(doc, response); server.send(200, "application/json", response); } void handleNotFound() { Serial.print("Not found: "); Serial.println(server.uri()); server.send(404, "text/plain", "Not Found"); } float dewPointCalculation(float temperature, float humidity) { float a = 17.271; float b = 237.7; float temp = (a * temperature) / (b + temperature) + log(humidity / 100); return (b * temp) / (a - temp); } float calculateAirQualityIndex(float gasResistance, float humidity) { float gasScore = map(gasResistance, 5, 500, 0, 100); gasScore = constrain(gasScore, 0, 100); float humidityScore = 100 - abs(humidity - 50) * 2; humidityScore = constrain(humidityScore, 0, 100); return gasScore * 0.7 + humidityScore * 0.3; // Weighted score for AQI } String getHTML() { String html = R"rawliteral( <!DOCTYPE HTML> <html lang="en"> <head> <title>BME688 Environmental Monitor | Dashboard</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="Environmental monitoring system using BME688 sensor"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css"> <style> :root { --primary-color: #2c3e50; --secondary-color: #34495e; --accent-color: #3498db; --success-color: #27ae60; --warning-color: #f39c12; --danger-color: #e74c3c; --light-color: #ecf0f1; --dark-color: #2c3e50; --border-radius: 6px; --box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); } * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Segoe UI', system-ui, -apple-system, BlinkMacSystemFont, sans-serif; } body { background-color: #f8f9fa; color: var(--dark-color); margin: 0; padding: 0; line-height: 1.6; } /* Header Styles */ .header { background: var(--primary-color); color: white; padding: 1rem; box-shadow: var(--box-shadow); } .header-container { max-width: 1200px; margin: 0 auto; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; /* Allow items to wrap on smaller screens */ gap: 0.5rem; /* Add some spacing between header elements */ } .header h1 { margin: 0; font-size: 1.25rem; /* Slightly smaller header on smaller screens */ font-weight: 500; display: flex; align-items: center; gap: 0.5rem; } /* Main Content Container */ .container { max-width: 1200px; margin: 0 auto; padding: 1rem; /* Reduced padding for smaller screens */ } .dashboard-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem; flex-wrap: wrap; /* Wrap elements on smaller screens */ gap: 0.5rem; /* Add spacing between header elements */ } .dashboard-title { font-size: 1.25rem; /* Slightly smaller title */ font-weight: 500; } .sensor-status { display: flex; align-items: center; gap: 0.375rem; /* Reduced spacing */ font-size: 0.75rem; /* Smaller font size */ } .sensor-status-dot { height: 8px; /* Smaller dot */ width: 8px; /* Smaller dot */ border-radius: 50%; background-color: var(--success-color); } .sensor-status-dot.calibrating { background-color: var(--warning-color); } .sensor-status-dot.error { background-color: var(--danger-color); } .date-time { font-size: 0.75rem; /* Smaller font size */ color: #666; padding: 0.375rem 0.625rem; /* Reduced padding */ border-radius: var(--border-radius); background-color: #fff; display: inline-flex; align-items: center; gap: 0.375rem; /* Reduced spacing */ box-shadow: var(--box-shadow); } /* Status Card Styles */ .status-card { background: #ffffff; border-radius: var(--border-radius); padding: 0.75rem; /* Reduced padding */ margin-bottom: 1rem; display: flex; align-items: center; box-shadow: var(--box-shadow); border-left: 4px solid var(--success-color); } .status-card.warning { border-left: 4px solid var(--warning-color); } .status-card.danger { border-left: 4px solid var(--danger-color); } .status-card i { font-size: 1.25rem; /* Slightly smaller icon */ margin-right: 0.75rem; /* Reduced margin */ padding: 0.5rem; /* Reduced padding */ border-radius: 50%; color: var(--success-color); } .status-card.warning i { color: var(--warning-color); } .status-card.danger i { color: var(--danger-color); } .status-content { flex-grow: 1; } .status-title { font-weight: 500; font-size: 0.875rem; /* Smaller font size */ margin-bottom: 0.125rem; } .status-message { color: #666; font-size: 0.75rem; /* Smaller font size */ } .action-button { background-color: var(--accent-color); color: white; border: none; border-radius: var(--border-radius); padding: 0.375rem 0.75rem; /* Reduced padding */ cursor: pointer; font-size: 0.75rem; /* Smaller font size */ display: flex; align-items: center; gap: 0.375rem; /* Reduced spacing */ transition: background-color 0.2s; } .action-button:hover { background-color: #2980b9; } /* Grid Styles */ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); /* Slightly smaller cards */ gap: 0.75rem; /* Reduced gap */ } /* Card Styles */ .card { background: #ffffff; border-radius: var(--border-radius); padding: 1rem; /* Reduced padding */ box-shadow: var(--box-shadow); height: 100%; } .card-header { display: flex; align-items: center; margin-bottom: 0.75rem; /* Reduced margin */ } .card-icon { font-size: 1rem; /* Smaller icon */ width: 2rem; /* Smaller icon container */ height: 2rem; /* Smaller icon container */ display: flex; align-items: center; justify-content: center; border-radius: 50%; margin-right: 0.5rem; /* Reduced margin */ } .card-title { font-size: 0.75rem; /* Smaller font size */ font-weight: 500; color: #666; } .card-value { font-size: 1.5rem; /* Slightly smaller value */ font-weight: 500; color: var(--dark-color); margin: 0.5rem 0; /* Reduced margin */ display: flex; align-items: baseline; } .card-unit { font-size: 0.75rem; /* Smaller font size */ color: #666; margin-left: 0.125rem; font-weight: 400; } .card-info { font-size: 0.625rem; /* Smaller font size */ color: #666; margin-top: 0.125rem; } .threshold-range { display: flex; justify-content: space-between; margin-top: 0.5rem; /* Reduced margin */ font-size: 0.625rem; /* Smaller font size */ color: #666; } .threshold-range span { white-space: nowrap; } /* Progress Bar Styles */ .progress-container { width: 100%; height: 0.375rem; /* Reduced height */ background-color: #f1f1f1; border-radius: 3px; margin-top: 0.5rem; /* Reduced margin */ overflow: hidden; } .progress-bar { height: 100%; border-radius: 3px; transition: width 0.8s ease, background-color 0.5s ease; } .progress-label { display: flex; justify-content: space-between; margin-top: 0.25rem; /* Reduced margin */ font-size: 0.625rem; /* Smaller font size */ color: #666; } .card-secondary-value { display: flex; font-size: 0.75rem; /* Smaller font size */ color: #666; margin-top: 0.25rem; /* Reduced margin */ justify-content: space-between; flex-wrap: wrap; /* Allow wrapping on smaller screens */ gap: 0.25rem; /* Add spacing between secondary values */ } .card-badge { display: inline-block; font-size: 0.625rem; /* Smaller font size */ padding: 0.0625rem 0.375rem; /* Reduced padding */ border-radius: 20px; background-color: #f8f9fa; margin-top: 0.375rem; /* Reduced margin */ } .card-badge.good { background-color: rgba(39, 174, 96, 0.15); color: var(--success-color); } .card-badge.ok { background-color: rgba(243, 156, 18, 0.15); color: var(--warning-color); } .card-badge.bad { background-color: rgba(231, 76, 60, 0.15); color: var(--danger-color); } /* Footer Styles */ .footer { background-color: var(--primary-color); color: var(--light-color); text-align: center; padding: 0.75rem; /* Reduced padding */ margin-top: 1.5rem; /* Reduced margin */ font-size: 0.625rem; /* Smaller font size */ display: flex; flex-direction: column; gap: 0.375rem; /* Reduced spacing */ } /* Custom card colors */ .temp-icon { background-color: rgba(231, 76, 60, 0.1); color: #e74c3c; } .humid-icon { background-color: rgba(52, 152, 219, 0.1); color: #3498db; } .pressure-icon { background-color: rgba(155, 89, 182, 0.1); color: #9b59b6; } .altitude-icon { background-color: rgba(243, 156, 18, 0.1); color: #f39c12; } .aqi-icon { background-color: rgba(26, 188, 156, 0.1); color: #1abc9c; } /* Responsive tweaks */ @media (max-width: 600px) { .header-container, .dashboard-header { flex-direction: column; align-items: flex-start; gap: 0.25rem; /* Further reduced spacing */ } .status-card { flex-direction: column; align-items: flex-start; } .status-card i { margin-bottom: 0.25rem; } .card-secondary-value { flex-direction: column; gap: 0.125rem; } /* Make the grid a single column on very small screens */ .grid { grid-template-columns: 1fr; } } /* Added refresh button styling */ .refresh-btn-container { margin-left: 0.5rem; } </style> </head> <body> <div class="header"> <div class="header-container"> <h1><i class="fas fa-microchip"></i> BME688 Environmental Monitor</h1> <div class="sensor-status"> <div id="sensor-status-dot" class="sensor-status-dot"></div> <span id="sensor-status-text">Connecting...</span> <div class="refresh-btn-container"> <button id="refresh-button" class="action-button"> <i class="fas fa-sync-alt"></i> Refresh </button> </div> </div> </div> </div> <div class="container"> <div class="dashboard-header"> <div class="dashboard-title">Environmental Metrics</div> <div class="date-time"> <i class="far fa-clock"></i> <span id="date-time">Loading...</span> </div> </div> <div class="grid"> <!-- Added Air Quality card --> <div class="card"> <div class="card-header"> <div class="card-icon aqi-icon"> <i class="fas fa-wind"></i> </div> <div class="card-title">Air Quality</div> </div> <div class="card-value" id="air-quality">--<span class="card-unit">/100</span></div> <div class="card-info">Air Quality Index</div> <div class="progress-container"> <div id="aqi-bar" class="progress-bar" style="width: 0%; background-color: var(--success-color);"></div> </div> <div class="progress-label"> <span>0</span> <span id="aqi-text">Measuring...</span> <span>100</span> </div> <div class="card-secondary-value"> <span>Status:</span> <span id="aqi-badge" class="card-badge">--</span> </div> </div> <!-- Temperature card --> <div class="card"> <div class="card-header"> <div class="card-icon temp-icon"> <i class="fas fa-thermometer-half"></i> </div> <div class="card-title">Temperature</div> </div> <div class="card-value" id="temperature">--<span class="card-unit">°C</span></div> <div class="card-info">Ambient temperature</div> <div class="progress-container"> <div id="temp-bar" class="progress-bar" style="width: 0%; background-color: var(--success-color);"></div> </div> <div class="progress-label"> <span>0°C</span> <span id="temp-text">Measuring...</span> <span>40°C</span> </div> <div class="threshold-range"> <span>Comfort Zone: 18-24°C</span> </div> </div> <!-- Humidity card --> <div class="card"> <div class="card-header"> <div class="card-icon humid-icon"> <i class="fas fa-tint"></i> </div> <div class="card-title">Humidity</div> </div> <div class="card-value" id="humidity">--<span class="card-unit">%</span></div> <div class="card-info">Relative humidity</div> <div class="progress-container"> <div id="humidity-bar" class="progress-bar" style="width: 0%; background-color: var(--success-color);"></div> </div> <div class="progress-label"> <span>0%</span> <span id="humidity-text">Measuring...</span> <span>100%</span> </div> <div class="card-secondary-value"> <span>Dew Point:</span> <span id="dew-point">-- °C</span> </div> </div> <!-- Pressure card --> <div class="card"> <div class="card-header"> <div class="card-icon pressure-icon"> <i class="fas fa-tachometer-alt"></i> </div> <div class="card-title">Pressure</div> </div> <div class="card-value" id="pressure">--<span class="card-unit">hPa</span></div> <div class="card-info">Atmospheric pressure</div> <div class="progress-container"> <div id="pressure-bar" class="progress-bar" style="width: 0%; background-color: var(--success-color);"></div> </div> <div class="progress-label"> <span>900 hPa</span> <span id="pressure-text">Measuring...</span> <span>1100 hPa</span> </div> <div class="card-secondary-value"> <span>Sea Level:</span> <span id="sea-level-pressure">1013.25 hPa</span> </div> </div> <!-- Altitude card --> <div class="card"> <div class="card-header"> <div class="card-icon altitude-icon"> <i class="fas fa-mountain"></i> </div> <div class="card-title">Altitude</div> </div> <div class="card-value" id="altitude">--<span class="card-unit">m</span></div> <div class="card-info">Approximate altitude</div> <div class="progress-container"> <div id="altitude-bar" class="progress-bar" style="width: 0%; background-color: var(--success-color);"></div> </div> <div class="progress-label"> <span>0 m</span> <span id="altitude-text">Measuring...</span> <span>1000 m</span> </div> <div class="card-secondary-value"> <span>Reference pressure:</span> <span>1013.25 hPa</span> </div> </div> </div> </div> <div class="footer"> <div>BME688 Environmental Monitor | ESP32</div> <div>Last updated: <span id="last-update-time">--</span></div> </div> <script> // Global variables const API_URL = '/data'; const REFRESH_INTERVAL = 5000; // 5 seconds let lastUpdateTime = 0; let sensorConnected = false; // DOM Elements const sensorStatusDot = document.getElementById('sensor-status-dot'); const sensorStatusText = document.getElementById('sensor-status-text'); const dateTimeElement = document.getElementById('date-time'); const lastUpdateTimeElement = document.getElementById('last-update-time'); //Keep last update time // Card values const temperatureElement = document.getElementById('temperature'); const humidityElement = document.getElementById('humidity'); const pressureElement = document.getElementById('pressure'); const altitudeElement = document.getElementById('altitude'); const airQualityElement = document.getElementById('air-quality'); // Progress Bar elements const tempBar = document.getElementById('temp-bar'); const humidityBar = document.getElementById('humidity-bar'); const pressureBar = document.getElementById('pressure-bar'); const altitudeBar = document.getElementById('altitude-bar'); const aqiBar = document.getElementById('aqi-bar'); // Progress text elements const tempText = document.getElementById('temp-text'); const humidityText = document.getElementById('humidity-text'); const pressureText = document.getElementById('pressure-text'); const altitudeText = document.getElementById('altitude-text'); const aqiText = document.getElementById('aqi-text'); const dewPointElement = document.getElementById('dew-point'); const seaLevelPressureElement = document.getElementById('sea-level-pressure'); const aqiBadge = document.getElementById('aqi-badge'); // Initialize refresh button const refreshButton = document.getElementById('refresh-button'); refreshButton.addEventListener('click', fetchData); // Function to update the date and time function updateDateTime() { const now = new Date(); const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' }; dateTimeElement.textContent = now.toLocaleDateString('en-US', options); } // Function to update the sensor connection status function updateSensorStatus(connected) { sensorConnected = connected; if (connected) { sensorStatusDot.className = 'sensor-status-dot'; sensorStatusText.textContent = 'Connected'; refreshButton.disabled = false; } else { sensorStatusDot.className = 'sensor-status-dot error'; sensorStatusText.textContent = 'Disconnected'; refreshButton.disabled = true; } } // Function to format timestamps from the sensor function formatTimestamp(timestamp) { if (!timestamp) return '--'; return timestamp; } // Function to format the last update time function formatLastUpdateTime(lastUpdate) { if (!lastUpdate) return '--'; const now = Date.now(); const diff = now - lastUpdate; if (diff < 60000) { return `${Math.floor(diff / 1000)} seconds ago`; } else if (diff < 3600000) { return `${Math.floor(diff / 60000)} minutes ago`; } else { return `${Math.floor(diff / 3600000)} hours ago`; } } // Function to map a value from one range to another function mapValue(value, inMin, inMax, outMin, outMax) { return ((value - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin; } // Function to update the air quality badge function updateAirQualityBadge(value) { if (value >= 70) { aqiBadge.className = 'card-badge good'; aqiBadge.textContent = 'Good'; } else if (value >= 50) { aqiBadge.className = 'card-badge ok'; aqiBadge.textContent = 'Moderate'; } else { aqiBadge.className = 'card-badge bad'; aqiBadge.textContent = 'Poor'; } } // Function to update all UI elements with sensor data function updateUI(data) { if (!data) return; // Update air quality index airQualityElement.textContent = data.airQuality ? data.airQuality.toFixed(1) : '--'; if (data.airQuality) { aqiBar.style.width = `${data.airQuality}%`; aqiText.textContent = `${data.airQuality.toFixed(1)}/100`; updateAirQualityBadge(data.airQuality); } // Update temperature temperatureElement.textContent = data.temperature ? data.temperature.toFixed(1) : '--'; if (data.temperature) { const tempPercent = mapValue(data.temperature, 0, 40, 0, 100); tempBar.style.width = `${tempPercent}%`; tempText.textContent = `${data.temperature.toFixed(1)}°C`; } // Update humidity humidityElement.textContent = data.humidity ? data.humidity.toFixed(1) : '--'; if (data.humidity) { humidityBar.style.width = `${data.humidity}%`; humidityText.textContent = `${data.humidity.toFixed(1)}%`; } dewPointElement.textContent = data.dewPoint ? `${data.dewPoint.toFixed(1)} °C` : '-- °C'; // Update pressure pressureElement.textContent = data.pressure ? data.pressure.toFixed(1) : '--'; if (data.pressure) { const pressurePercent = mapValue(data.pressure, 900, 1100, 0, 100); pressureBar.style.width = `${pressurePercent}%`; pressureText.textContent = `${data.pressure.toFixed(1)} hPa`; } // Update altitude altitudeElement.textContent = data.altitude ? data.altitude.toFixed(1) : '--'; if (data.altitude) { const altitudePercent = mapValue(data.altitude, 0, 1000, 0, 100); altitudeBar.style.width = `${altitudePercent}%`; altitudeText.textContent = `${data.altitude.toFixed(1)} m`; } // Update timestamp lastUpdateTimeElement.textContent = formatTimestamp(data.timestamp); } // Function to fetch data from the ESP32 function fetchData() { refreshButton.disabled = true; refreshButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Refreshing...'; fetch(API_URL) .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .then(data => { updateSensorStatus(true); updateUI(data); lastUpdateTime = Date.now(); }) .catch(error => { console.error('Error fetching sensor data:', error); updateSensorStatus(false); alert("Connection Error: Could not fetch sensor data. Check connection and ESP32."); }) .finally(() => { refreshButton.disabled = false; refreshButton.innerHTML = '<i class="fas fa-sync-alt"></i> Refresh'; }); } // Function to start the periodic data updates function startPeriodicUpdates() { // Update the date and time immediately and every second updateDateTime(); setInterval(updateDateTime, 1000); // Fetch data immediately fetchData(); // Set up periodic data fetching setInterval(fetchData, REFRESH_INTERVAL); } // Start the application when the page is loaded window.addEventListener('load', startPeriodicUpdates); </script> </body> </html> )rawliteral"; return html; } |
- Upload the code to ESP32 using Arduino IDE.
- Open Serial Monitor (Baud Rate: 115200).
- Check IP Address (e.g.,
192.168.81.238
).
Sensor Configuration
The BME688 is initialized with specific settings to optimize its performance:
1 2 3 4 5 |
bme.setTemperatureOversampling(BME680_OS_8X); bme.setHumidityOversampling(BME680_OS_4X); bme.setPressureOversampling(BME680_OS_4X); bme.setIIRFilterSize(BME680_FILTER_SIZE_3); bme.setGasHeater(320, 150); // 320°C for 150ms |
These settings provide a good balance between accuracy and power consumption.
Data Collection and Processing
The system collects raw sensor data and then processes it to derive valuable metrics:
Dew Point Calculation
1 2 3 4 5 6 |
float dewPointCalculation(float temperature, float humidity) { float a = 17.271; float b = 237.7; float temp = (a * temperature) / (b + temperature) + log(humidity / 100); return (b * temp) / (a - temp); } |
1 2 3 4 5 6 7 8 9 |
float calculateAirQualityIndex(float gasResistance, float humidity) { float gasScore = map(gasResistance, 5, 500, 0, 100); gasScore = constrain(gasScore, 0, 100); float humidityScore = 100 - abs(humidity - 50) * 2; humidityScore = constrain(humidityScore, 0, 100); return gasScore * 0.7 + humidityScore * 0.3; // Weighted score for AQI } |
This calculation creates a 0-100 scale where higher values indicate better air quality.
The project has a web dashboard built with HTML, CSS, and JavaScript. The interface displays:
- Real-time sensor readings
- Visual indicators for each metric
- Progress bars showing values about normal ranges
- Connection status and timestamp information
Testing IoT Air Quality & Weather Monitoring ESP32 BME688
- Open a web browser and enter the ESP32’s IP address.
- The webpage will display temperature, humidity, pressure, and air quality data.
This is how we can interface the BME688 Environmental Sensor with ESP32 or ESP8266 WiFi module to measure IAQ (Indoor Air Quality) and other environmental parameters, detect harmful gases, measure IAQ, and estimate CO2 levels. This makes it ideal for home automation, IoT, and weather monitoring applications.