We will need to have a way of reading a number from the user. I have decided to use all of PORTB as inputs for our number reading (we can do this even with the LED display because we can make use of my cunning multiplexing of the input/output pins).

There is a slight problem in that this means I will only be able to read numbers containing digits 0-7, but I will write the code so that we store the numbers as decimal, so if we find a better keypad we can increase our range. If I am careful about how I write the code I can change the keypad reader and leave the rest of the code untouched.

You repeat the process on the right until you have read as many digits as you need. This means that I need to find a function which will get me a digit from a button press. We can use the code from the piano to do some of this for us.

When it comes to reading digits we are not working in quite the same way as we did for our player piano. In the piano you are just interested in whether or not the key is held down. After I read a digit I have to wait for the key to go up again, so that I don't read the same digit twice. I am also interested in when there is no key down, since I want my lock to "go to sleep" to save batteries if it is not required. The sequence for reading a digit is given on the right.

Remember that I want to register the digit when the key goes down (which is when the user would expect something to happen) but that I also have to wait for the keys to go back up again before I continue so that I stop double entries. You might think you can simplify your code by acting on a value when the button is release rather then when it is pressed, but users do not like this. I have seen people nearly break keyboards because when they don't see something happen when they press the button they react by pressing down harder. The fact that the change takes place when the keys are released does not appeal at all.

If I don't see a button go down I will update a counter which will eventually trigger a move to "sleep" mode. We have already done something like this with the torch program we looked at earlier. That had a timeout where the torch would shut down after a while. Once we have completed this work we will know how we could create a torch which shut down the processor as well as the light when it had been left for a while. That used a counter which we incremented while the light was lit, until it reached a timeout value.

We are going to do the sleep mode in a slightly different way, which you could also apply to the torch as well.