Thanks alot for valuable comments, and yes UKHeliBob, I am copying and modifying examples, tests how they behave and tries to understand what the command lines do. My learning works best that way, theory without practice is not my strong side.
Jimmus, thank you very much for guidance code and explanational comments, very nice. I have taken a first peak at it (at work, no arduino board here, dont tell anyone) and tried to interprete it with further noob comments and questions. Please dont take it for lecturing from my side, it is quite the opposite.
int lastSwitchPinState = HIGH; // This will be used to keep track of what state the switchPin WAS last time we checked it
// This assumes the button is not pressed at startup
Comment Staffan: As I understand this DECIDES that the lastSwitchPinState was HIGH and assumes that since the button was not pressed under startup the state is HIGH with the pullup resistor. This is for the program to know what the state next change should be. This value gets changed by lastSwitchPinState = currentSwitchPinState; in the loop when button is pressed.
Question: Why is this an int when it can only have two values?
int currentSwitchPinState = digitalRead(switchPin);
Comment Staffan: This reads the state of the switchPin and declares it to be the currentSwitchPinState, is that the way to interprete it?
if (currentSwitchPinState != lastSwitchPinState) // If the state has changed, we have a state change. Imagine that!
Comment Staffan: OK, this is a way of DETECTING a state change, and works together with the next if command? It compares the value current with last?
if (currentSwitchPinState == LOW) // State change was HIGH to LOW. Button was pressed, not released.
Comment Staffan: Together with the former if command it is querying if the state change was from HIGH to LOW, ie button was pressed.
// toggle the output
}
delay(20); // debounce
lastSwitchPinState = currentSwitchPinState;
Comments Staffan: If the above if-queries was true go ahead and change lastSwitchPinState to currentSwitchPinState, but it doesn’t toggle any output, that is code I have to add, correct?