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
This image is created using Fritzing. Click to enlarge image
Quick Steps
- Connect Arduino to PC via USB cable
- Open Arduino IDE, select the right board and port
- Navigate to the Libraries icon on the left bar of the Arduino IDE.
- Search “ezButton”, then find the button library by ArduinoGetStarted
- Click Install button to install ezButton library.
- Copy the above code and open with Arduino IDE
- Click Upload button on Arduino IDE to upload code to Arduino
- Press the button several time
- See the switch's state on Serial Monitor
COM6
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
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 |
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.