CountPressedButtons
Example of using the standard library algorithms and the Button class.
- Boards: 🛈
- AVR, AVR USB, Nano Every, Nano 33 IoT, Nano 33 BLE, UNO R4, Pi Pico, Due, Teensy 3.x, ESP8266, ESP32
This sketch reads a number of push buttons or switches, and uses the standard library algorithms to count how many of them are pressed.
The internal pull-up resistors are enabled and the switches are debounced.
Written by PieterP, 2019-11-24
https://github.com/tttapa/Arduino-Helpers
#include <AH/STL/numeric>
Button buttons[] {
2, 3, 4, 5, 6, 7, 8, 9,
};
void setup() {
for (auto &button : buttons)
button.begin();
Serial.begin(115200);
}
void loop() {
auto addOneIfPressed = [](unsigned count, const Button &button) {
return button.getState() == Button::Pressed ? count + 1 : count;
};
for (auto &button : buttons)
button.update();
unsigned pressed =
std::accumulate(std::begin(buttons),
std::end(buttons),
0u,
addOneIfPressed);
Serial.println(pressed);
}
Dummy header file for Arduino builder.