Cookie Timer
Step 1 - Build the Project
The cookie timer combines an indicator light with a software timer and a light and speaker alarm and some math to ensure the timer is working in 10 second increments.
Step 2 - Upload the Code
Step 3 - Read the Walkthrough
The pressCount variable holds the number of times you have increased the timer by a 10 second increment. After setting up the ‘add time’ button and the ‘go!’ button as INPUT_PULLUPs and the LED and speaker as OUTPUTs, the rest of the code is a series of steps that can be broken down into small pieces.
The first ‘if’ statement in the loop looks for the ‘add time’ button to be pressed. If it’s pressed, the indicator light will illuminate and the pressCount is increased by one, then the indicator light turns off.
The second ‘if’ statement watches for the ‘go’ button. When it is pressed, the code drops into a ‘for’ loop that blinks the pressCounts and beeps a tone so you’re sure how many 10 second increments you added to the timer.
You then create the variables that define the number of seconds you want to add to your time each time you press the ‘add time’ button. The timer variable then multiplies that ‘time added per press’ by the pressCount to get a total number of seconds on your timer.
Next is a ‘while’ loop, which is useful when you’re not sure how many times a loop will need to repeat. With a ‘for’ loop, the loop will run a set number of times. With a ‘while’ loop the loop will run until the condition after ‘while’ is untrue. For this ‘while’ loop, you’re saying “write the light HIGH, wait half a second, write the light LOW, wait half a second, take 1 off of the timer number, and repeat”. This effectively reduces timer by 1 every second and gives a blink so you know the timer is running.
When the code falls through this first ‘while’ loop, it falls into another ‘while’ loop. The conditions of this ‘while’ loop are “as long as the button on 4 and the button on 12 are not both pressed, do the things in this ‘while’ loop”. This check means that you have to press both of the buttons at the same time to stop the alarm.
Unless that condition is false (meaning both buttons are pressed) the alarm will continue alternating between a tone of 650 and 950 and flashing the light on. Once the conditions are false, the code drops through this second ‘while’ loop, resets the pressCount, and is ready to start again!