The problem with our first light switch is that we have to hold it down to make the light work. Sometimes you might not want this. You may prefer a solution where we have two buttons, one to turn the light on and another to turn it off. (I actually have a torch which works like this).

To do this we will need another button, I am going to use bit 1 on PORTB. If bit 0 goes high I turn the light on, if bit 1 goes high I turn the light off. This means that my program must "remember" the state of the light, so that it can turn it on if it is off, and vice versa.

Fortunately the bits in the ports do remember their state, i.e. if I set the bit high it will stay high until I set it low. I can therefore "read back" the states of the ports, in effect treating them as variables. Note that this only works because the PICmicro has been designed this way. If you use a different chip as an output port you may find that you cannot read the settings. In this case you need to use a variable to "shadow" the state of the port.

The flowchart shows how we check each button in turn and turn the led on or off. We then go around and repeat the tests.

We need two if constructions, one for each button.