class Button {
private:
const int BUTTON_PIN;
const int DEBOUNCE_TIME;
int lastSteadyState;
int lastFlickerableState;
int currentState;
int btnStatus;
bool firstRun;
unsigned long lastDebounceTime;
public:
Button(int buttonPin, int debounceTime) : BUTTON_PIN(buttonPin), DEBOUNCE_TIME(debounceTime) {
lastSteadyState = LOW;
lastFlickerableState = LOW;
currentState = LOW;
lastDebounceTime = 0;
btnStatus = 0; // 0 = nothing, 1 = press, 2 = release
firstRun = true;
pinMode(BUTTON_PIN, INPUT_PULLUP);
}
void setup(){
lastSteadyState = digitalRead(BUTTON_PIN);
}
void update() {
currentState = digitalRead(BUTTON_PIN);
if (currentState != lastFlickerableState) {
lastDebounceTime = millis();
lastFlickerableState = currentState;
}
if ((millis() - lastDebounceTime) > DEBOUNCE_TIME) {
if(lastSteadyState == HIGH && currentState == LOW){
// Serial.println("The button is pressed");
btnStatus = 1;
lastSteadyState = currentState;
return;
}
else if(lastSteadyState == LOW && currentState == HIGH){
// Serial.println("The button is released");
if(firstRun){
firstRun = false;
} else {
btnStatus = 2;
}
lastSteadyState = currentState;
return;
}
lastSteadyState = currentState;
btnStatus = 0;
}
}
bool isPressed(){
return btnStatus == 1 ? true : false;
}
bool isReleased(){
return btnStatus == 2 ? true : false;
}
int getState(){
return lastSteadyState == HIGH ? 1 : 0;
}
};
Button btnA(21, 50); //instiate button class (pin, debounceDelay)
Button mySwitch(19,50);
#define LED_A 18
int ledState = LOW;
int switchState;
void setup() {
Serial.begin(9600);
pinMode(LED_A, OUTPUT);
btnA.setup();
mySwitch.setup();
switchState = mySwitch.getState();
Serial.println(switchState);
}
void loop() {
btnA.update(); // must be call to update attribute value of the clas
mySwitch.update();
if (btnA.isPressed()) {
Serial.println("The button is pressed");
}
if (btnA.isReleased()) {
Serial.println("The button is released");
toggleLed();
}
if (mySwitch.getState() != switchState){
switchState = mySwitch.getState();
Serial.println(switchState);
}
}
void toggleLed() {
ledState = (ledState == HIGH) ? LOW : HIGH;
digitalWrite(LED_A, ledState);
}