Momentary button as latching button

Hi,

I am looking for some help please, I need to make a momentary push button act like a latching button so that when it is pressed it does something until its pressed again to turn that function off.

My current code for the function is:

/* function to control maintain mode */
void maintainMode()
{
  byte maintainSwitch = 0;
  maintainSwitch = digitalRead(MAINTAIN_SWITCH_PIN);
  delay(50);

  if(maintainSwitch == LOW)
  {

    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Maintenance Mode: ON");
    lcd.setCursor(0, 2);
    lcd.print("Disable mode when complete.");
    digitalWrite(HEATER_RELAY_PIN, HIGH);
    digitalWrite(FILTER_UV_RELAY_PIN, HIGH);

  }else{
   
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Maintenance Mode: OFF");

}

The above code does not work and ive spend hours trying to find a solution, any ideas?

How do you call the function "maintainMode()"? Post ALL your code.

The state change detection example shows how to do what you want.

groundFungus:
The state change detection example shows how to do what you want.

Ive just looked at the code and tried it but it still acts as a momentary button! the cade just shows its current state

wreckitsteve:
Ive just looked at the code and tried it

Show us! All of it! Because we know one thing for sure, the bug is in the code you did not post...

When a push button is pressed, it is pressed at human speed. This means that it stays pressed for several cycles of your loop().