Line data Source code
1 : #include "Button.hpp" 2 : 3 : BEGIN_CS_NAMESPACE 4 : 5 : using namespace ExtIO; 6 : 7 80 : Button::Button(pin_t pin) : pin(pin) {} 8 : 9 37 : void Button::begin() { ExtIO::pinMode(pin, INPUT_PULLUP); } 10 : 11 0 : void Button::invert() { invertState = true; } 12 : 13 : #ifndef INDIVIDUAL_BUTTON_INVERT 14 : bool Button::invertState = false; 15 : #endif 16 : 17 172 : Button::State Button::update() { 18 : // read the button state and invert it if "invertState" is true 19 172 : bool input = ExtIO::digitalRead(pin) ^ invertState; 20 172 : bool prevState = debouncedState & 0b01; 21 172 : unsigned long now = millis(); 22 172 : if (now - prevBounceTime > debounceTime) { // wait for state to stabilize 23 160 : debouncedState = static_cast<State>((prevState << 1) | input); 24 160 : } else { 25 12 : debouncedState = static_cast<State>((prevState << 1) | prevState); 26 : } 27 172 : if (input != prevInput) { // Button is pressed, released or bounces 28 81 : prevBounceTime = now; 29 81 : prevInput = input; 30 81 : } 31 172 : return debouncedState; 32 : } 33 : 34 0 : Button::State Button::getState() const { return debouncedState; } 35 : 36 0 : const __FlashStringHelper *Button::getName(Button::State state) { 37 0 : switch (state) { 38 0 : case Button::Pressed: return F("Pressed"); 39 0 : case Button::Released: return F("Released"); 40 0 : case Button::Falling: return F("Falling"); 41 0 : case Button::Rising: return F("Rising"); 42 0 : default: return F("<invalid>"); // Keeps the compiler happy 43 : } 44 0 : } 45 : 46 0 : unsigned long Button::stableTime() { return millis() - prevBounceTime; } 47 : 48 : END_CS_NAMESPACE