#include <WiFi.h> // Library for WiFi connectivity
#include "DHTesp.h" // Library for the DHT sensor
#include "ThingSpeak.h" // Library for ThingSpeak communication
// Define the pins for sensors and LED
const int DHT_PIN = 15; // Pin connected to the DHT22 sensor
const int LED_PIN = 13; // Pin connected to the LED
const int MQ2_PIN = 34; // Analog pin connected to the MQ2 gas sensor
// WiFi and ThingSpeak settings
const char* WIFI_NAME = "Wokwi-GUEST"; // WiFi network name
const char* WIFI_PASSWORD = ""; // WiFi password
const int myChannelNumber = 2780341; // ThingSpeak channel number
const char* myApiKey = "7L60HZYCQQSBWG4K"; // ThingSpeak API key
// Global variables
DHTesp dhtSensor; // Instance of the DHT sensor
WiFiClient client; // WiFi client for ThingSpeak
void setup() {
Serial.begin(115200); // Initialize the serial communication
// Initialize the DHT sensor
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
// Initialize the pins for LED and MQ2
pinMode(LED_PIN, OUTPUT);
pinMode(MQ2_PIN, INPUT);
// Connect to WiFi network
WiFi.begin(WIFI_NAME, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(1000); // Wait 1 second between connection attempts
Serial.println("Wifi not connected");
}
Serial.println("Wifi connected!");
// Initialize ThingSpeak
ThingSpeak.begin(client);
}
// Function to read the gas level percentage from the MQ2 sensor
float readMQ2Percentage() {
int sensorValue = analogRead(MQ2_PIN); // Read the analog value from MQ2
// Convert the analog reading (0-4095) to a percentage (0-100)
float percentage = (sensorValue * 100.0) / 4095.0;
return percentage;
}
void loop() {
// Read temperature and humidity from the DHT22 sensor
TempAndHumidity data = dhtSensor.getTempAndHumidity();
// Read the gas level percentage from the MQ2 sensor
float gasPercentage = readMQ2Percentage();
// Update ThingSpeak fields with sensor data
ThingSpeak.setField(1, data.temperature); // Field 1: Temperature
ThingSpeak.setField(2, data.humidity); // Field 2: Humidity
ThingSpeak.setField(3, gasPercentage); // Field 3: Gas level
// Determine if an alert is needed based on threshold values
bool alert = (data.temperature > 35 || // High temperature
data.temperature < 12 || // Low temperature
data.humidity > 70 || // High humidity
data.humidity < 40 || // Low humidity
gasPercentage > 40); // High gas level
// Turn the LED on if alert conditions are met
digitalWrite(LED_PIN, alert);
// Send data to ThingSpeak
int response = ThingSpeak.writeFields(myChannelNumber, myApiKey);
// Print sensor readings and response status to the serial monitor
Serial.println("Temperature: " + String(data.temperature, 1) + "°C");
Serial.println("Humidity: " + String(data.humidity, 1) + "%");
Serial.println("Gas Level: " + String(gasPercentage, 1) + "%");
Serial.println(response == 200 ? "Data sent successfully" : "Error: " + String(response));
Serial.println("---");
// Wait for 10 seconds before the next loop iteration
delay(10000);
}