How to use push-button as on-off switch

How to use push-button as on-off switch in Arduino?

Answer

The below Arduino code uses a push-button as an on-off switch

Arduino Code

#include <ezButton.h> #define SWITCH_OFF 0 #define SWITCH_ON 1 ezButton button(7); // create ezButton object that attach to pin 7; int switch_state = SWITCH_OFF; // initial state void setup() { Serial.begin(9600); button.setDebounceTime(50); // set debounce time to 50 milliseconds } void loop() { button.loop(); // MUST call the loop() function first if (button.isPressed()) { // change state of switch if (switch_state == SWITCH_OFF) switch_state = SWITCH_ON; else switch_state = SWITCH_OFF; Serial.print("switch's state -> "); Serial.println(switch_state); } //Serial.print("switch's state: "); //Serial.println(switch_state); }

Wiring Diagram for the above code

Arduino Button Wiring Diagram

This image is created using Fritzing. Click to enlarge image

Quick Steps

Arduino button library
Arduino IDE Upload Code
COM6
Send
switch's state -> 1 switch's state -> 0 switch's state -> 1 switch's state -> 0 switch's state -> 1 switch's state -> 0 switch's state -> 1
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

※ NOTE THAT:

The above code debounces for the button. See why do we need to debounce for button

You can also refer to the following tutorials:

Buy Arduino

1 × Arduino UNO Buy on Amazon
1 × USB 2.0 cable type A/B 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.

The Best Arduino Starter Kit

※ OUR MESSAGES