We now need a way of adding the sleep code to the lock itself. I am not particularly proud of the way which I implemented this (I have an aversion to doing things like stopping the processor during interrupt handlers) but it does seem to work extremely well. I will leave it as an exercise for you to improve on it!

I keep a counter, sleep_timer, which is incremented each time the refresh takes place. When this reaches a certain value I call the sleep function which stops everything. When I get a keypress I reset the timer and continue.

In order to stop the system from timing out while a user is entering a number I have added a reset of the timer so that whenever a digit is entered the counter is set back to 0. This means that the user has five seconds to enter each digit. The system works so well that you can even pause and resume entering digits and the PICmicro will wake up and keep going!

In real life you could make the timeout value configurable for different applications, and could even store it in EEPROM!

The full version of the ultimate lock program is in Exercise 7.7 for you to play with.