/
3_button_and_led.ino
42 lines (31 loc) · 1.03 KB
/
3_button_and_led.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// momentary control of the built-in led with a button input
// (led on while button pressed)
// with serial monitor feedback
// button on port D2
int buttonPin = 2;
// booleans can have only 2 states : 0/1, true/false, HIGH/LOW
boolean buttonCurrentState;
boolean buttonPreviousState;
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
pinMode(buttonPin, INPUT);
// initialize serial connection
Serial.begin(9600);
}
void loop() {
// read state of button input pin
buttonCurrentState = digitalRead(buttonPin);
// has the button been pressed?
if (buttonCurrentState == HIGH && buttonPreviousState == LOW) {
digitalWrite(LED_BUILTIN, HIGH);
Serial.println("on");
} else {
// has the button been released?
if (buttonCurrentState == LOW && buttonPreviousState == HIGH) {
digitalWrite(LED_BUILTIN, LOW);
Serial.println("off");
}
}
// store current button state in 'memory' variable to check against in next loop
buttonPreviousState = buttonCurrentState;
}