Hey guys!
I've got a long program for a gardening system running on an Arduino Nano and it's supposed to turn on and off the grow lights at set times. It calculates the time it should turn on and off the grow lights depending on what I am growing and the length of the plant (which affects how strong light the plant gets). However when it needs more time than 20 hours per day, it is still supposed to cap that time to 20 hours to ensure the plants get at least 4 hours of night each day, but for some reason my grow lights runs 24/7 still.
I really can't seem to figure it out and have been at this for an eternity.
Can perhaps someone here see if there's something obvious I've missed?
Code below, the light control function is called LightTimer. Thanks!
void LightTimer(int current_hour, int current_minute){
float halftime = on_hours/2;
// Function for emulating daylight using RTC time function and LED lights
if (current_minute != last_lightminute) {
if (current_hour < (13-halftime) || current_hour > (12+halftime)) { // Eg. halftime = 8 gives current_hour < 5 OR current_hour > 20
if (current_hour > 21 || current_hour < 7) {
digitalWrite(mushlight_pin, LOW);
}
else {
digitalWrite(mushlight_pin, HIGH);
}
digitalWrite(growlight_pin, LOW);
digitalWrite(fan_pin, LOW);
}
else if (current_hour > (12-halftime) && current_hour < (13+halftime)) { // Eg. halftime = 8 gives current_hour > 4 AND current_hour < 21
if (mode == 1) {
digitalWrite(mushlight_pin, HIGH);
digitalWrite(growlight_pin, LOW);
digitalWrite(fan_pin, LOW);
}
else if (mode == 2) {
digitalWrite(mushlight_pin, HIGH);
digitalWrite(growlight_pin, HIGH);
digitalWrite(fan_pin, HIGH);
}
}
last_lightminute = current_minute;
}
}
void nap(int msec){
// Pause function
unsigned long currentMillis;
unsigned long previousMillis = millis(); // Setting starting time
while (true) {
currentMillis = millis();
if (currentMillis - previousMillis >= msec) {
break;
}
}
}
Ok so found it haha.. I was overwriting the on_hours after setting it to a max 20. Silly me
What did you mean by this? :
Is this a bad solution?
I did this because I want to port the system to an ESP32 when it is finally delivered here, and use OTA updates but then I can't use delay() as I understand.
void nap(int msec){
// Pause function while using OTA
unsigned long currentMillis;
unsigned long previousMillis = millis(); // Setting starting time
do {
// OTA
currentMillis = millis();
ArduinoOTA.handle();
}
while (currentMillis - previousMillis >= msec);
}
Is that still bad, or is there a better way to do this? Maybe the state-machine way as LarryD suggested?