#include <Wire.h>
#include <WiFi.h>
#include <WebServer.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <DHT.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
WebServer server(80);
// OLED
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
// DHT22
#define DHTPIN 4
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
// MQ2
#define MQ2_PIN 34
#define BUZZER_PIN 26
// Variables
float temperature = 0;
float humidity = 0;
int gasValue = 0;
int aqi = 0;
void handleRoot() {
String html = "<html><head>";
html += "<meta http-equiv='refresh' content='2'>";
html += "<title>ENV MONITOR</title>";
html += "</head><body>";
html += "<h1>ENV MONITOR</h1>";
html += "<p>Temperature: ";
html += String(temperature, 2);
html += " °C</p>";
html += "<p>Humidity: ";
html += String(humidity, 2);
html += " %</p>";
html += "<p>Gas: ";
html += String(gasValue);
html += "</p>";
html += "<p>AQI: ";
html += String(aqi);
html += "</p>";
html += "</body></html>";
server.send(200, "text/html", html);
}
void setup() {
pinMode(BUZZER_PIN, OUTPUT);
digitalWrite(BUZZER_PIN, LOW);
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("WiFi connected! IP: ");
Serial.println(WiFi.localIP());
server.on("/", handleRoot);
server.begin();
Serial.println("Web server started!");
// Start OLED
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println("OLED not found");
while (true);
}
display.clearDisplay();
display.setTextColor(WHITE);
// Start DHT22
dht.begin();
delay(1000);
}
void loop() {
server.handleClient();
// Read DHT22
temperature = dht.readTemperature();
humidity = dht.readHumidity();
// Read MQ2
gasValue = analogRead(MQ2_PIN);
// Convert gas value to estimated AQI
aqi = map(gasValue, 0, 4095, 0, 500);
if (aqi >= 300) {
tone(BUZZER_PIN, 1000);
} else {
noTone(BUZZER_PIN);
}
// Check DHT22
if (isnan(temperature) || isnan(humidity)) {
Serial.println("DHT Error!");
return;
}
// Serial Monitor
Serial.print("Temp: ");
Serial.print(temperature);
Serial.print(" C | Hum: ");
Serial.print(humidity);
Serial.print(" % | Gas: ");
Serial.print(gasValue);
Serial.print(" | AQI: ");
Serial.println(aqi);
// OLED
display.clearDisplay();
display.setTextSize(1);
display.setCursor(0, 0);
display.println("ENV MONITOR");
display.setCursor(0, 12);
display.print("Temp: ");
display.print(temperature);
display.println(" C");
display.setCursor(0, 24);
display.print("Humidity: ");
display.print(humidity);
display.println(" %");
display.setCursor(0, 36);
display.print("Gas: ");
display.println(gasValue);
display.setCursor(0, 48);
display.print("AQI: ");
display.println(aqi);
display.display();
delay(2000);
}