Project 3.00 Read Input
In this project you will be introduced to buttons. By the end of this project, you will know how to read the state of a button (on or off) and how to store that in a bool type variable.
There are two buttons on the MC Trainer we can use, SW1 and SW2. SW1 is on the left side of the board and SW2 is on the right side. The abbreviation “SW” stands for switch.
Project Code:
//////////////////////////////////////////////////// // 3.00 - Read Input byte SW1 = 1; void setup() { Serial.begin(9600); pinMode(SW1, INPUT); } void loop() { bool buttonState = digitalRead(SW1); Serial.print("The state of the button is: "); Serial.println(buttonState); delay(250); } ////////////////////////////////////////////////////
*If you’re copying and pasting the code, or typing from scratch, delete everything out of a new Arduino sketch and paste / type in the above text.
SW1 is connected to pin 1 so we first create a variable to represent our button in code:
byte SW1 = 1;
Next, in setup(), we initialize Serial so we can get feedback from our microcontroller:
Serial.begin(9600);
Then because we are trying to read something from the outside world (a button press), SW1 is an input.
pinMode(SW1, INPUT);
If you think about a button, it is either pressed or not pressed, there is no in-between. In similar terms, it is HIGH or LOW, ON or OFF, TRUE or FALSE, 1 or 0. A bool type variable is strictly meant to hold values like this, 1 or 0. So to store our buttons current state we will use a bool type variable.
bool buttonState
The digitalRead function can be used to read the digital state of a pin. This function will return a 1 if the voltage is HIGH (the button is not pressed) and a 0 if the voltage is LOW (the button is pressed).
bool buttonState = digitalRead(SW1);
Once read, the state of the button is printed out to the Serial port. Make sure to open it so you can see what is being printed!
Serial.print("The state of the button is: "); Serial.println(buttonState);
Lastly, there is a delay so thousands of lines don’t print out at once and the loop() is ended.
delay(250); }
Press SW1 and watch the button state change in the Serial monitor!
Now that we can read the button state, we can combine that with programmatic logic to make decisions on what to do when the button is pressed!