#include <DHT.h>
#include <WiFi.h>
#include <ThingSpeak.h>
#define PIR_PIN 14
#define DHTPIN 27 // Pin connected to DHT sensor
#define DHTTYPE DHT22 // DHT 22 sensor
#define Buzzer 4 //buzzer pin
DHT dht(DHTPIN, DHTTYPE);
WiFiClient client;
// Replace with your ThingSpeak Channel ID and API Key
const unsigned long channelId = 2434125;
const char *apiKey = "MAS41LH1LA8UYAV4";
void setup() {
Serial.begin(9600);
Serial.print("Connecting to WiFi");
WiFi.begin("Wokwi-GUEST", "", 6);
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println(" Connected!");
dht.begin();
// Initialize ThingSpeak
ThingSpeak.begin(client);
pinMode(Buzzer, OUTPUT);
pinMode(PIR_PIN, INPUT);
}
void loop() {
// Reading temperature or humidity takes about 250 milliseconds!
float humidity = dht.readHumidity();
// Read temperature as Celsius (the default)
float temperature = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
//float t = dht.readTemperature(true);
// Check if any reads failed and exit early (to avoid NaN)
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Show humidity data in percentage
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print("% ");
// Show temperature data in Celsius
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println("°C");
int motion = digitalRead(PIR_PIN);
if (motion == HIGH) {
Serial.println("Motion detected!");
}
else {
Serial.println("No motion.");
}
if((temperature<15||temperature>30) || (humidity<30||humidity>60)){
Serial.println("Alert!!!");
digitalWrite(Buzzer, HIGH);
delay(1000);
digitalWrite(Buzzer, LOW);
delay(1000);
}
// set the fields with the values
ThingSpeak.setField(1, temperature);
ThingSpeak.setField(2, humidity);
// Update ThingSpeak channel with sensors data
ThingSpeak.writeFields(channelId, apiKey);
delay(2000);
}