The solution is to provide code to debounce the signal. This means that I wait until I have twenty readings all the same before I decide that the button is in one position or the other. You can write the sequence we want to perform as follows:

1. Set our counter to 0

2. Read the state of the inputs

3. Record it

4. Read the state of the inputs again

5. If the state is the same as the previous state, make our counter one bigger

6. If the state is not the same as the previous state, make the counter 0 and record the state.

7. If the counter has reached 20 we can exit with the correct state.

8. Go back to step 4

If you work through this "mini-program" you will see that it needs 20 consecutive readings before it can escape. As soon as it receives an input which is different from the previous one it resets the counter.

The upper limit of the counter determines how sensitive our function is. If we make the counter larger we improve our rejection of noise, but it takes us longer to notice a pulse.

On the other hand, if we make the counter smaller we notice a pulse more quickly, but we are more likely to see noise as a valid reading. I have found that a value of 20 seems to work well.

The CPIC program on the right hand side implements a function called key which you can use to get a debounced value of the key input. If you run it you can toggle the value on the input pin and watch it react. Only when the value has been steady long enough for count to reach 20 does the function return a value.