#include <Servo.h>
#include "DHT.h"
// Pin Definitions
#define DHTPIN 2
#define DHTTYPE DHT22
#define SOIL_SENSOR A0
#define WATER_PUMP 8
#define HEATER 7
#define VENT_SERVO_PIN 9
// Initialize DHT Sensor and Servo Motor
DHT dht(DHTPIN, DHTTYPE);
Servo ventServo;
void setup() {
// Initialize Serial Monitor
Serial.begin(9600);
// Start the DHT sensor
dht.begin();
// Pin Modes
pinMode(SOIL_SENSOR, INPUT);
pinMode(WATER_PUMP, OUTPUT);
pinMode(HEATER, OUTPUT);
// Attach the Servo Motor
ventServo.attach(VENT_SERVO_PIN);
ventServo.write(0); // Vent starts closed
Serial.println("Smart Greenhouse System Initialized");
}
void loop() {
// Read temperature and humidity from the DHT sensor
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
// Read soil moisture from the sensor
int soilMoisture = analogRead(SOIL_SENSOR);
// Error check for the DHT sensor
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Display sensor readings on the Serial Monitor
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println("°C");
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println("%");
Serial.print("Soil Moisture: ");
Serial.println(map(soilMoisture, 0, 1023, 0, 100)); // Convert to percentage
// *** Actuator Logic ***
// 1. Temperature Control
if (temperature > 30) {
ventServo.write(90); // Open the vent
Serial.println("Vent opened");
} else if (temperature < 20) {
digitalWrite(HEATER, HIGH); // Turn on heater
Serial.println("Heater ON");
} else {
ventServo.write(0); // Close the vent
digitalWrite(HEATER, LOW); // Turn off heater
Serial.println("Vent closed, Heater OFF");
}
// 2. Soil Moisture Control
if (soilMoisture < 300) { // Adjust threshold for dry soil
digitalWrite(WATER_PUMP, HIGH); // Activate water pump
Serial.println("Water Pump ON");
delay(10000); // Keep the pump running for 10 seconds
digitalWrite(WATER_PUMP, LOW); // Turn off the pump
Serial.println("Water Pump OFF");
}
// 3. Humidity Alert
if (humidity < 50) {
Serial.println("Warning: Humidity too low!");
}
// Delay before the next loop iteration
delay(5000);
}