Button press timeout

Folks,

The project is an Alarm Clock - not sure if I can do it but I'm going to try to break it down into small sections. I'm planning on having 4 buttons (one for alarm off, two for setup, three for up and four for down). That's the plan at this point anyway. I was thinking that the user would push the setup button once and a message would be displayed on the LCD - "Press set again to enter setup mode." If the user does not push the set button within 10 seconds, carry on. Obviously there are some housekeeping items like clearing the LCD after the timeout but I think I can handle that.

Two things. One, when I push the button I think I'm getting multiple instances of a button press - I think. Is this a debouncing issue? Two, am I on the right track with this code? Recommendations regarding my approach are also welcome.

const byte setButton              = 3;

byte lastState3;

boolean buttonTimer = false;

const unsigned long buttonTimeOut = 10000;

unsigned long switchMillis;
unsigned long buttonMillis;

//************************************************************************

void setup()
{
  Serial.begin(9600);
  
  pinMode(setButton, INPUT_PULLUP);
  lastState3 = digitalRead(setButton);


} //END of setup()

//*************************************

void loop()
{
  if (millis() - switchMillis >= 50)                                  //time to check the switches ?
  {
    switchMillis = millis();                                          //restart the Timer
    checkSwitches();
  }

  //*************************************

  if (millis() - buttonMillis <= buttonTimeOut && digitalRead(setButton) == LOW)
  {
    Serial.print("You are in SETUP");
  }

} //END of loop()

void checkSwitches()
{

  //****************** SWITCH 1 / ENTER SET UP ******************* 

  byte currentState3 = digitalRead(setButton);

  if (lastState3 != currentState3)

  {
    lastState3 = currentState3;

    if (buttonTimer == false && currentState3 == LOW)
    {
      buttonMillis = millis();
      buttonTimer = true;
      Serial.println("PRESS SET AGAIN TO  ");    
      Serial.println("ENTER SETUP MODE   ");
    }
  }
} //END of checkSwitches()

Thank you.

Best,

Tony

To simplify your coding, leverage existing button libraries, for example OneButton from Matthias Hertel.

What you describe is best achieved through a "State Machine". There are multiple tutorials and examples on line

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.