Digital input — Button
Students will: Use a digital input — the ThinkerShield button — to control the LED with an `if`/`else` statement. Learn to give pins friendly names with the `int` command.
int buttonPin = 7; // the pushbutton is on pin D7 of the ThinkerShield
int ledPin = 12; // the LED is on pin D12
int buttonState = 0; // variable for reading the pushbutton's state
void setup() {
pinMode(ledPin, OUTPUT); // the LED pin is an output
pinMode(buttonPin, INPUT); // the button pin is an input
}
void loop() {
buttonState = digitalRead(buttonPin); // read the button
if (buttonState == HIGH) { // is it pressed?
digitalWrite(ledPin, HIGH); // yes -> LED on
} else {
digitalWrite(ledPin, LOW); // no -> LED off
}
}
int LED = 12; // call pin 12 "LED" for the rest of this sketch
void setup() {
pinMode(LED, OUTPUT); // make the LED pin an output
}
void loop() { // runs over and over again, forever
digitalWrite(LED, HIGH); // turn the LED on
delay(1000); // wait for one second
digitalWrite(LED, LOW); // turn the LED off
delay(1000); // wait for one second
}
Common errors & fixes
=vs==— single=assigns; double==compares. The IDE won't always warn you.- Pin 2 vs pin 7 — some printed copies of the workbook use pin 2; on the ThinkerShield the button is pin 7. Use 7.