Magnetic switch loop

The whole point is that to detect a state change on a pin you must
remember the previous state on the pin to compare with the current state.

Code will always be like:

  now_state = digitalRead (...) ;
  if (now_state != previous_state)  // detect a change
  {
    if (now_state == ...)  // HIGH or LOW depending on which change
    {
      perform_action () ;
    }
    previous_state = now_state ;  // housekeeping for next time
  }