Commit b86d81de authored by Sam Guyer's avatar Sam Guyer
Browse files

Factored out button class

parent 68ba3da2
#include <FastLED.h>
#include <Buttons.h>
// -- Motor --------------------------------
......@@ -25,107 +26,11 @@ CRGB leds[NUM_LEDS];
// -- Time to spin up and down the jetpack
#define POWERUP_TIME 5000
// -----------------------------------------------
// Button class
// -----------------------------------------------
class Button
{
public:
enum EventKind { NONE, CLICK, HOLD, RELEASE };
private:
enum State { UP, START, DOWN };
int m_pin;
uint32_t m_state;
uint32_t m_start_time;
uint32_t m_hold_time;
public:
Button(int pin)
: m_pin(pin),
m_state(UP),
m_start_time(0),
m_hold_time(0)
{}
void init()
{
pinMode(m_pin, INPUT);
}
EventKind getEvent(uint32_t current_time)
{
unsigned long elapsed_time = current_time - m_start_time;
// -- Read raw button
int button_raw = digitalRead(m_pin);
// --- Cap sense button
// long cs = CapSense.capacitiveSensor(1);
// if (cs > 20) button = HIGH;
// else button = LOW;
EventKind buttonEvent = NONE;
switch (m_state) {
// -- First detection of button down -- just record the time
case UP:
if (button_raw == HIGH) {
m_state = START;
m_start_time = current_time;
m_hold_time = 0;
}
break;
// -- Debouncing: if we detected a button push, check again after 50ms
// to make sure it is real
case START:
if (elapsed_time > 50) {
if (button_raw == HIGH)
m_state = DOWN;
else
m_state = UP;
}
break;
// -- Button was clicked
// Depending on how long it stays down, we either return CLICK or HOLD
case DOWN:
if (button_raw == HIGH) {
if (elapsed_time > 500) {
buttonEvent = HOLD;
m_hold_time = elapsed_time;
}
} else {
if (elapsed_time > 500) {
buttonEvent = RELEASE;
m_hold_time = elapsed_time;
} else {
buttonEvent = CLICK;
}
m_state = UP;
}
break;
}
return buttonEvent;
}
uint32_t getHoldTime(uint32_t current_time)
{
return m_hold_time;
}
};
// -- Button -------------------------------
#define BUTTON_PIN 4
Button button(BUTTON_PIN);
MomentaryButton button(BUTTON_PIN);
// -----------------------------------------------
// Set up
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment