#include <DHT.h> // Library for DHT sensor
#include <LiquidCrystal_I2C.h> // Library for LCD
#include <Servo.h> // Library for Servo motor
// DHT22 sensor setup
#define DHTPIN 2 // DHT sensor pin
#define DHTTYPE DHT22 // DHT sensor type
DHT dht(DHTPIN, DHTTYPE);
// LCD setup
LiquidCrystal_I2C lcd(0x27, 16, 2); // LCD address, 16x2 size
// Servo motor setup
Servo flapServo;
#define SERVO_PIN 3 // Servo motor pin
// Thresholds
const float TEMP_HIGH = 40.0; // High temperature threshold (°C)
const float TEMP_LOW = 35.0; // Low temperature threshold (°C)
const float HUMID_HIGH = 75.0; // High humidity threshold (%)
const float HUMID_LOW = 60.0; // Low humidity threshold (%)
// Variables for sensor data
float hum; // Humidity value
float temp; // Temperature value
void setup() {
// Initialize DHT sensor
dht.begin();
// Initialize LCD
lcd.init();
lcd.backlight();
// Initialize Servo motor
flapServo.attach(SERVO_PIN);
flapServo.write(0); // Start with flaps closed
// Display welcome message
lcd.setCursor(0, 0);
lcd.print("Beehive Monitor");
lcd.setCursor(0, 1);
lcd.print("Initializing...");
delay(2000);
lcd.clear();
}
void loop() {
// Read temperature and humidity
hum = dht.readHumidity();
temp = dht.readTemperature();
// Check if readings are valid
if (isnan(hum) || isnan(temp)) {
lcd.setCursor(0, 0);
lcd.print("Sensor Error!");
lcd.setCursor(0, 1);
lcd.print("Retrying...");
delay(2000);
return; // Skip this iteration
}
// Display readings on LCD
lcd.setCursor(0, 0);
lcd.print("Humidity: ");
lcd.print(hum, 1); // Display with 1 decimal place
lcd.print("%");
lcd.setCursor(0, 1);
lcd.print("Temp: ");
lcd.print(temp, 1); // Display with 1 decimal place
lcd.print("C");
// Flap control logic
if (temp >= TEMP_HIGH || hum >= HUMID_HIGH) {
openFlaps(); // Open flaps if temperature or humidity exceeds high threshold
}
else if (temp <= TEMP_LOW && hum <= HUMID_LOW) {
closeFlaps(); // Close flaps if temperature and humidity drop below low threshold
}
delay(2000); // Wait for 2 seconds before next reading
}
// Function to open flaps
void openFlaps() {
lcd.setCursor(0, 1); // Update LCD second row
lcd.print("Flaps: Opening ");
flapServo.write(90); // Rotate servo to open flaps
delay(1000); // Allow time for the flaps to open
}
// Function to close flaps
void closeFlaps() {
lcd.setCursor(0, 1); // Update LCD second row
lcd.print("Flaps: Closing ");
flapServo.write(0); // Rotate servo to close flaps
delay(1000); // Allow time for the flaps to close
}