I have made the stopwatch very easy to control, and simple for the software, as I have executed routines when I detect buttons pressed down. If you look at the code for Exercise 4.7 again you will find that I always do things when the button is pressed. If the button is held down I will repeatedly do the action, i.e. while the "reset" button is held down I will repeatedly set the count to 0. If the stop button is held down I will repeatedly set the state of the stopwatch to stopped.

Fortunately I have arranged things so that the fact these things are repeated doesn't matter, in that the PICmicro has nothing better to do when it is repeating the commands. Furthermore, since I am detecting whether or not a button is held down I don't get any problems with debounce.

However, suppose I want to re-design my stopwatch so that it stops when a button is pressed and released, and then starts again when the same button is pressed and released (this is how real stopwatches work).

In this case I am really interested in the event of the button being pressed. I don't care when the button is released, only when it goes down. This is when my user wants to start or stop the watch. We are all used to using event driven software. The computer you are using to read these notes will respond when you move the mouse or press buttons and keys. This is because the windowed operating system which it uses has been designed to respond to events generated by the keyboard and mouse. Now we are going to find out how we can make our own event driven software.

Events vs. Polling

When we created our music playing program we made the program repeatedly check the keyboard, waiting for a key to be pressed. This is the "polling" or "busy waiting" way of performing input/output. It is quite often the simplest way of writing small programs which require input output. In the case of the keyboard I might want the note to continue when the key is held down (as in an electric organ) and so it makes sense to make the program work like this. However, for my stop watch the only events I am interested in are the ones where the button goes down. Note that I am still polling really, it is just that I have hidden the polling process inside the timer interrupt. Later in the course we will find that we can make the PICmicro itself generate interrupts when the state of an input pin changes, and so do events properly.

In this program I can detect the event of a button being pressed by comparing the state of the key now with the state it had previously. If the two are different we have a change of state. If the new state is "button down" then I have just had a button down event.

On the right you can see the code which I have added to the interrupt handler to implement the events.