I have a routine that looks for input from one of 5 buttons. It was originally written such that on detecting a button press it waited for the button to be released before returning a flag indicating that a button had been pressed and released and the number of the button. This was as follows :
void lookForButton() //return btnPressed=true and btnNum if a button is pressed and released
{
btnPressed = false;
for (int btn=8;btn<=12;btn++)
{
if (digitalRead(btn) == HIGH) // check for a button being pressed
{
btnPressed = true;
btnNum = btn; //save number of button pressed
}
}
if (btnPressed == true)
{
while (digitalRead(btnNum) == HIGH) //wait for the button to be released
{
delay(100); //debounce
}
}
}
Being aware that I might not want the main program to stall at some time in the future I have re-written the routine as follows :
void lookForButton() //return btnReleased=true and btnNum if a button is pressed and released
{
boolean static btnPressed = false; //note STATIC to preserve value for next call
for (int btn=8;btn<=12;btn++)
{
if (digitalRead(btn) == HIGH) // check for a button being pressed now
{
btnPressed = true; //flag that we have found a button pressed and need to check for release
btnNum = btn; //save number of button pressed (could exit the loop at this point)
}
}
if (btnPressed == false) //no button pressed
{
btnReleased = false; //not pressed so it can't have been released so flag it and return
return;
}
currentBtnState = digitalRead(btnNum); //get current state of the button
if (currentBtnState != prevBtnState) //button state has changed. Did it bounce or was it released ?
{
if ((millis() - prevBtnTime > 100) && (digitalRead(btnNum) == LOW)) //button released and debounce time has elapsed
{
Serial.println("got a button"); //***********************DEBUGGING CODE*********************
btnPressed = false; //reset the flag for next time that it is needed
btnReleased = true; //flag release of button for action
}
else
{
Serial.println("no valid button yet"); //***********************DEBUGGING CODE*********************
prevBtnTime = millis(); //button is still pressed or debounce time has not elapsed
prevBtnState = currentBtnState; //remember the current button state and current time
}
}
}
prevBtnTime is defined as a global long initially set to 0
currentBtnState and prevButtonState are defined as global ints initially set to LOW
None of these variables are changed anywhere else in the sketch
The routine appears to work but the debug Serial.print only outputs "no valid button yet" the first time that the routine is used after uploading a sketch or resetting the Arduino so something is wrong and I would be grateful for advice as I suspect my logic is wrong somewhere.