To detect a short and long button press using millis can give your project more functionality without adding more buttons. In this line-by-line example, I show how to react to a user pressing a button for a short period (100ms) or a long period (over 500ms). My example changes the blink rate of an LED on short presses. A long button press turns off the LED.
In the code, I make use of a struct so that a single variable can be used to track multiple parameters. The benefit of this method is that adding multiple buttons is easy. You could create an array of these tyepdef’d variables.
It’s a well-known fact of engineering: LEDs make everything look better. And that means a Fading LED is even better. Using Arduino’s analogWrite(), fading a LED is just a matter of a loop. If you use delay(), you can’t easily add other actions. What can you do? Well, Fading a LED with millis() is pretty simple. Here’s the code to do it and a quick explanation.
One of the common questions related to using the millis() function in Arduino, is around timed events. After an event occurs, you want the code to wait for some time before doing the next step. But you don’t want to stop the program with delay().
[featured-image link=”https://www.baldengineer.com/use-millis-with-buttons-to-delay-events.html” single_newwindow=”false”]
In this example, we will use millis() to wait a few seconds after a pushbutton press to turn on an LED. Then a few seconds later, we will turn it off. All without using delay().
The Arduino millis() function will let you accomplish this delayed action relatively easily. First, read through my multitasking with millis() tutorial and then look at some of my millis() cookbook examples I’ve already posted. Getting used to seeing this kind of code will make this line by line tutorial on timed events using millis() easier to follow.
The Arduino is fast, humans are slow. When you push down a button, what seems like a single change to slow humans is really multiple presses to an Arduino. This is known as “bouncing.” Figure 1 is an oscilloscope screenshot showing what could happen when a button is pressed.
A popular LED project is the “Larson Scanner.” This scanner emulates the effect seen on KIT from Knight Rider and the Cylons in Battlestar Galactica. The code is usually written using “delay()” which means you can’t combine it with anything else. The following code could be put into a function, called periodically and allow your code to scan while doing other things.