-
-
Notifications
You must be signed in to change notification settings - Fork 5
Listen for events from multiple buttons
Vladimir Zahradnik edited this page Aug 13, 2019
·
2 revisions
You can listen for events from several buttons in one listener. Even in the same function. Each callback function receives a reference to ObjectButton
instance, from which it can tell, which button was triggered.
Each ObjectButton
instance has a button ID, which corresponds to input pin number used by the button.
To get ID of a button, call ObjectButton#getId()
function:
int input_pin = 13;
ObjectButton button = ObjectButton(input_pin);
// buttonId == input_pin
int buttonId = button.getId();
Let's create an example of a listener receiving events from two distinct buttons.
#include <ObjectButton.h>
#include <interfaces/IOnClickListener.h>
constexpr static byte INPUT_PIN_BUTTON1 = 13;
constexpr static byte INPUT_PIN_BUTTON2 = 14;
class OnClickListener : private virtual IOnClickListener {
public:
OnClickListener() = default;
void init();
void update();
private:
void onClick(ObjectButton &button) override;
// Create two button instances, each bound to different input pin
ObjectButton button1 = ObjectButton(INPUT_PIN_BUTTON1);
ObjectButton button2 = ObjectButton(INPUT_PIN_BUTTON2);
};
void OnClickListener::onClick(ObjectButton &button) {
// Which button was triggered?
switch (button.getId()) {
case INPUT_PIN_BUTTON1:
// Button 1 clicked!
break;
case INPUT_PIN_BUTTON2:
// Button 2 clicked!
break;
}
}
void OnClickListener::init() {
// Initialize the listener
button1.setDebounceTicks(10);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
}
void OnClickListener::update() {
button1.tick();
button2.tick();
}
OnClickListener listener = OnClickListener();
void setup() {
listener.init();
}
void loop() {
listener.update();
}
Notice how we check in onClick()
function, by which button it was triggered.