Dev-Tools/HIB.cpp

81 lines
1.6 KiB
C++
Raw Normal View History

2016-11-06 11:03:06 +01:00
#include "HIB.h"
static uint8_t pin;
static uint8_t initialState;
static int state;
static volatile bool debouncing;
static ETSTimer timer;
static unsigned long previousMillis;
static unsigned int longPressMsec;
void timerCallback(void *);
void IRQ_handler();
void onButtonPressed();
void onButtonReleased();
void onLongButtonPressed();
void setConfig(uint8_t p, uint8_t initState, int longPress );
HIB::HIB(uint8_t pin, uint8_t initialState, int longPressMsec)
{
setConfig(pin, initialState, longPressMsec);
}
HIB::HIB(){
}
void HIB::configure(uint8_t pin, uint8_t initState, int longPressMsec){
setConfig(pin, initState, longPressMsec);
}
void setConfig(uint8_t p, uint8_t initState, int longPress ){
pin = p;
initialState = initState;
state = initialState;
debouncing = false;
previousMillis = 0;
longPressMsec = longPress;
pinMode(pin, INPUT);
attachInterrupt(digitalPinToInterrupt(pin), IRQ_handler, CHANGE);
os_timer_setfn(&timer, timerCallback, NULL);
}
void IRQ_handler(){
if(!debouncing){
debouncing = true;
os_timer_arm(&timer, 50, 0);
}
}
void timerCallback(void *){
debouncing = false;
state = !state;
if (state != digitalRead(pin)){
Serial.println("Debounce failed");
state = !state;
return;
}
if(state != initialState)
onButtonPressed();
else
onButtonReleased();
}
void onButtonPressed(){
Serial.println("Button Pressed");
previousMillis = millis();
}
void onLongButtonPressed(){
Serial.println("Long Button Pressed");
}
void onButtonReleased(){
Serial.println("Button Released");
if(millis() - previousMillis >= longPressMsec){
onLongButtonPressed();
}
}
HIB Hib;