Buttons

Alternative button

This sketch demonstrates an alternative implementation of a pull-up button or switch, with debouncing functionality for noisy buttons.

With this alternative approach you can instantiate all your objects first, while setting the handlers at a later point. This is especially handy in larger projects where you have to access other objects from the handlers. And you can't access an object if it hasn't been instantiated yet (and you might not want to use 'forward declaration'). To illustrate this problem further, in the approach described in the basic example you will quickly run into problems as you have to keep track of the order of instantiation, which can become messy very quickly.


The code

#include <CtrlBtn.h>

// Create a button with the signal pin number & bounce duration.
CtrlBtn button(1, 15);

// Define an onPress handler.
void onPress() {
  Serial.println("Alternative button pressed");
}

// Define an onRelease handler.
void onRelease() {
  Serial.println("Alternative button released");
}

void setup() {
  Serial.begin(9600);
  // Register the handlers with the button object.
  button.setOnPress(onPress);
  button.setOnRelease(onRelease);
  // If you use an external pull-up resistor, uncomment this:
  // button.setPinMode(INPUT, PULL_UP);
  // If you use an external pull-down resistor, uncomment this:
  // button.setPinMode(INPUT, PULL_DOWN);
}

void loop() {
  // The process method will poll the button object and handle all it's functionality.
  button.process();
}
Previous
Pull-down button