Using a Digital Push Button
In this lab you will connect the LED to one of the pins of the Arduino. You will then connect a push button to one of the other pins of the Arduino. Finally you will programme the Arduino so that when the button is pushed the light toggles on and off.
Programme the Arduino
Programme the following into the Arduino. Verify it and if there are no errors, upload and test it.
!!! You will need to CHANGE the use of pin4 to either pin 2 or 3 !!!
Does the LED always change state?
What happens if you hold the button down?
Can you explain what is happening?
Toggle Buttons
Another way to debounce the button is to use a flag. A flag is a variable that can be in one of two states. We are going to add a flag variable, called “buttonFlag” to track the state of the button. The process works like this.
- As soon as we detect the button push we check the flag.
- If the flag is false then this is the first time we’ve seen the button being pushed. Change the light and set the flag to true
- When the programme loops around again check if the button is being pushed.
- If it is then check the flag. If the flag is true then this is the same button push (not a new one) so don’t so anything
- When the programme loops around again check if the button is being pushed.
- If it’s not then the user has let it go so set the flag back to false ready for the next push.