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:

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:

One button multiple purpose

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
Please note: These are Amazon affiliate links. If you buy the components through these links, We will get a commission at no extra cost to you. We appreciate it.

The Best Arduino Starter Kit

※ OUR MESSAGES