/ RNode_Firmware_CE_G2 / Input.h
Input.h
1 // Copyright (C) 2024, Mark Qvist 2 3 // This program is free software: you can redistribute it and/or modify 4 // it under the terms of the GNU General Public License as published by 5 // the Free Software Foundation, either version 3 of the License, or 6 // (at your option) any later version. 7 8 // This program is distributed in the hope that it will be useful, 9 // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 // GNU General Public License for more details. 12 13 // You should have received a copy of the GNU General Public License 14 // along with this program. If not, see <https://www.gnu.org/licenses/>. 15 16 #ifndef INPUT_H 17 #define INPUT_H 18 19 #define PIN_BUTTON pin_btn_usr1 20 21 #define PRESSED LOW 22 #define RELEASED HIGH 23 24 #define EVENT_ALL 0x00 25 #define EVENT_CLICKS 0x01 26 #define EVENT_BUTTON_DOWN 0x11 27 #define EVENT_BUTTON_UP 0x12 28 #define EVENT_BUTTON_CLICK 0x13 29 #define EVENT_BUTTON_DOUBLE_CLICK 0x14 30 #define EVENT_BUTTON_TRIPLE_CLICK 0x15 31 32 int button_events = EVENT_CLICKS; 33 int button_state = RELEASED; 34 int debounce_state = button_state; 35 unsigned long button_debounce_last = 0; 36 unsigned long button_debounce_delay = 25; 37 unsigned long button_down_last = 0; 38 unsigned long button_up_last = 0; 39 40 // Forward declaration 41 void button_event(uint8_t event, unsigned long duration); 42 43 void input_init() { 44 pinMode(PIN_BUTTON, INPUT_PULLUP); 45 } 46 47 void input_get_all_events() { 48 button_events = EVENT_ALL; 49 } 50 51 void input_get_click_events() { 52 button_events = EVENT_CLICKS; 53 } 54 55 void input_read() { 56 int button_reading = digitalRead(PIN_BUTTON); 57 if (button_reading != debounce_state) { 58 button_debounce_last = millis(); 59 debounce_state = button_reading; 60 } 61 62 if ((millis() - button_debounce_last) > button_debounce_delay) { 63 if (button_reading != button_state) { 64 // State changed 65 int previous_state = button_state; 66 button_state = button_reading; 67 68 if (button_events == EVENT_ALL) { 69 if (button_state == PRESSED) { 70 button_event(EVENT_BUTTON_DOWN, 0); 71 } else if (button_state == RELEASED) { 72 button_event(EVENT_BUTTON_UP, 0); 73 } 74 } else if (button_events == EVENT_CLICKS) { 75 if (previous_state == PRESSED && button_state == RELEASED) { 76 button_up_last = millis(); 77 button_event(EVENT_BUTTON_CLICK, button_up_last-button_down_last); 78 } else if (previous_state == RELEASED && button_state == PRESSED) { 79 button_down_last = millis(); 80 } 81 } 82 } 83 } 84 85 } 86 87 bool button_pressed() { 88 if (button_state == PRESSED) { 89 return true; 90 } else { 91 return false; 92 } 93 } 94 95 #endif