#include <WiFi.h>
#include "DHTesp.h"
#include "ThingSpeak.h"
#include <MQUnifiedsensor.h> // Include MQUnifiedsensor library
// Pin settings
const int DHT_PIN = 15;
const int LED_PIN = 13;
const int MQ2_PIN = 34; // Pin connected to MQ2 sensor
const char* WIFI_NAME = "Wokwi-GUEST";
const char* WIFI_PASSWORD = "";
const int myChannelNumber = 2780341;
const char* myApiKey = "7L60HZYCQQSBWG4K";
const char* server = "api.thingspeak.com";
// MQ2 sensor setup
#define Board ("ESP-32")
#define Pin (MQ2_PIN) // Pin connected to MQ2 sensor
#define Type ("MQ-2") // MQ2 Gas sensor type
#define Voltage_Resolution (3.3)
#define ADC_Bit_Resolution (12) // 12-bit ADC resolution
#define RatioMQ2CleanAir (9.83) // Clean air ratio for calibration
MQUnifiedsensor MQ2(Board, Voltage_Resolution, ADC_Bit_Resolution, Pin, Type);
DHTesp dhtSensor;
WiFiClient client;
void setup() {
Serial.begin(115200);
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
pinMode(LED_PIN, OUTPUT);
pinMode(MQ2_PIN, INPUT); // Initialize MQ2 as an analog input
WiFi.begin(WIFI_NAME, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED){
delay(1000);
Serial.println("Wifi not connected");
}
Serial.println("Wifi connected!");
Serial.println("Local IP: " + String(WiFi.localIP()));
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);
// Initialize MQ2 sensor
MQ2.init();
MQ2.setRegressionMethod(1); // PPM = a * ratio^b
MQ2.setA(574.25);
MQ2.setB(-2.222); // Set the constants for LPG
// Calibrate the sensor (ratio in clean air)
MQ2.calibrate(RatioMQ2CleanAir); // Pass the ratio value for clean air
}
void loop() {
TempAndHumidity data = dhtSensor.getTempAndHumidity();
ThingSpeak.setField(1, data.temperature); // Set temperature to field 1
ThingSpeak.setField(2, data.humidity); // Set humidity to field 2
// Read MQ2 value and calculate PPM concentration
MQ2.update(); // Read new data from the sensor
float mq2Value = MQ2.readSensor(); // Returns the raw value of the sensor
float gasPPM = MQ2.calibrate(RatioMQ2CleanAir); // Calibrate and get PPM value
// Update the Smoke field with the MQ2 value
ThingSpeak.setField(3, gasPPM); // Set MQ2 value to field 3 (Smoke field)
// If MQ2 value is high, turn on the LED
if (data.temperature > 35 || data.temperature < 12 || data.humidity > 70 || data.humidity < 40 || gasPPM > 400) {
digitalWrite(LED_PIN, HIGH); // Turn on the LED if conditions are met
} else {
digitalWrite(LED_PIN, LOW); // Otherwise, turn off the LED
}
int x = ThingSpeak.writeFields(myChannelNumber, myApiKey);
Serial.println("Temp: " + String(data.temperature, 2) + "°C");
Serial.println("Humidity: " + String(data.humidity, 1) + "%");
Serial.println("MQ2 Value: " + String(gasPPM));
if (x == 200) {
Serial.println("Data pushed successfully");
} else {
Serial.println("Push error" + String(x));
}
Serial.println("---");
delay(10000); // Wait for 10 seconds before the next loop
}