#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <DHT.h>
#define DHTTYPE DHT11
#define DHTPin 15
#define FAN_PIN 12
#define BUZZER_PIN 14
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* weatherURL = "http://api.openweathermap.org/data/2.5/weather?q=Cape%20Town&appid=8afe6ff51a633adf969759388762328a&units=metric";
DHT dht(DHTPin, DHTTYPE);
unsigned long lastSensorRead = 0;
unsigned long lastWeatherFetch = 0;
const unsigned long interval = 10000; // 10 seconds
float localTemp = 0.0;
float externalTemp = 0.0;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi connected");
dht.begin();
delay(2000); // Let the sensor stabilize
pinMode(FAN_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
analogWrite(FAN_PIN, 0); // Start with fan off
digitalWrite(BUZZER_PIN, LOW); // Start with buzzer off
}
void fetchWeatherData() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(weatherURL);
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
String payload = http.getString();
Serial.println("\n[OpenWeatherMap JSON]");
Serial.println(payload);
const size_t capacity = 1024;
DynamicJsonDocument doc(capacity);
deserializeJson(doc, payload);
externalTemp = doc["main"]["temp"];
float extHum = doc["main"]["humidity"];
Serial.print("External Temp: ");
Serial.print(externalTemp);
Serial.println(" °C");
Serial.print("External Humidity: ");
Serial.print(extHum);
Serial.println(" %");
} else {
Serial.print("HTTP request failed. Code: ");
Serial.println(httpResponseCode);
}
http.end();
}
}
void readSensorData() {
float h = dht.readHumidity();
localTemp = dht.readTemperature();
if (isnan(h) || isnan(localTemp)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Local Temperature: ");
Serial.print(localTemp);
Serial.println(" °C");
Serial.print("Local Humidity: ");
Serial.print(h);
Serial.println(" %");
controlFanAndBuzzer(localTemp);
}
void controlFanAndBuzzer(float temperature) {
if (temperature >= 30.0) {
analogWrite(FAN_PIN, 255); // Max speed
digitalWrite(BUZZER_PIN, HIGH); // Alert
} else if (temperature >= 25.0) {
analogWrite(FAN_PIN, 128); // Medium speed
digitalWrite(BUZZER_PIN, LOW);
} else {
analogWrite(FAN_PIN, 0); // Fan off
digitalWrite(BUZZER_PIN, LOW);
}
}
void loop() {
unsigned long now = millis();
if (now - lastSensorRead > interval) {
lastSensorRead = now;
readSensorData();
}
if (now - lastWeatherFetch > 60000) { // Fetch weather every 60 seconds
lastWeatherFetch = now;
fetchWeatherData();
}
}