Control Surface stm32
MIDI Control Surface library for Arduino
Button.cpp
Go to the documentation of this file.
1#include "Button.hpp"
2
3AH_DIAGNOSTIC_WERROR() // Enable errors on warnings
4
6
7Button::Button(pin_t pin) : pin(pin) {}
8
9void Button::begin() { ExtIO::pinMode(pin, INPUT_PULLUP); }
10
11void Button::invert() { state.invert = true; }
12
13Button::State Button::update() {
14 // Read pin state and current time
15 bool input = ExtIO::digitalRead(pin) ^ state.invert;
16 unsigned long now = millis();
17 // Check if enough time has elapsed after last bounce
18 if (state.bouncing)
19 state.bouncing = now - state.prevBounceTime <= debounceTime;
20 // Shift the debounced state one bit to the left, either appending the
21 // new input state if not bouncing, or repeat the old state if bouncing
22 bool prevState = state.debounced & 0b01;
23 bool newState = state.bouncing ? prevState : input;
24 state.debounced = (prevState << 1) | newState;
25 // Check if the input changed state (button pressed, released or bouncing)
26 if (input != state.prevInput) {
27 state.bouncing = true;
28 state.prevInput = input;
29 state.prevBounceTime = now;
30 }
31 return getState();
32}
33
34Button::State Button::getState() const {
35 return static_cast<State>(state.debounced);
36}
37
38FlashString_t Button::getName(Button::State state) {
39 switch (state) {
40 case Button::Pressed: return F("Pressed");
41 case Button::Released: return F("Released");
42 case Button::Falling: return F("Falling");
43 case Button::Rising: return F("Rising");
44 default: return F("<invalid>"); // Keeps the compiler happy
45 }
46}
47
48unsigned long Button::previousBounceTime() const {
49 return state.prevBounceTime;
50}
51
52unsigned long Button::stableTime(unsigned long now) const {
53 return now - previousBounceTime();
54}
55
56unsigned long Button::stableTime() const { return stableTime(millis()); }
57
58void Button::setDebounceTime(unsigned long debounceTime) {
59 Button::debounceTime = debounceTime;
60}
61
62unsigned long Button::getDebounceTime() { return Button::debounceTime; }
63
64unsigned long Button::debounceTime = BUTTON_DEBOUNCE_TIME;
65
67
#define END_AH_NAMESPACE
#define BEGIN_AH_NAMESPACE
constexpr PinMode_t INPUT_PULLUP
std::remove_reference< decltype(*F(""))>::type * FlashString_t
#define AH_DIAGNOSTIC_POP()
Definition: Warnings.hpp:37
#define AH_DIAGNOSTIC_WERROR()
Definition: Warnings.hpp:36
A class for reading and debouncing buttons and switches.
Definition: Button.hpp:18
State
An enumeration of the different states a button can be in.
Definition: Button.hpp:48
void pinMode(pin_t pin, PinMode_t mode)
An ExtIO version of the Arduino function.
PinStatus_t digitalRead(pin_t pin)
An ExtIO version of the Arduino function.
constexpr unsigned long BUTTON_DEBOUNCE_TIME
The debounce time for momentary push buttons in milliseconds.
uint16_t pin_t
The type for Arduino pins (and ExtendedIOElement pins).