|
| 1 | +/* |
| 2 | + * This example demonstrates usage of interrupt by detecting a button press. |
| 3 | + * |
| 4 | + * Setup: Connect first button between pin defined in BUTTON1 and GND |
| 5 | + * Similarly connect second button between pin defined in BUTTON2 and GND. |
| 6 | + * If you do not have a button simply connect a wire to those buttons |
| 7 | + * - touching GND pin with other end of the wire will behave same as pressing the connected button. |
| 8 | + * Wen using the bare wire be careful not to touch any other pin by accident. |
| 9 | + * |
| 10 | + * Note: There is no de-bounce implemented and the physical connection will normally |
| 11 | + * trigger many more button presses than actually happened. |
| 12 | + * This is completely normal and is not to be considered a fault. |
| 13 | + */ |
| 14 | + |
| 15 | + |
1 | 16 | #include <Arduino.h>
|
2 | 17 | #include <FunctionalInterrupt.h>
|
3 | 18 |
|
4 | 19 | #define BUTTON1 16
|
5 | 20 | #define BUTTON2 17
|
6 | 21 |
|
7 |
| -class Button |
8 |
| -{ |
| 22 | +class Button{ |
9 | 23 | public:
|
10 | 24 | Button(uint8_t reqPin) : PIN(reqPin){
|
11 | 25 | pinMode(PIN, INPUT_PULLUP);
|
12 |
| - attachInterrupt(PIN, std::bind(&Button::isr,this), FALLING); |
13 | 26 | };
|
14 |
| - ~Button() { |
| 27 | + |
| 28 | + void begin(){ |
| 29 | + attachInterrupt(PIN, std::bind(&Button::isr,this), FALLING); |
| 30 | + Serial.printf("Started button interrupt on pin %d\n", PIN); |
| 31 | + } |
| 32 | + |
| 33 | + ~Button(){ |
15 | 34 | detachInterrupt(PIN);
|
16 | 35 | }
|
17 | 36 |
|
18 |
| - void ARDUINO_ISR_ATTR isr() { |
| 37 | + void ARDUINO_ISR_ATTR isr(){ |
19 | 38 | numberKeyPresses += 1;
|
20 | 39 | pressed = true;
|
21 | 40 | }
|
22 | 41 |
|
23 |
| - void checkPressed() { |
| 42 | + void checkPressed(){ |
24 | 43 | if (pressed) {
|
25 | 44 | Serial.printf("Button on pin %u has been pressed %u times\n", PIN, numberKeyPresses);
|
26 | 45 | pressed = false;
|
27 | 46 | }
|
28 | 47 | }
|
29 | 48 |
|
30 | 49 | private:
|
31 |
| - const uint8_t PIN; |
| 50 | + const uint8_t PIN; |
32 | 51 | volatile uint32_t numberKeyPresses;
|
33 | 52 | volatile bool pressed;
|
34 | 53 | };
|
35 | 54 |
|
36 | 55 | Button button1(BUTTON1);
|
37 | 56 | Button button2(BUTTON2);
|
38 | 57 |
|
39 |
| - |
40 | 58 | void setup() {
|
41 | 59 | Serial.begin(115200);
|
| 60 | + while(!Serial) delay(10); |
| 61 | + Serial.println("Starting Functional Interrupt example."); |
| 62 | + button1.begin(); |
| 63 | + button2.begin(); |
| 64 | + Serial.println("Setup done."); |
42 | 65 | }
|
43 | 66 |
|
44 | 67 | void loop() {
|
|
0 commit comments