#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>
// Pin definitions
#define DHTPIN D2
#define DHTTYPE DHT22
#define MQ2_PIN A1
#define PIR_PIN D5
#define TRIG_PIN D3
#define ECHO_PIN D4
#define RED_LED D6
#define GREEN_LED D7
#define BLUE_LED D8
LiquidCrystal_I2C lcd(0x27, 16, 2);
DHT dht(DHTPIN, DHTTYPE);
// RGB LED control
void setRGB(uint8_t r, uint8_t g, uint8_t b) {
analogWrite(RED_LED, r);
analogWrite(GREEN_LED, g);
analogWrite(BLUE_LED, b);
}
void setup() {
pinMode(MQ2_PIN, INPUT);
pinMode(PIR_PIN, INPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(RED_LED, OUTPUT);
pinMode(GREEN_LED, OUTPUT);
pinMode(BLUE_LED, OUTPUT);
dht.begin();
lcd.begin(16, 2);
lcd.backlight();
}
void loop() {
// Sensor readings
int temp = (int)dht.readTemperature();
int humid = (int)dht.readHumidity();
int gas = analogRead(MQ2_PIN);
bool motion = digitalRead(PIR_PIN);
// Distance calculation
digitalWrite(TRIG_PIN, LOW); delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
int duration = pulseIn(ECHO_PIN, HIGH, 30000);
int dist = (duration > 0) ? (duration / 58) : -1;
// Display
lcd.setCursor(0, 0);
lcd.print(F("T:")); lcd.print(temp); lcd.print(F("C "));
lcd.print(F("H:")); lcd.print(humid); lcd.print(F("%"));
lcd.setCursor(0, 1);
lcd.print(F("G:")); lcd.print(gas);
lcd.print(F(" M:")); lcd.print(motion ? F("Y") : F("N"));
// Alert condition
bool alert = (gas > 400 || temp > 35 || motion || (dist >= 0 && dist < 10));
setRGB(alert ? 255 : 0, alert ? 0 : 255, 0);
delay(1000);
}