Arduino Uno Lesson 5 Digital Switch Code

recently I was trying to get my setup for a LED and button to work on toggle, like a light switch in a house. A user provided me the code that worked for me but I was wondering if someone could help explain the code so i can understand how it works instead of just making my LED and button work.

The code is

// recognize multiple button presses; tgl LED when pressed

byte butPin = A1;
byte ledPin = 10;

byte butLst;


// -----------------------------------------------------------------------------
void setup (void)
{
    digitalWrite (ledPin, HIGH);
    pinMode      (ledPin, OUTPUT);

    pinMode      (butPin, INPUT_PULLUP);
    butLst      = digitalRead (butPin);
}

// -----------------------------------------------------------------------------
void loop (void)
{
    byte but = digitalRead (butPin);

    if (butLst != but)  {
        butLst = but;

        if (LOW == but)     // button pressed
            digitalWrite (ledPin, ! digitalRead (ledPin));
    }

    delay (10);         // debounce
}
/code]

See my post here

xsteven_:
I was wondering if someone could help explain the code so i can understand how it works instead of just making my LED and button work.

define a state variable for the button

byte butLst;

set the ledPin to a desired starting state: HIGH and configure the pin as an output

    digitalWrite (ledPin, HIGH);
    pinMode      (ledPin, OUTPUT);

configure the button pin as an INPUT with a pullup resistor. With the switch connected between the pin and ground the input is normally HIGH and when the switch is depressed, it pulls the input LOW.

"butLst" is initialized by reading the state of the button pin

    pinMode      (butPin, INPUT_PULLUP);
    butLst      = digitalRead (butPin);

reads the butten pin value

    byte but = digitalRead (butPin);

compares the button value to its previously know state to detect a change. Update the butLst when there is a change

    if (butLst != but)  {
        butLst = but;

if the button state has change and the but is LOW is was just pressed. If it's pressed, read the led pin, and write a new value which is NOT, "!", what the current value is. In other words, toggle the led pin state, if HIGH set is LOW and visa versa.

        if (LOW == but)     // button pressed
            digitalWrite (ledPin, ! digitalRead (ledPin));

the metal contacts of a switch can bounce resulting in several changes of state. Delaying 10 msec when there is a change avoids detecting any subsequent changes in state

    delay (10);         // debounce