1+ /*
2+ Turns an LED on when the button is pressed and off when the button is released.
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+ #include " CustomButton.h"
13+
14+ // Change these if your button or LED are on other pins.
15+ int buttonPin = 8 ;
16+ int ledPin = 9 ;
17+
18+ // The button will automatically configure the button pin.
19+ CustomButton button (buttonPin);
20+
21+ // Used for timing.
22+ unsigned long intervalStartTime;
23+ const int fastBlinkInterval = 100 ;
24+ bool timing;
25+
26+ void setup ()
27+ {
28+ // Setup the output LED.
29+ pinMode (ledPin, OUTPUT);
30+ digitalWrite (ledPin, LOW);
31+ }
32+
33+ void loop ()
34+ {
35+ // Hold the button down to turn the LED on and release it to turn it off.
36+ switch (button.getBehavior ())
37+ {
38+ case CustomButton::LIGHTOFF:
39+ {
40+ // Turn off the light and make sure timing is turned off.
41+ digitalWrite (ledPin, LOW);
42+ timing = false ;
43+ break ;
44+ }
45+
46+ case CustomButton::BLINKONCE:
47+ {
48+ // Turn on the light for 1 second. We won't bother with timing for this.
49+ digitalWrite (ledPin, HIGH);
50+ delay (1000 );
51+ break ;
52+ }
53+
54+ case CustomButton::FASTBLINK:
55+ {
56+ // If we are not timing, then we start it. That is, we have determine the button is being
57+ // held down and this is the first pass through the loop since the long press was activated.
58+ //
59+ // If we are already timing, we need to alternate the status of the light everytime the
60+ // timing interval is up.
61+ if (!timing)
62+ {
63+ // Turn on the light and start the timing.
64+ digitalWrite (ledPin, HIGH);
65+ intervalStartTime = millis ();
66+ timing = true ;
67+ }
68+ else
69+ {
70+ // Check if the timing interval is up.
71+ if (millis () - intervalStartTime > fastBlinkInterval)
72+ {
73+ // Swap the state of the LED light. If it's off, turn it on and vice versa.
74+ // This is done by reading the current status of the pin, negating it and
75+ // passing it to the write function.
76+ digitalWrite (ledPin, !digitalRead (ledPin));
77+
78+ // Restart the timing.
79+ intervalStartTime = millis ();
80+ }
81+ }
82+ break ;
83+ }
84+ }
85+ }
0 commit comments