#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <DHT.h>
// --- CONFIGURATION ---
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
// Pin Definitions
#define DHTPIN 15
#define DHTTYPE DHT22
#define RELAY_PIN 4
#define DUST_POT_PIN 34 // Simulating PMS5003
#define GAS_POT_PIN 35 // Simulating MQ-135
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
// Initialize Pins
pinMode(RELAY_PIN, OUTPUT);
// ESP32 Analog pins are input by default
dht.begin();
// Initialize OLED
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
// Show Boot Screen
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(25, 20);
display.println("AirGuard Pro");
display.setCursor(30, 35);
display.println("Initializing...");
display.display();
delay(2000);
}
void loop() {
// --- 1. READ SENSORS ---
// ESP32 ADC is 12-bit (0-4095)
int dustRaw = analogRead(DUST_POT_PIN);
int gasRaw = analogRead(GAS_POT_PIN);
// Map raw voltage to realistic sensor values
// Dust: 0 to 500 ug/m3
int dustValue = map(dustRaw, 0, 4095, 0, 500);
// Gas: 0 to 1000 PPM
int gasValue = map(gasRaw, 0, 4095, 0, 1000);
float t = dht.readTemperature();
float h = dht.readHumidity();
// --- 2. LOGIC CONTROL ---
// Thresholds: Dust > 50 OR Gas > 400
bool isUnsafe = (dustValue > 50 || gasValue > 400);
if (isUnsafe) {
digitalWrite(RELAY_PIN, HIGH); // Turn Relay ON
} else {
digitalWrite(RELAY_PIN, LOW); // Turn Relay OFF
}
// --- 3. DISPLAY OUTPUT ---
display.clearDisplay();
// Header
display.setCursor(0,0);
if(isUnsafe) display.print("STATUS: ALERT!");
else display.print("STATUS: NORMAL");
// Data
display.setCursor(0, 15);
display.print("PM2.5: "); display.print(dustValue); display.print(" ug");
display.setCursor(0, 25);
display.print("Gas: "); display.print(gasValue); display.print(" PPM");
display.setCursor(0, 35);
display.print("Temp: "); display.print(t, 1); display.print(" C");
// Fan Status at bottom
display.setCursor(0, 52);
display.print("FAN: ");
if(digitalRead(RELAY_PIN)) display.print("ON [Active]");
else display.print("OFF");
display.display();
delay(500); // Refresh rate
}