#include <DHT.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h> // Include the Servo library
#define DHTPIN 12 // Pin connected to DHT11 sensor
#define DHTTYPE DHT22 // DHT 11
#define servoPin 9 // PWM pin connected to the servo
DHT dht(DHTPIN, DHTTYPE); // Initialize DHT sensor
LiquidCrystal_I2C lcd(0x27, 16, 2); // Initialize I2C LCD with address 0x27, 16 columns, and 2 rows
byte degree[8] = {
B00100,
B01010,
B00100,
B00000,
B00000,
B00000,
B00000,
B00000
};
Servo myServo; // Create a Servo object
void setup() {
lcd.begin(16, 2); // Initialize the LCD with 16 columns and 2 rows
lcd.createChar(1, degree); // Create a custom degree symbol
lcd.clear(); // Clear LCD screen
lcd.print("Temperature-Based"); // Display initial message
lcd.setCursor(0, 1);
lcd.print("Fan Speed Controller");
delay(2000);
myServo.attach(servoPin); // Attach the servo to the specified pin
myServo.write(0); // Set the initial position of the servo
lcd.clear();
lcd.print("Detecting.....");
delay(2000);
Serial.begin(9600); // Initialize serial communication
dht.begin(); // Start DHT sensor
}
void loop() {
// Read temperature and humidity from DHT sensor
float h = dht.readHumidity(); // Read humidity
float t = dht.readTemperature(); // Read temperature in Celsius
float f = dht.readTemperature(true); // Read temperature in Fahrenheit
// Check if any reads failed
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Compute heat index
float hi = dht.computeHeatIndex(f, h);
// Print temperature and humidity readings to the serial monitor
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" ");
Serial.print((char)223); // Degree symbol
Serial.print("C ");
Serial.print(f);
Serial.print(" ");
Serial.print((char)223); // Degree symbol
Serial.print("F\t");
Serial.print("Heat index: ");
Serial.print(hi);
Serial.print(" ");
Serial.print((char)223); // Degree symbol
Serial.println("F");
// Display temperature and humidity on the I2C LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(t);
lcd.print((char)223); // Degree symbol
lcd.print("C ");
lcd.setCursor(0, 1);
// Calculate fan speed based on temperature range
int fanSpeed = map(t, 20, 30, 0, 100);
// Control servo position based on temperature
int servoPosition = map(t, 20, 30, 0, 180); // Map temperature to servo position (0-180 degrees)
myServo.write(servoPosition); // Set the servo to the calculated position
// Display fan speed on the I2C LCD
lcd.setCursor(0, 1);
lcd.print("Fan Speed: ");
lcd.print(fanSpeed);
lcd.print("%");
delay(3000); // Delay between readings
}