Print a Button's State
Part of the Inputs section of Coddy's Arduino journey. Lesson 1 of 22.
In Read a Button, digitalRead(pin) gave you HIGH or LOW. To the board these are plain numbers: HIGH is 1 and LOW is 0. So you can keep a reading in an int variable and print it like any other number:
int state = digitalRead(2);
Serial.println(state);The button here is wired the way you met it before: it joins pin 2 to ground (GND, 0 volts) while you hold it, and INPUT_PULLUP keeps the pin HIGH the rest of the time. So the Serial monitor shows 1 while the button is up and 0 while it is down.
loop() runs thousands of times a second. A short delay(100) after the print keeps the Serial monitor readable: ten lines a second instead of thousands.
Challenge
EasyThe button is on pin 2. Print its state to the Serial monitor:
- in
setup(), set pin 2 toINPUT_PULLUP - in
loop(), read the pin into anint, print it withSerial.println(), then wait 100 ms
Press Run, open the Serial monitor and hold the button, then Check.
Try it yourself
const int buttonPin = 2;
void setup() {
Serial.begin(9600);
// set the button pin to INPUT_PULLUP
}
void loop() {
// read the button, print the reading, wait 100 ms
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Inputs
1Buttons
Print a Button's StatePull-Down ResistorThe Internal Pull-UpToggle on Each PressCount Button PressesDebounce a ButtonTwo Buttons at OncePractice on your own: Arduino playground