#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
// === WiFi and ThingSpeak Configuration ===
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const String apiKey = "129XW35TOMI41Q8P"; // Replace with your actual API key
const String server = "http://api.thingspeak.com/update";
// === Pin Definitions ===
#define DHTPIN 15 // DHT22 data pin
#define DHTTYPE DHT 22 // Sensor type
#define MQ135_PIN 34 // Analog pin for gas sensor simulation
#define LDR_PIN 35 // Analog pin for light sensor (LDR)
#define LED_PIN 2 // LED for air quality status
#define BUZZER_PIN 4 // Buzzer pin for alerts
DHT dht(DHTPIN, DHTTYPE); // DHT sensor object
void setup() {
Serial.begin(115200);
delay(1000);
// Initialize sensors and actuators
dht.begin();
pinMode(MQ135_PIN, INPUT);
pinMode(LDR_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
Serial.println("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("\nWiFi connected.");
}
void loop() {
Serial.println("WiFi connected.");
// === Sensor Readings ===
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
int airQuality = analogRead(MQ135_PIN);
int lightLevel = analogRead(LDR_PIN); // Simulated light intensity
// Validate DHT sensor readings
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
delay(2000);
return;
}
// === Print to Serial Monitor ===
Serial.print("Temp: ");
Serial.print(temperature);
Serial.print("°C, Humidity: ");
Serial.print(humidity);
Serial.print("%, Air Quality: ");
Serial.print(airQuality);
Serial.print(", Light Level: ");
Serial.println(lightLevel);
// === Alert and Indication Based on Air Quality ===
bool poorAir = airQuality > 2000;
digitalWrite(LED_PIN, poorAir ? HIGH : LOW); // LED warning
digitalWrite(BUZZER_PIN, poorAir ? HIGH : LOW); // Buzzer warning
// === Send Data to ThingSpeak ===
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = server + "?api_key=" + apiKey +
"&field1=" + String(temperature) +
"&field2=" + String(humidity) +
"&field3=" + String(airQuality) +
"&field4=" + String(lightLevel);
http.begin(url); // Start HTTP request
int httpResponseCode = http.GET(); // Send GET
if (httpResponseCode > 0) {
Serial.print("Data sent. Response code: ");
Serial.println(httpResponseCode);
} else {
Serial.print("Error sending data. Code: ");
Serial.println(httpResponseCode);
}
http.end(); // Close HTTP connection
} else {
Serial.println("WiFi not connected.");
}
delay(15000); // Wait 15 seconds (ThingSpeak limit)
}