HOW-TO TEST SWITCHES & INPUTS ---

A common 'error' among beginners is to test the state of an input (sensor, switch or pushbutton) simply by checking the immediate pin state...
e.g.
const char inputPin = pp;
pinMode(inputPin, dir) as required, then...

if ((digitalRead(inputPin) == LOW)) {
    // do some LOW state thing
}
.... or similar

This will work reliably in a few cases, but does not take into account the input may return to a the opposite state, be held down, or other environmental /logical condition.

What you should/might/could be doing unless there is a good reason you can explain - is more like...
const char inputPin = pp;
pinMode(inputPin, dir) as required, then...

static bool prevInState;
bool inState = (digitalRead(inputPin));
if (inState != prevInState) {
   if (inState == HIGH) { 
      // do HIGH state things
   } else {
      // do LOW state things
   }
   prevInState = inState;
} else {
   // if it gets here - the input hasn't changed state!
}

lastchancename:
A common 'error' among beginners is to test the state of an input (sensor, switch or pushbutton) simply by checking the immediate pin state...
e.g.
const char inputPin = pp;
pinMode(inputPin, dir) as required, then...

if ((digitalRead(inputPin) == LOW)) {

// do some LOW state thing
}
.... or similar



This will work [u]_reliably in a **few** cases_[/u], but does not take into account the input may return to a the opposite state, be held down, or other environmental /logical condition.

What you should/might/could be doing unless there is a good reason you can explain - is more like...
__const char inputPin = *pp*;__
__pinMode(inputPin, *dir*)__ as required, then...


static bool prevInState;
bool inState = (digitalRead(inputPin));
if (inState != prevInState) {
  if (inState == HIGH) {
     // do HIGH state things
  } else {
     // do LOW state things
  }
  prevInState = inState;
} else {
  // if it gets here - the input hasn't changed state!
}

A slightly more advanced user would then go on to use logic which added some de-bounce to the button.