diff --git a/AirQuality.ino b/AirQuality.ino new file mode 100644 index 0000000..2971711 --- /dev/null +++ b/AirQuality.ino @@ -0,0 +1,274 @@ +#include +#include +#include "DFRobot_ENS160.h" + +// Wi-Fi credentials +const char* ssid = "MegMan-WiFi"; +const char* password = "Zp5egGamPcENXr"; + +// I2C Communication setup +DFRobot_ENS160_I2C ENS160(&Wire, 0x53); // Default I2C address is 0x53 + +AsyncWebServer server(80); + +String jsonData = "[]"; // JSON buffer to hold the air quality data +uint8_t lastAQI = 0; // Store the last AQI value for display + +void setup() { + Serial.begin(115200); + + // Initialise the sensor + while (NO_ERR != ENS160.begin()) { + Serial.println("Communication with ENS160 failed. Please check connections."); + delay(3000); + } + Serial.println("ENS160 initialised successfully."); + + // Set power mode + ENS160.setPWRMode(ENS160_STANDARD_MODE); + + // Set temperature and humidity compensation + ENS160.setTempAndHum(25.0, 50.0); // Example values: 25°C, 50% humidity + + // Connect to Wi-Fi + WiFi.begin(ssid, password); + while (WiFi.status() != WL_CONNECTED) { + delay(1000); + Serial.println("Connecting to Wi-Fi..."); + } + Serial.println("Connected to Wi-Fi!"); + Serial.print("ESP32 IP Address: "); + Serial.println(WiFi.localIP()); + + // Route for the main webpage + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + String html = R"rawliteral( + + + + + + Air Quality Monitoring + + + + + +
+

Air Quality Monitoring

+
+
+
+
+
Air Quality Index (AQI)
+

Value: Loading...

+

Loading recommendation...

+
+
+
+
+
+
+
eCO2 Recommendation
+

Value: Loading...

+

Loading recommendation...

+
+
+
+
+
+
+
TVOC Recommendation
+

Value: Loading...

+

Loading recommendation...

+
+
+
+
+
+
+
+
+
Real-Time Air Quality Graph
+
+
+
+
+
+
+ + + + + + )rawliteral"; + request->send(200, "text/html", html); + }); + + // Route for sensor data (JSON) + server.on("/data", HTTP_GET, [](AsyncWebServerRequest *request) { + request->send(200, "application/json", jsonData); + }); + + // Start the server + server.begin(); +} + +void loop() { + uint16_t TVOC = ENS160.getTVOC(); + uint16_t ECO2 = ENS160.getECO2(); + uint8_t AQI = ENS160.getAQI(); + + unsigned long timestamp = millis(); + String newEntry = "{\"timestamp\":" + String(timestamp) + ",\"tvoc\":" + String(TVOC) + ",\"eco2\":" + String(ECO2) + ",\"aqi\":" + String(AQI) + "}"; + + if (jsonData == "[]") { + jsonData = "[" + newEntry + "]"; + } else { + jsonData = jsonData.substring(0, jsonData.length() - 1) + "," + newEntry + "]"; + } + + // Limit data buffer to 60 entries (last minute) + int maxEntries = 60; + int count = std::count(jsonData.begin(), jsonData.end(), '{'); + if (count > maxEntries) { + int firstComma = jsonData.indexOf(','); + jsonData = "[" + jsonData.substring(firstComma + 1); + } + + delay(1000); // Update every second +}