I have written (with the help of many) a sketch in which I can change the time of a clock with the press of a button. The only problem is that I have a delay in the void loop and this delay messes up the timekeeping qualities of the clock.
void loop()
{
{
if (digitalRead(HourSet) == 0)
{
clockHourSet++;
delay(100); // Delay so the numbers do not change too quickly
}
if (digitalRead(MinsSet) == 0)
{
clockMinSet++;
delay(100);
}
}
What I'm looking for is a sketch that would allow me to change the time without adding a delay to the loop and would have the numbers change at a reasonable pace.
How to do what you want depends on whether you want the time to change continuously when the switch is held down, or only one hour or minute increment per button press.
You can use the millis() function to determine whether it is time to increment again, if you want continuous incrementing. You'll need to record, of course, when the last increment occurred, in order to know whether it is time to increment again.
My plan is to have two time set buttons that increase the time for every press of the button or change when the button is held down. What is a good way to accomplish this?
If you want to really optimize it you could check which if condition takes more cycles, so the test would fail faster. You might win a few micro seconds
if (millis() - lastMinSet > 100)
{
if (digitalRead(MinsSet) == 0)
{
clockMinSet++;
if (clockMinSet == 60) clockMinSet = 0;
lastMinSet = millis();
}
}
How should I go about the lastHour/MinSet? I understand that I have to have an 'int'
Then, I'm sorry, but you don't understand correctly. Look at the millis() function documentation. Nowhere on that page does it mention millis() returning anything other than an unsigned long.
Why not just make a note of the time when you enter the method that adjusts the time, then when you leave that method figure out how much time has passed and then make an adjustment. That will let you keep your delay() calls, as in this case they don't really hurt anything.