renderbug-cpp/firmware/inputs/Buttons.h

95 lines
2.4 KiB
C
Raw Normal View History

2019-05-10 05:17:29 +00:00
#pragma once
#include "../Figments/Input.h"
2019-05-10 05:17:29 +00:00
class Bounce {
public:
void attach(int pin, PinMode buttonPinMode) {
m_pin = pin;
pinMode(m_pin, buttonPinMode);
Log.info("Attaching a button to %d", pin);
}
void update() {
int readResult = digitalRead(m_pin);
if (m_state == Ready) {
if (readResult == HIGH) {
m_state = Started;
m_downStart = millis();
2021-03-28 01:19:55 +00:00
//Log.info("Button %d is started!", m_pin);
2019-05-10 05:17:29 +00:00
}
} else if (m_state == Started && millis() - m_downStart >= m_interval) {
if (readResult == HIGH) {
m_state = Confirmed;
2021-03-28 01:19:55 +00:00
//Log.info("Button %d is CONFIRMED!", m_pin);
2019-05-10 05:17:29 +00:00
} else {
m_state = Ready;
2021-03-28 01:19:55 +00:00
//Log.info("Button %d bounced back to ready!", m_pin);
2019-05-10 05:17:29 +00:00
}
} else if (m_state == Confirmed || m_state == Held) {
if (readResult == LOW) {
2021-03-28 01:19:55 +00:00
//Log.info("Button %d is released", m_pin);
m_state = Released;
2019-05-10 05:17:29 +00:00
} else if (m_state == Confirmed) {
m_state = Held;
2021-03-28 01:19:55 +00:00
//Log.info("Button %d is being held down!", m_pin);
2019-05-10 05:17:29 +00:00
}
2021-03-28 01:19:55 +00:00
} else if (m_state == Released) {
//Log.info("Button %d is ready!", m_pin);
m_state = Ready;
2019-05-10 05:17:29 +00:00
}
}
void interval(uint8_t v) {
m_interval = v;
}
bool fell() const {
return m_state == Confirmed;
}
2021-03-28 01:19:55 +00:00
bool rose() const {
return m_state == Released;
}
bool held() const {
return m_state == Held;
}
2019-05-10 05:17:29 +00:00
private:
enum State {
Ready,
Started,
Confirmed,
2021-03-28 01:19:55 +00:00
Held,
Released
2019-05-10 05:17:29 +00:00
};
State m_state = Ready;
unsigned int m_pin = 0;
unsigned int m_downStart = 0;
unsigned int m_interval = 10;
};
class Buttons: public InputSource {
public:
2021-03-28 01:19:55 +00:00
Buttons() : InputSource("Buttons") {}
void onStart() override;
InputEvent read() override;
2019-05-10 05:17:29 +00:00
2021-03-28 01:19:55 +00:00
enum Chord {
None = 0,
Circle = 1,
Triangle = 2,
Cross = 4,
CircleTriangle = Circle | Triangle,
CircleCross = Circle | Cross,
TriangleCross = Triangle | Cross,
CircleTriangleCross = Circle | Triangle | Cross
};
2019-05-10 05:17:29 +00:00
private:
Bounce m_buttons[3];
2021-03-28 01:19:55 +00:00
Chord m_buttonMap[3] = {Circle, Triangle, Cross};
bool m_wasChord[3] = {false, false, false};
2019-05-10 05:17:29 +00:00
};