#include "button.hpp" #include void Button::setup(void) { pinMode(_pin, INPUT_PULLUP); } bool Button::is_button_pressed(void) { return digitalRead(_pin) == 0; } void AnalogButton::setup(void) { if (_vRef < 0) { calibrate(); } } bool AnalogButton::is_button_pressed(void) { return analogRead(_pin) < _vRef; } void AnalogButton::calibrate(void) { int highRef, lowRef; #if defined(__BUILD_DEBUG__) && false debugSerial.print(__func__); #endif /* defined(__BUILD_DEBUG__) */ /* Get the button released (High) state voltage, should be close to 1024 (analogRead max) */ do { highRef = analogRead(_pin); delay(300); } while (highRef < 1000); #if defined(__BUILD_DEBUG__) && false debugSerial.println("highRef="); debugSerial.println(highRef); #endif /* defined(__BUILD_DEBUG__) */ /* Get the button pushed (Low) state voltage (min of ~5% difference needed to avoid false detection) */ lowRef = analogRead(_pin); while (highRef - lowRef < 50) { lowRef = analogRead(_pin); delay(300); } #if defined(__BUILD_DEBUG__) && false debugSerial.println("lowRef="); debugSerial.println(lowRef); #endif /* defined(__BUILD_DEBUG__) */ /* Add ~1% tolerance */ _vRef = lowRef + 10; }