Skip to main content

Fundamentals

Including the Library

Once the library has been installed, you may include it as shown below.

#include <EasyButton.h>

EasyButton Class

The library exposes the EasyButton class. Create an instance of the class for every button that you have connected.

#define PWR_BTN_PIN 26

#define RST_BTN_PIN 27

EasyButton powerButton(PWR_BTN_PIN);

EasyButton resetButton(RST_BTN_PIN);

Arguments

The following arguments can be passed to the class constructor.

#define PWR_BTN_PIN 26

uint8 debounce = 40;

bool pullup = false;

bool invert = false;

EasyButton powerButton(PWR_BTN_PIN, debounce, pullup, invert);
ArgumentData TypeRequired?Default ValueDescription
pinuint8_tyesn/aArduino pin number where the button is connected.
debounce_timeuint32_tno35Period of time to make sure the pushbutton is definitely pressed. Please refer to debounce.
pullup_enableboolnotrueEnable internal pullup resistor. Please refer to digital pins. If using ESP32, please see the note below.
invertboolnotrueInvert button logic. If true, low = pressed else high = pressed. Please refer to invert.
Note

If using ESP32, be aware that some of the pins does not have software pull-up/pull-down functionalities. In that case, use an external pull-up resistor, 10K works well. Please refer to Pull-up Resistors.

Initializing a button

Initialize the button by calling the method begin within the setup function.

void setup() {
powerButton.begin();
}

Update Button State

Poll

Continuously read the state of the button.

void loop() {
powerButton.read();
}

External interrupts

Defining interruption service routine

void buttonISR()
{
//When button is being used through external interrupts, parameter INTERRUPT must be passed to read() function
powerButton.read(INTERRUPT);
}

Enabling external interrupt

if (powerButton.supportsInterrupt())
{
powerButton.enableInterrupt(buttonISR);
}

Callbacks

EasyButton allows you to attach callback functions to certain button events. Use callback functions to run specific code when the event gets triggered. Attach callback functions within the setup function.

void onPressed() {
Serial.println("Power button has been pressed!");
}

void setup() {
// onPressed function will be called when the onPressed event of the button gets triggered.
powerButton.onPressed(onPressed);
}