How to use button to start/stop the loop?

How can I start the loop if a button is pressed, stop the loop if the button is pressed again? This process is repeated forever.

Let's see and compare the code WITHOUT and WITH the start/stop button.

Arduino Code WITHOUT the Start/Stop Button.

void setup() { /******************* * your setup code *******************/ } void loop() { /****************** * your loop code ******************/ }

Arduino Code WITH the Start/Stop Button.

#include <ezButton.h> #define LOOP_STATE_STOPPED 0 #define LOOP_STATE_STARTED 1 ezButton button(7); // create ezButton object that attach to pin 7; int loopState = LOOP_STATE_STOPPED; void setup() { /******************* * your setup code *******************/ button.setDebounceTime(50); // set debounce time to 50 milliseconds } void loop() { button.loop(); // MUST call the loop() function first if (button.isPressed()) { if (loopState == LOOP_STATE_STOPPED) loopState = LOOP_STATE_STARTED; else // if(loopState == LOOP_STATE_STARTED) loopState = LOOP_STATE_STOPPED; } if (loopState == LOOP_STATE_STARTED) { /****************** * your loop code ******************/ } }

The wiring diagram for above code:

How to use button to start/stop program

Image is developed using Fritzing. Click to enlarge image

If you want to use a button to start the program only when the button is pressed the first time, see Arduino - using a button to start the program


  • In this case, we SHOULD debounce the button. If not, the code may not work as expected.