#include <WiFi.h>
#include "DHTesp.h"
#include "ThingSpeak.h"
DHTesp dht;
const char* WIFI_NAME = "Wokwi-GUEST";
const char* WIFI_PASSWORD = ""; // Add your WiFi password here
const int myChannelNumber = 2346352; // Your ThingSpeak channel ID
const char* myApiKey = "ZMCX8SZQCM26KHMM"; // Your ThingSpeak API key
const char* server = "api.thingspeak.com";
// Mapping GPIO <--> DHT Pin
const byte dhtPin = 15;
const byte led1 = 23;
const byte buzz = 12;
#define MQ2 35 // define MQ2 analog pin
#define NOTE_FS5 800
#define NOTE_REST 0
int melody[] = {
NOTE_FS5, NOTE_FS5, NOTE_FS5, NOTE_FS5, NOTE_FS5, NOTE_FS5, NOTE_FS5, NOTE_FS5, NOTE_FS5, NOTE_FS5, NOTE_FS5, NOTE_REST
};
int noteDurations[] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
};
float temperature = 0.0, humidity = 0.0;
WiFiClient client;
int gas;
void setup() {
Serial.begin(115200); // Initialize serial
pinMode(led1, OUTPUT);
pinMode(buzz, OUTPUT);
pinMode(MQ2, INPUT);
dht.setup(dhtPin, DHTesp::DHT22);
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);
}
void loop() {
humidity = dht.getHumidity();
temperature = dht.getTemperature();
gas = analogRead(MQ2);
ThingSpeak.setField(1, temperature);
ThingSpeak.setField(2, humidity);
ThingSpeak.setField(3, gas);
Serial.printf("Gas: %d\n", gas);
Serial.println("Temp: " + String(temperature, 2) + "°C");
Serial.println("Humidity: " + String(humidity, 1) + "%");
if (gas > 480 || temperature > 50) {
Serial.println("Dangerous conditions!");
Serial.println("---");
for (int i = 0; i < sizeof(melody) / sizeof(melody[0]); i++) {
digitalWrite(led1, HIGH);
delay(100);
digitalWrite(led1, LOW);
delay(1000);
int noteDuration = 100 / noteDurations[i];
if (melody[i] != NOTE_REST) {
tone(buzz, melody[i], noteDuration);
}
delay(noteDuration);
noTone(buzz);
}
}
// Upload data to ThingSpeak
int httpCode = ThingSpeak.writeFields(myChannelNumber, myApiKey);
if (httpCode == 200) {
Serial.println("Channel update successful");
} else {
Serial.println("Error updating channel. HTTP code: " + String(httpCode));
}
delay(15000); // Delay for 15 seconds (adjust as needed)
}