BinaryDice/SimpleButton/SimpleButton.ino
const unsigned int BUTTON_PIN = 7;
const unsigned int LED_PIN = 13;
void setup() {
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT);
}
void loop() {
const int BUTTON_STATE = digitalRead(BUTTON_PIN);
if (BUTTON_STATE == HIGH)
digitalWrite(LED_PIN, HIGH);
else
digitalWrite(LED_PIN, LOW);
}
We connect the button to pin 7 and the LED to pin 13 and initialize those
pins in the
setup
function. In
loop
, we read the current state of the pin connected
to the button. If it is
HIGH
, we turn the LED on. Otherwise, we turn it off.
Upload the program to the Arduino, and you’ll see that the LED is on as long
as you press the button. As soon as you release the button, the LED turns
off. This is pretty cool, because now we nearly have everything we need to
control our die using our own button. But before we proceed, we’ll slightly
enhance our example and turn the button into a real light switch.
To build a light switch, we start with the simplest possible solution. Do not
change the current circuit, and upload the following program to your Arduino:
BinaryDice/UnreliableSwitch/UnreliableSwitch.ino
const unsigned int BUTTON_PIN = 7;
Line 1
const unsigned int LED_PIN = 13;
-
-
void setup() {
-
pinMode(LED_PIN, OUTPUT);
5
pinMode(BUTTON_PIN, INPUT);
-
}
-
int led_state = LOW;
-
void loop() {
-
const int CURRENT_BUTTON_STATE = digitalRead(BUTTON_PIN);
10
if (CURRENT_BUTTON_STATE == HIGH) {
-
if (led_state == LOW)
-
led_state = HIGH;
-
else
-
led_state = LOW;
15
digitalWrite(LED_PIN, led_state);
-
}
-
}
-
Chapter 3. Building Binary Dice • 50
report erratum • discuss
www.it-ebooks.info