CTRL library / Object groups

Grouped buttons

This sketch demonstrates the grouping of buttons, with a shared event handler.

Groups offer another way to handle a large number of buttons. They let you use one shared event handler. If we then provide the buttons with some data, in the form of setters: setInteger(), setString() & setBoolean(), we can retrieve this data in the event handler and take action based on this data. Getting the data is done with the following getters: getInteger(), getString() & getBoolean().

The code

grouped_buttons.ino
#include <CtrlGroup.h>#include <CtrlBtn.h> // Create a button group.CtrlGroup buttonGroup; // Create 2 buttons with: pin number & bounce duration.CtrlBtn button1(2, 15);CtrlBtn button2(3, 15); // Define an onPress handler. This will be triggered by all buttons registered to the group.void onPress(Groupable& button) {  // Retrieve the variables we need within this handler.  bool canPrint = button.getBoolean("canPrint");  int id = button.getInteger("id");  String name = button.getString("name");  // if the button can print, we print to the serial monitor.  if (canPrint) {    Serial.print("Pressed button with id: ");    Serial.print(id);    Serial.print(" / Name: ");    Serial.println(name);  }} void setup() {  Serial.begin(9600);   // Register the onPress handler with the group.  buttonGroup.setOnPress(onPress);   // Register the buttons to the group.  button1.setGroup(&buttonGroup);  button2.setGroup(&buttonGroup);   // Set all variables needed for button 1 & 2.  button1.setInteger("id", 0);  button1.setString("name", "Button 1");  button1.setBoolean("canPrint", true);  button2.setInteger("id", 1);  button2.setString("name", "Button 2");  button2.setBoolean("canPrint", true);} void loop() {  // Process all buttons registered to the group.  buttonGroup.process();}