#include <WiFi.h>
#include <DHT.h>
// Define Wi-Fi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// DHT sensor setup
#define DHTPIN 15 // Pin where the DHT22 is connected
#define DHTTYPE DHT22 // Define sensor type as DHT22
DHT dht(DHTPIN, DHTTYPE);
// Define relay (fan) pin
#define RELAY_PIN 13 // Pin for relay (fan control)
// Temperature threshold for activating the fan (prediction threshold)
const float TEMP_THRESHOLD = 30.0; // Temperature in Celsius
// Linear regression model parameters
const float slope = 0.05; // Example slope (m)
const float intercept = -0.5; // Example intercept (b)
// Setup Wi-Fi client
WiFiServer server(80);
void setup() {
// Start serial communication
Serial.begin(115200);
// Connect to Wi-Fi
connectToWiFi();
// Initialize DHT sensor
dht.begin();
// Set relay pin as output
pinMode(RELAY_PIN, OUTPUT);
// Start the server
server.begin();
}
void loop() {
// Read the temperature and humidity from the DHT22 sensor
float temp = dht.readTemperature(); // Get temperature in Celsius
float humidity = dht.readHumidity(); // Get humidity percentage
// Check if the readings are valid
if (isnan(temp) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Print the sensor values
Serial.print("Temperature: ");
Serial.print(temp);
Serial.print("°C, Humidity: ");
Serial.print(humidity);
Serial.println("%");
// Apply the linear regression model to make a decision (whether to turn on the fan)
float prediction = slope * temp + intercept; // Predicted output based on temperature
// Print the prediction value
Serial.print("Predicted Value: ");
Serial.println(prediction);
// Simple decision-making: turn on the fan if predicted value exceeds threshold
if (prediction > 0.5) { // If predicted value > 0.5, turn on the fan
digitalWrite(RELAY_PIN, HIGH); // Turn on the fan
Serial.println("Fan turned ON");
} else {
digitalWrite(RELAY_PIN, LOW); // Turn off the fan
Serial.println("Fan turned OFF");
}
// Delay before reading again
delay(5000); // Wait for 5 seconds before checking again
}
// Connect to Wi-Fi
void connectToWiFi() {
Serial.print("Connecting to Wi-Fi");
WiFi.begin(ssid, password);
// Wait until connected
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Print the IP address once connected
Serial.println();
Serial.print("Connected to Wi-Fi. IP address: ");
Serial.println(WiFi.localIP());
}