We begin with the usual pin constants, and in
setup
we set the modes of the
pins we use. In line 8, we define a global variable named
led_state
to store the
current state of our LED. It will be
LOW
when the LED is off and
HIGH
otherwise.
In
loop
, we check the button’s current state. When we press the button, its
state switches to
HIGH
, and we toggle the content of
led_state
. That is, if
led_state
was
HIGH
, we set it to
LOW
, and vice versa. At the end, we set the physical LED’s
state to our current software state accordingly.
Our solution is really simple, but unfortunately, it doesn’t work. Play around
with it, and you’ll quickly notice some annoying behavior. If you press the
button, the LED sometimes will turn on and then off immediately. Also, if
you release it, the LED will often remain in a more or less arbitrary state; that
is, sometimes it will be on and sometimes off.
The problem is that the Arduino executes the
loop
method over and over again.
Although the Arduino’s CPU is comparatively slow, this would happen quite
often—regardless of whether we are currently pressing the button. But if you
press it and keep it pressed, its state will constantly be
HIGH
, and you’d con-
stantly toggle the LED’s state (because this happens so fast, it seems like the
LED is constantly on). When you release the button, the LED is in a more or
less arbitrary state.
To improve the situation, we have to store not only the LED’s current state,
but also the pushbutton’s previous state:
BinaryDice/MoreReliableSwitch/MoreReliableSwitch.ino
const unsigned int BUTTON_PIN = 7;
const unsigned int LED_PIN = 13;
void setup() {
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT);
}
int old_button_state = LOW;
int led_state = LOW;
void loop() {
const int CURRENT_BUTTON_STATE = digitalRead(BUTTON_PIN);
if (CURRENT_BUTTON_STATE != old_button_state && CURRENT_BUTTON_STATE == HIGH) {
if (led_state == LOW)
led_state = HIGH;
else
led_state = LOW;
digitalWrite(LED_PIN, led_state);
}
old_button_state = CURRENT_BUTTON_STATE;
}
report erratum • discuss
Working with Buttons • 51
www.it-ebooks.info