const int phototransistor = A2 ; // connected to PA2 , A2 in arduino const int mosfet = 7 ; // connected to PA7 , 7 in arduino int photovalue; int treshold = 300; // threshold for the phototransistor bool night = 0; // one time during night int moisture_duration = 15000; // 15 seconde of moisture unsigned long previous_time; unsigned long actual_time; unsigned long interval = 1000 * 3600 * 4; // every 4 hours void setup() { pinMode(phototransistor, INPUT); pinMode(mosfet, OUTPUT); previous_time = millis(); } void loop() { actual_time = millis(); photovalue = analogRead(phototransistor); // after 50 days millis overflow , time should be reset if(actual_time < previous_time){ previous_time = millis(); } // the sun shine if(photovalue < treshold && actual_time > (previous_time + interval)){ digitalWrite(mosfet, HIGH); delay(moisture_duration); digitalWrite(mosfet, LOW); previous_time = millis(); night = 0; } // one time during the night if(photovalue > treshold && actual_time > (previous_time + interval) && night == 0 ){ digitalWrite(mosfet, HIGH); delay(moisture_duration); digitalWrite(mosfet, LOW); previous_time = millis(); night = 1; } }