button icon indicating copy to clipboard operation
button copied to clipboard

Add array of struct ezButtonExample

Open drf5n opened this issue 6 months ago • 0 comments

Expanding on the examples in https://forum.arduino.cc/t/for-beginners-the-simple-way-to-program-for-multiple-buttons-code-example/629651 and https://github.com/ArduinoGetStarted/button/blob/master/examples/07.ButtonArray/07.ButtonArray.ino , I wrote an example using an array of structs with ezButtons as elements. It might be nice to add as an example.

/* an ezButton demo using an array of structures
  Build from https://forum.arduino.cc/t/for-beginners-the-simple-way-to-program-for-multiple-buttons-code-example/629651
  and its array of buttons example from
  https://github.com/ArduinoGetStarted/button/blob/master/examples/07.ButtonArray/07.ButtonArray.ino

  Wokwi demo: https://wokwi.com/projects/405606656376410113
*/

#include <ezButton.h> // https://github.com/ArduinoGetStarted/button

struct MyButtonsStruct {
  ezButton ezb;
  byte pin;
  char * name;
  char * desc;
  char * pressMessage;
  char * releaseMessage;
};

MyButtonsStruct myButtons[] = {
  { ezButton(2), 2, "Green/2", "Start the device", "starting...", "started."},
  { ezButton(3), 3, "Red/3", "Stop the device", "stopping...", "stopped"},
  { ezButton(4), 4, "Blue/4", "Increment", "filling...", "filled"},
  { ezButton(5), 5, "Yellow/5", "Decrement", "draining...", "drained"},
  { ezButton(6), 6, "Gray/6", "Accept", "Submitting...", "accepted"}
};

const int BUTTON_NUM = sizeof(myButtons) / sizeof(myButtons[0]);

void setup() {
  Serial.begin(115200);

  for (byte i = 0; i < BUTTON_NUM; i++) {
    Serial.print("Enabling ");
    Serial.print(myButtons[i].name);
    Serial.print(" as ");
    Serial.println(myButtons[i].desc);
    myButtons[i].ezb.setDebounceTime(50); // set debounce time to 50 milliseconds
  }
}

void loop() {
  for (byte i = 0; i < BUTTON_NUM; i++) { // read all the input buttons
    myButtons[i].ezb.loop(); // MUST call the loop() function first
  }

  for (byte i = 0; i < BUTTON_NUM; i++) { // process all the buttons
    if (myButtons[i].ezb.isPressed()) {
      Serial.print("The ");
      Serial.print(myButtons[i].name);
      Serial.print(" button ");
      Serial.print(myButtons[i].pin);
      Serial.print(" is pressed. ");
      Serial.println(myButtons[i].pressMessage);
    }
    if (myButtons[i].ezb.isReleased()) {
      Serial.print("The ");
      Serial.print(myButtons[i].name);
      Serial.print(" button ");
      Serial.print(myButtons[i].pin);
      Serial.print(" is released. ");
      Serial.println(myButtons[i].releaseMessage);
    }
  }
}

There is a live demo here:

https://wokwi.com/projects/405606656376410113

drf5n avatar Aug 08 '24 01:08 drf5n