Book
Input and output
Input and output
Completion requirements
View
Switches, speakers, LEDs, and flashing unicorns.
2. Add a button
2.1. A look on the sketch
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}
Let's now examine the code of the Button sketch.
Constants
The very first lines of this program introduce constants,
which are similar to variables in that they store a piece of
information. However, constants don't change
throughout your program, and are therefore great for things like pin
numbers. They take up less memory space than variables.
const int buttonPin = 2;
digitalRead()
In the main loop, a function called digitalRead()
checks/reads the state of pin 2 (which is initialised as INPUT) and stores that state in a variable called buttonState.
buttonState = digitalRead(buttonPin);