#include <Servo.h>
const int soilMoisturePin = A0; // Pin del sensore di umidità del terreno
const int lightSensorPin = A1; // Pin del fotoresistore
const int servoPin = 9; // Pin del servomotore
const int moistureMin = 300; // Valore umidità minima per azionare l'irrigazione
const int moistureMax = 750; // Valore umidità massima per fermare l'irrigazione
const int lightThresholdNight = 10; // Valore di luminosità al tramonto
const int lightThresholdDayMin = 2000; // Valore di luminosità minimo durante il giorno
Servo servo;
unsigned long startTime = 0;
int irrigationState = 0; // 0 = OFF, 1 = ON
void setup() {
Serial.begin(9600);
servo.attach(servoPin);
servo.write(0); // Valvola chiusa
}
void loop() {
int soilMoisture = analogRead(soilMoisturePin);
int lightLevel = analogRead(lightSensorPin);
// Avvio irrigazione
if (irrigationState == 0) {
if (soilMoisture < moistureMin && lightLevel <= lightThresholdNight) {
servo.write(90); // Aprire la valvola
startTime = millis();
irrigationState = 1;
Serial.println("Irrigazione ON");
}
}
// Fermare irrigazione
if (irrigationState == 1) {
if (soilMoisture >= moistureMax) {
servo.write(0); // Chiudere la valvola
unsigned long duration = (millis() - startTime) / 60000; // Durata in minuti
irrigationState = 0;
Serial.print("Irrigazione OFF - Durata: ");
Serial.print(duration);
Serial.println(" minuti");
}
}
delay(1000); // Attendere un secondo prima di rilevare nuovamente
}