One button for multiple functions
I want to use only one button for multiple purposes. For example, the first press, do task 1. The second press, do task 2. The third presss, do the task 3. This process is repeated.
Answer
In general, there are two ways for a single button to do multiple functions:
- If there are only two functions, we can use the long press and short press to do the two seperate tasks.
- If there are two or more functions, we can use the button press's count to do multiple tasks.
The below example shows how to use a single button to do three different tasks based on the press's count.
#include <ezButton.h>
ezButton button(7); // create ezButton object that attach to pin 7;
unsigned long lastCount = 0;
unsigned long count = 0;
void setup() {
Serial.begin(9600);
button.setDebounceTime(50); // set debounce time to 50 milliseconds
button.setCountMode(COUNT_FALLING);
}
void loop() {
button.loop(); // MUST call the loop() function first
count = button.getCount();
if (count != lastCount) {
Serial.println(count);
int countIn3 = count % 3 + 1;
switch (countIn3) {
case 1:
// TO DO TASK 1
break;
case 2:
// TO DO TASK 2
break;
case 3:
// TO DO TASK 3
break;
}
lastCount = count;
}
}
The wiring diagram for above code:
This image is created using Fritzing. Click to enlarge image
※ NOTE THAT:
The above code uses the ezButton library, you can see how to install the library
Hardware for above code
1 × Arduino UNO Buy on Amazon | |
1 × USB 2.0 cable type A/B Buy on Amazon | |
1 × Button Buy on Amazon | |
1 × Breadboard Buy on Amazon | |
1 × Jumper Wires Buy on Amazon |
Disclosure: Some links in this section are Amazon affiliate links. If you make a purchase through these links, we may earn a commission at no extra cost to you.
Additionally, some links direct to products from our own brand, DIYables.
Additionally, some links direct to products from our own brand, DIYables.