NerfStatTrak/Button.h

37 lines
1.0 KiB
C
Raw Normal View History

#ifndef Button_h
#define Button_h
#include "Arduino.h"
class Button
{
public:
void init(uint8_t pin, int offState = HIGH, bool usePullUp = true);
void update(unsigned long referenceTime = 0);
void block() { if (lastState != offState) blocked = true; }
bool changed() { return !blocked && lastChanged; }
bool pressed() { return !blocked && lastState != offState; }
unsigned long pressedMillis(unsigned long referenceTime = 0) { return getTime(referenceTime) - lastPressedTime; }
unsigned long getDebounceMillis() { return debounceMillis; }
void setDebounceMillis(unsigned long value) { debounceMillis = value; }
protected:
inline unsigned long getTime(unsigned long referenceTime) { return referenceTime == 0 ? millis() : referenceTime; };
private:
uint8_t pin = 1;
int offState = HIGH;
unsigned long debounceMillis = 50;
unsigned long lastChangedTime = 0;
unsigned long lastPressedTime = 0;
int lastState;
bool lastChanged;
bool blocked = false;
};
#endif