Hello
Please note that I am a beginner :)
I am working on a project that needs a relay to be turned on for a preset time. I have written the following code and it works but obviously no other code can run at the same time. I have been trying to use millis() instead but with no success. Can someone give me a hint?
The timer span will be 1 sec - 999 hours or 1 sec - 99 hours. I have not decided yet, will it be some problems with max to be 999 hours? The timer do not need to be very accurate.
It says the millis() will overflow after about 50 days. If I use millis() somehow will this couse any problems if the timer is enabled while the millis overflows after 50 days?
onTime is the time in milliseconds / 10 ( one hundred of a second) that the relay should be on
if (relayState != lastRelayState && onTime > 0) { // See if the state of the relay has changed and if the timer is enabled.
if (relayState == LOW) { // If relay is activated
onTimeCounter = 10; // Reset the counter, this is crucial. Reset to 10 to compensate for 1 second delay.
while (relayState == LOW && onTimeCounter < onTime) { // Loop until timer is reached or the relay is diactivated externally.
onTimeCounter++;
delay(10); //10ms per cycle
relayState = digitalRead(relayPin); // Read the state of the relay if it has been diactivated externally.
}
if (onTimeCounter >= (onTime)-1) { // When timer is reached switch off the relay
changeRelayState(); // Switch of relay
} // End of counter reached
} // End of relay state active
} // End of relay state changed
lastRelayState = relayState; // Reset relay state
Best regards
Andreas