Lesson 5 - Button States

We are now at the stage where we have a better understanding of programming using the Arduino IDE. In this lesson, we will be going through how to use a button within our programs. This will allow us to progress and write complex programs. We will be using the built in button on the Multi Functional Shield, A1, but you can also wire up a button to this pin.

Push Buttons

The buttons on the MFS are push buttons, which are single pole - single throw. This means that when the button is pressed down, it is HIGH, and when released, it is LOW. But, what if we want to use this push button to turn an LED on or off? We would have to hold the button down so that the LED is on, and the moment we release the button, the LED will turn back off. This isn't very convenient because, for instance, we may need the LED to stay on constantly after the button is pressed and when pressed again, the LED turns off. This can digitally be programmed using Button States.

Button States

To program a push button to act as a toggle switch, there are 3 variables we use:

1. Button State - This variable stores the current digital state of the button

2. Last Button State - This variable stores the previous digital state of the button

3. Control State - This variable stores the digital state of the unit we are controlling with the button

Below is the sample template code of how the Arduino reads the current state of the button. The conditional if statement compares the last button state to the current button state to perform the required operations when the button is digitally on or off. After each press, we update the Last Button State with a new value, in order for the program to keep up to date with the button states.

The source code below demonstrates how we can use a button as a toggle switch to turn an LED on and off. This program can be further developed to perform more complex toggle switch operations by simply writing more instructions within the 'ControlState' if condition.

Source Code

We recommend copying the source code to the IDE


By Zaqyas Mahmood, Electronics Engineer