Pressing the push button doesn't utilize the other part of the code

Here is an example that toggles the state of a pin and the state if a bool variable (flag). It uses the method from the state change detection tutorial and my state change for active low (low when pressed) switch tutorial.

if you need help to figure out how to use it, post your latest version of your code.

// by C Goulding aka groundFungus

const byte  buttonPin = 2;    // the pin to which the pushbutton is attached
const byte ledPin = 13;       // the pin to which the LED is attached

bool buttonState = 0;         // current state of the button
bool lastButtonState = 0;     // previous state of the button

bool mode = false;

void setup()
{
   // initialize the button pin as a input with internal pullup enabled
   pinMode(buttonPin, INPUT_PULLUP);
   // initialize the LED as an output:
   pinMode(ledPin, OUTPUT);
   // initialize serial communication:
   Serial.begin(115200);
   Serial.println("Select mode with push button");
}

void loop()
{
   static unsigned long timer = 0;
   unsigned long interval = 50;  // check switch 20 times per second
   if (millis() - timer >= interval)
   {
      timer = millis();
      // read the pushbutton input pin:
      buttonState = digitalRead(buttonPin);
      // compare the new buttonState to its previous state
      if (buttonState != lastButtonState)
      {
         if (buttonState == LOW)
         {
            // if the current state is LOW then the button
            // went from off to on:
            digitalWrite(ledPin, !digitalRead(ledPin)); // toggle the output
            mode = !mode;
            if (mode == true)
            {
               Serial.println("Manual mode\n");
            }
            else
            {
               Serial.println("Scan mode\n");
            }
         }
      }
      // save the current state as the last state,
      //for next time through the loop
      lastButtonState = buttonState;
   }
}
1 Like