Writing Arduino Code
Read a Button
13 minStudent plan
Input, not just output. Pull-up resistors, why an unconnected pin lies to you, and reacting to a press in code.
After this lesson you can
- Read a button with digitalRead
- Explain what a floating input is and how a pull-up fixes it
- Say why one press can register as several
Reading an input
Configure the pin as an input, then read it:
pinMode(2, INPUT_PULLUP); int state = digitalRead(2);
digitalRead returns HIGH or LOW. Store it, compare it, act on it, it is an ordinary value.
Use it with an if statement to make something happen:
if (digitalRead(2) == LOW) { digitalWrite(13, HIGH); } else { digitalWrite(13, LOW); }
Note the double equals. A single = assigns; a double == compares. Writing if (x = LOW) assigns LOW to x and then tests the result, which compiles and behaves bizarrely, a bug that has cost people entire evenings.
In the full lesson
- Reading an input
- Floating inputs and pull-ups
- Bounce
This lesson comes with the Student plan. The first module of Programming is free.