Looping functions with buttons

Hi everyone!

I am at beginner level with Arduino and have a question about using buttons to switch programs.

I want to create a project using three buttons to activatie three programs. I want the program to continue to loop until another button is pressed. So let's say that I want to turn on a LED when the red button is pressed, but want it to continue to loop until the yellow button is pressed, which turns on another sequence. How do I begin to do this?

So for example:

3 buttons (Red, yellow and green)
1 LED light

When red is pressed, the led starts to blink with intervals of 1 second, continuing until another button is pressed
When yellow is pressed, the LED starts to blink with intervals of 2 seconds, continuing until another button is pressed
When green is pressed, the LED starts to blink with intervals of 3 seconds until another button is pressed.

How can I best do this?

Start simple. Write a sketch that prints

  I see you pressed the red button.

when you press the red button, and same same for yellow and green.

You will need to learn how to debounce a pushbutton, and react to a change in the state of a button pressed or not pressed.

A good example and tutorial are on offer in the IDE, see

Files/Examples/02.Digital/StateChangeDetection

and google

Arduino state change detection

to find the official article

Once you can reliably detect a button getting pressed, you can use that to set a mode variable that might be used to select one section or another or another to execute, until the mode changes again you pressed a button.

HTH

a7

1 Like

It will actually only be one single program - but that one program will do different things depending on the buttons.

Yep! Had a little trouble translating it in the right way :wink: But you're totally right!

1 Like

Hello abrouwer

Welcome to the worldbest Arduino forum ever.

You might start with the BlinkWithOutDelay example of the IDE.

This example can be modified to your needs easily by using an array for the timing requirements.

Have a nice day and enjoy coding in C++.

As noted above, You have to learn and understand a couple of things…

  1. the ‘kright’ way to detect button presses. (state change)

  2. the most efficient way to blink LEDs (with millis delay)

  3. how to vary the blink interval without waiting or ‘blocking’ the ‘next’ button.
    -(using variables instead of constants)

Treat them separately as learning lessons…
All three are extremely useful skills to learn for future projects as wee

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.