Backlight Timer

I'm considering a backlight timer and am just wondering if there is an easier or better way?

I thought of using two variables: my desired backlight duration and backlight timestamp.

In my loop, I check if (millis - timestamp > duration), send the command to turn backlight off.

The next time through the loop, the condition is still true, so the backlight is sent a redundant "off" command.

My solution is to create a 3rd boolean variable flag and change my if condition to (millis - timestamp > duration && flag)

When I touch a control, the command to turn backlight on is sent, flag = false, timestamp = millis.

As a general practice I avoid booleans, because they are stored as an 8-bit word or an entire byte of precious RAM for very little benefit. For small projects this isn’t a big deal, but as you get more complex, this will become an issue. You know you’re out of RAM when strange erratic behavior begins.

On the other hand, you may find that your LCD is slow to respond or your timers are off if you continue to send redundant commands every trip through the loop.

Here’s a thought:
When you touch the controls, timestamp = millis() + duration;
When you go through the loop if(millis() > timestamp)
send the backlight off command to your backlight and set timestamp = some extremely large number

This way you preserve RAM and avoid redundant commands.

Yes, that is the issue I’m worried about as this is a complex program.

Your solution seems like the redundant off commands sill start up again at some point. I’m expecting the program to run indefinately…

I had thought of changing to, if (millis - timestamp > duration && millis - timestamp < duration + 1000)

However, there are certain conditions where the loop could complete many times in that second, or take a very long time to complete depending on how the instrument is set up (is the maximum long micros 1.2 days?).

The LCD does not handle the repetitive off commands.

Here’s another idea:
When you touch the controls: timestamp = millis() + duration as before.
In the loop, check for millis > timestamp && timestamp != 0
Then set timestamp = 0 when you turn the backlight off. Millis will only be 0 for a millisecond at boot, and the > sign in the if statement ensures that the unusual case of millis and timestamp being 0 together will not be true.

According to the reference docs, millis overflows after about 50 days. If you’re going to be concerned about an instrument running longer than 50 days, it’s worth looking into a real time clock, in my opinion.

Thanks! I think your solution will work perfectly!

I do not need absolute time accuracy. I was just wondering about the micros() overflow, and I now see it's right there obscured right in front of me, 70 minutes. (I did my dimensional analysis wrong, (50days/1000us per ms) * 24hours per day = 1.2 hours)