The working
When the button isn't pressed, there is no connection between the two legs of the button; it will input 0V to the Arduino since the pin of the button is connected to ground through the pull-down resistor. If you recall what we learned about logic states, the Arduino should read a LOW
or binary 0 in this case.
Then the button is pressed and the connection is closed; this makes a connection between its two legs, thus connecting 5V to the Arduino's I/O pin, and we read a HIGH or binary 1.
Let's walk through this code, line by line, so that you can understand what each line does:
int state = 0;
This initializes a variable of an integer type and puts the value of 0 in it.
This is also called initializing a variable. In our case, this variable shall store the value of the state of our button. Values are assigned to variables using =
; hence, this is also called an assignment operator:
void setup() { // initialize digital I/O pins pinMode(2, INPUT); pinMode...