#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>
#define DHTPIN 2 // Pin where the DHT11 is connected
#define DHTTYPE DHT11 // DHT 11
#define SOIL_MOISTURE_PIN A0 // Pin where the soil moisture sensor is connected
#define RELAY_PIN 3 // Pin where the relay is connected
#define BUTTON_PIN 4 // Pin where the button is connected
#define SPEAKER_PIN 9 // Pin where the speaker is connected
#define LDR_PIN A1 // Pin where the photoresistor is connected
DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal_I2C lcd(0x27, 16, 2); // Set the LCD address to 0x27 for a 16 chars and 2 line display
int soilMoistureValue = 0;
int ldrValue = 0;
float temperature = 0;
float humidity = 0;
bool relayState = false;
void setup() {
// Initialize the LCD
lcd.begin(16, 2); // Specify the dimensions of the LCD
lcd.backlight();
// Display welcome message
lcd.setCursor(0, 0);
lcd.print("Smart Garden");
lcd.setCursor(0, 1);
lcd.print("Initializing...");
delay(3000); // Show the message for 3 seconds
// Initialize the DHT sensor
dht.begin();
// Set up the pin modes
pinMode(SOIL_MOISTURE_PIN, INPUT);
pinMode(RELAY_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(SPEAKER_PIN, OUTPUT);
pinMode(LDR_PIN, INPUT);
// Start with the relay off
digitalWrite(RELAY_PIN, LOW);
}
void loop() {
// Read the soil moisture level
soilMoistureValue = analogRead(SOIL_MOISTURE_PIN);
// Read the temperature and humidity
temperature = dht.readTemperature();
humidity = dht.readHumidity();
// Read the LDR value
ldrValue = analogRead(LDR_PIN);
// Display the values on the LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(temperature);
lcd.print("C ");
lcd.print("Hum: ");
lcd.print(humidity);
lcd.print("%");
lcd.setCursor(0, 1);
lcd.print("Soil: ");
lcd.print(soilMoistureValue);
lcd.print(" LDR: ");
lcd.print(ldrValue);
// Check soil moisture level and control the relay
if (soilMoistureValue < 500) { // Adjust the threshold as needed
digitalWrite(RELAY_PIN, HIGH);
relayState = true;
tone(SPEAKER_PIN, 1000); // Play a tone when watering
} else {
digitalWrite(RELAY_PIN, LOW);
relayState = false;
noTone(SPEAKER_PIN);
}
// Check if the button is pressed to manually control the relay
if (digitalRead(BUTTON_PIN) == LOW) {
relayState = !relayState; // Toggle the relay state
digitalWrite(RELAY_PIN, relayState ? HIGH : LOW);
delay(300); // Debounce delay
}
delay(2000); // Wait 2 seconds before the next loop
}