const int CURRENT_BUTTON_STATE = digitalRead(BUTTON_PIN);
-
if (CURRENT_BUTTON_STATE != old_button_state &&
-
CURRENT_BUTTON_STATE == HIGH)
-
{
15
if (led_state == LOW)
-
led_state = HIGH;
-
else
-
led_state = LOW;
-
digitalWrite(LED_PIN, led_state);
20
delay(50);
-
}
-
old_button_state = CURRENT_BUTTON_STATE;
-
}
-
This final version of our LED switch differs from the previous one in only a
single line: to debounce the button, we wait for 50 milliseconds in line 21
before we enter the main loop again. For the moment this solution is sufficient,
but you’ll learn about an even better one in a few minutes.
That’s everything you need to know about pushbuttons for now. In the next
section, we’ll use two buttons to turn our binary die into a real game.
Adding Your Own Button
Now that you know how to work with pushbuttons, you no longer have to
abuse the Arduino’s reset button to control the die. You can add your own
pushbutton instead. As Figure 12, Our binary die with its own start button,
on page 54, we need to change our current circuit only slightly. Actually, we
don’t have to change the existing parts at all; we only need to add some things.
First, we plug a button into the breadboard and connect it to pin 7. Then we
connect the button to the ground via a 10kΩ resistor and use a small piece
of wire to connect it to the 5-volt pin.
That’s all the hardware we need. Here’s the corresponding software:
BinaryDice/DiceWithButton/DiceWithButton.ino
const unsigned int LED_BIT0 = 12;
const unsigned int LED_BIT1 = 11;
const unsigned int LED_BIT2 = 10;
const unsigned int BUTTON_PIN = 7;
void setup() {
pinMode(LED_BIT0, OUTPUT);
pinMode(LED_BIT1, OUTPUT);
pinMode(LED_BIT2, OUTPUT);
pinMode(BUTTON_PIN, INPUT);
randomSeed(analogRead(A0));
}
report erratum • discuss
Adding Your Own Button • 53
www.it-ebooks.info