Read the code
Here is the whole sketch. It does the same job as Arduino’s own Button example3.
l4-button-arduino.ino// Lesson 4, Arduino version.
// Lights the UNO R3's LED on pin 13 while the button on pin 2 is held.
void setup() {
pinMode(2, INPUT);
pinMode(13, OUTPUT);
}
void loop() {
if (digitalRead(2) == HIGH) {
digitalWrite(13, HIGH);
} else {
digitalWrite(13, LOW);
}
}What each line does
void setup()The lines insidesetuprun once, when the board starts11.pinMode(2, INPUT);Makes pin 2 an input: a pin your code reads6.pinMode(13, OUTPUT);Makes pin 13 an output, as in Lesson 16.void loop()Runs again and again, so the board checks the button all the time12.if (digitalRead(2) == HIGH) {If pin 2 reads HIGH, the button is down, so the next line runs8.digitalWrite(13, HIGH);Turns the light on7.} else {The lines afterelserun when the test is false: the button is up9.digitalWrite(13, LOW);Turns the light off7.
Reading the button
digitalRead(2) reads pin 2. It gives back HIGH or LOW5.
The two equals signs, ==, ask whether the two sides are equal10.