|
| 1 | +/* |
| 2 | + Toggles an LED between on and off with each press of the button. |
| 3 | +
|
| 4 | + The button should be wired such that when pressed, the "buttonPin" is |
| 5 | + connected to ground. |
| 6 | +
|
| 7 | + The LED should be wired with the "ledPin" to the positive lead and the |
| 8 | + negative lead should be connected to ground. A current limiting resistor |
| 9 | + should be used. |
| 10 | +*/ |
| 11 | + |
| 12 | +/* |
| 13 | + Please note the difference between the examples MomentaryButton_Demo_02 and |
| 14 | + LatchingButton_Demo_01. Both examples toggle an LED on and off but one uses |
| 15 | + a MomentaryButton and one uses the LatchingButton. While the behavior is the |
| 16 | + same for these simple examples, there is an important difference. In the case |
| 17 | + of the MomentaryButton, the state of the LED (on or off) is not known. For the |
| 18 | + LatchingButton, it is known what state the button (and therefore LED) is in. |
| 19 | +*/ |
| 20 | + |
| 21 | +#include "MomentaryButton.h" |
| 22 | + |
| 23 | +// Change these if your button or LED are on other pins. |
| 24 | +int buttonPin = 8; |
| 25 | +int ledPin = 9; |
| 26 | + |
| 27 | +// The MomentaryButton will automatically configure the button pin. |
| 28 | +MomentaryButton button(buttonPin); |
| 29 | + |
| 30 | +void setup() |
| 31 | +{ |
| 32 | + // Setup the output LED. |
| 33 | + pinMode(ledPin, OUTPUT); |
| 34 | + digitalWrite(ledPin, LOW); |
| 35 | +} |
| 36 | + |
| 37 | +void loop() |
| 38 | +{ |
| 39 | + // Press the button once to turn the LED on and again it to turn it off. This only captures button release |
| 40 | + // events, i.e., nothing happens when the button is pressed down, only after the release. |
| 41 | + if (button.wasPressed()) |
| 42 | + { |
| 43 | + // The button was pressed, so toggle the LED state. To toggle it, the current value is read (digitalRead) |
| 44 | + // and negated. The result is written back to the pin to change its state. |
| 45 | + digitalWrite(ledPin, !digitalRead(ledPin)); |
| 46 | + } |
| 47 | +} |
0 commit comments