I'm using the following function to debounce the push-button of a rotary encoder.
The button uses a Nano's internal pullup resistor.
bool rotaryPress()
{
bool rotaryButtonPress = false;
static bool buttonState = true;
static bool lastButtonState = true;
static unsigned long rotaryDbStart = 0;
const long dbDelay = 50;
bool sampleButton = false;
sampleButton = digitalRead(rotaryButtonPin);
if (!sampleButton) Serial.println("pressed"); // for debugging
if (sampleButton) Serial.println("not pressed"); // for debugging
if (lastButtonState)
{
rotaryDbStart = millis();
}
if (rotaryDbStart + dbDelay < millis())
{
if (sampleButton != buttonState)
{
buttonState = sampleButton;
if (buttonState == false)
{
rotaryButtonPress = true;
}
else rotaryButtonPress = false;
}
}
lastButtonState = sampleButton;
return rotaryButtonPress;
}
The button debounce function is used in about 7 places in the sketch and works perfectly.
In the 8th place it is called, once the button is pressed, the value of sampleButton never changes, whether the button is released or not.
The only place sanpleButton and rotaryButtonPin appear in the sketch are in this funciton and when rotaryButtonPin is declared and the pin initialised in setup().
As far as I can tell, there is something stopping digitalRead(rotaryButtonPin) from reading a new value. Any thoughts?