PushME Keypad Reader for FreeRTOS
My fancy, event-based keypad reader library PushME is on my website for a while and its time to add FreeRTOS support now. Since reading multiple buttons and keeping track of events like long-press or repetitive-press is a critical task for many embedded projects, the FreeRTOS version will help you on medium to large scale FreeRTOS projects. Let’s get hands dirty ?
Design with FreeRTOS
Experts know that in FreeRTOS there is no unique way to implement your code architecture but many options are available. Preferences between different methods like using mutex or binary-semaphore is up to your requirements and trade-offs. So I created a single task out of keypadRead() function of original library. This task sleeps for a while every time using vTaskDelay(), so there is no problem giving high task priority. It could also be a software timer depending on the task priority of the timer service.
1 2 3 4 |
void keypadRead(void *param) { //... vTaskDelay(KEY_TASKDELAY_TIME / portTICK_PERIOD_MS); } |
The most straightforward replacement for long-press and debounce timeouts is of course FreeRTOS timer. But unfortunately those timers can’t be configured for being checked for timeout but they have their own obligatory callback. Since we need a timer that can be polled for expiration, this callback has to be a dummy place holder function keypadDummyTimerCallback(). We will create one-shot timers using xTimerCreate() and poll them using xTimerIsTimerActive(). This seems the only way for replacing the timeout functionality of the original library with FreeRTOS timer. Switching between different delays is done by a call to xTimerChangePeriod() is followed by xTimerReset(). Here task can be preempted between two calls by higher priority tasks but fortunately large tolerances is acceptable for those timers.
Finally, the keypadRead() task can monitor the buttons and keys with success. Next thing to do is the communication between this task and the clients.
There are many options for talking to clients. The most user-friendly option is implementing a subscribing mechanism such that every client could subscribe its desired key combinations and PushME could unblock them using binary-semaphore by xSemaphoreGive() on match. However it is the bulkiest way of doing this.
Another option is using 1-dimensional queue and posting the results with xQueueOverwrite(). This option is cool for the library side but the client has to poll the last event with xQueueReceive() for a match. If there are multiple listeners everybody should peek the queue by xQueuePeek() instead of emptying the queue. But waking up (unblocking) all the clients on every cycle of the library is not so efficient.
The last but the best option is event-group since this method provides wake-on-match functionality. To be more specific, every client can block on a specific key combination using xEventGroupWaitBits() which is the most efficient way for our case. Although this option does what we need, it has two problems. First problem is on the library side. It has no method for overwriting/setting the value at once. First we need to clear old value using xEventGroupClearBits() then set the new value using xEventGroupSetBits(). Another problem is that the client does not have the option to check/compare the whole event-group value with the expected but can only check for 1 bits. What I try to say is, a client waiting for 0x06 will also unblock for 0x07 by-design. Due to the drawbacks of event-group, I additionally provide queue option to the user.
The Library Code
Here is the library code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 |
/** * @file keypad.c * @author Atakan S. * @date 01/01/2018 * @version 1.0 * @brief "PushME" Event based keypad reader module with debouncing. * * @copyright Copyright (c) 2018 Atakan SARIOGLU ~ www.atakansarioglu.com * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include <porty.h> #ifdef _H_KEYPAD_H // Exclude from compile when not included in projech.h #include <keypad.h> #include <FreeRTOS.h> #include <task.h> #include <timers.h> EventGroupHandle_t keypadEventGroup = NULL; QueueHandle_t keypadQueue = NULL; static void keypadDummyTimerCallback(TimerHandle_t xTimer) { } // Struct to keep the variables of the keypad module. typedef struct { //-- Key events. uint16_t keysPressed; // PORT POLLING register uint16_t keysDown; // uint16_t keysReleased; // TimerHandle_t timerDebounce; TimerHandle_t timerLong; uint8_t counterBoost; } tKeypad; // Initialize the variables. tKeypad keypad = { .keysPressed = 0, .keysDown = 0, .keysReleased = 0, .counterBoost = 0, }; // This function reads the pin values and writes to bits of a variable. uint16_t keypadSerialize(void) { uint16_t result = 0; #ifdef KEY00_pin result |= (mPinRead(KEY00_pin) == KEY00_active) ? KEY00 : 0; #endif #ifdef KEY01_pin result |= (mPinRead(KEY01_pin) == KEY01_active) ? KEY01 : 0; #endif #ifdef KEY02_pin result |= (mPinRead(KEY02_pin) == KEY02_active) ? KEY02 : 0; #endif #ifdef KEY03_pin result |= (mPinRead(KEY03_pin) == KEY03_active) ? KEY03 : 0; #endif #ifdef KEY04_pin result |= (mPinRead(KEY04_pin) == KEY04_active) ? KEY04 : 0; #endif #ifdef KEY05_pin result |= (mPinRead(KEY05_pin) == KEY05_active) ? KEY05 : 0; #endif #ifdef KEY06_pin result |= (mPinRead(KEY06_pin) == KEY06_active) ? KEY06 : 0; #endif #ifdef KEY07_pin result |= (mPinRead(KEY07_pin) == KEY07_active) ? KEY07 : 0; #endif #ifdef KEY08_pin result |= (mPinRead(KEY08_pin) == KEY08_active) ? KEY08 : 0; #endif #ifdef KEY09_pin result |= (mPinRead(KEY09_pin) == KEY09_active) ? KEY09 : 0; #endif #ifdef KEY10_pin result |= (mPinRead(KEY10_pin) == KEY10_active) ? KEY10 : 0; #endif #ifdef KEY11_pin result |= (mPinRead(KEY11_pin) == KEY11_active) ? KEY11 : 0; #endif #ifdef KEY12_pin result |= (mPinRead(KEY12_pin) == KEY12_active) ? KEY12 : 0; #endif #ifdef KEY13_pin result |= (mPinRead(KEY13_pin) == KEY13_active) ? KEY13 : 0; #endif #ifdef KEY14_pin result |= (mPinRead(KEY14_pin) == KEY14_active) ? KEY14 : 0; #endif return result; } //-- Read keypad. void keypadRead(void *param) { // Create timers. keypad.timerDebounce = xTimerCreate("Debounce", (KEY_DEBOUNCE_TIME / portTICK_PERIOD_MS), pdFALSE, (void *) 0, keypadDummyTimerCallback); keypad.timerLong = xTimerCreate("LongPress", (KEY_LONGPRESS_TIME / portTICK_PERIOD_MS), pdFALSE, (void *) 0, keypadDummyTimerCallback); // Create Event Group. keypadEventGroup = xEventGroupCreate(); xEventGroupClearBits(keypadEventGroup, KEY_EVENTBITMASK); // Create Queue. keypadQueue = xQueueCreate(1, sizeof(uint32_t)); while(true){ //-- All release events processed in the last cycle are cleared. keypad.keysReleased &= KEYLONG; //Release=0 // Read all the keys to variable. keypad.keysPressed = keypadSerialize(); //-- If pressed. if (keypad.keysPressed) { //-- If pressed and seen for the first time. if (keypad.keysPressed != keypad.keysDown) { keypad.keysReleased &= ~KEYLONG; //Long=0 keypad.counterBoost = 0; // Set periods and reset timers. xTimerChangePeriod(keypad.timerDebounce, (KEY_DEBOUNCE_TIME / portTICK_PERIOD_MS), portMAX_DELAY); xTimerReset(keypad.timerDebounce, portMAX_DELAY); xTimerChangePeriod(keypad.timerLong, (KEY_LONGPRESS_TIME / portTICK_PERIOD_MS), portMAX_DELAY); xTimerReset(keypad.timerLong, portMAX_DELAY); } //-- Remember what is just seen. keypad.keysDown |= keypad.keysPressed; //-- Longpress timeout check. //-- If this is the first Longpress event or REPEAT is enabled (KEY_LONGPRESS_REPEAT_TIME > 0). if (!xTimerIsTimerActive(keypad.timerLong) && (((keypad.keysReleased & KEYLONG) == 0) || KEY_LONGPRESS_REPEAT_TIME)) { keypad.keysReleased = keypad.keysDown | KEYLONG; //Release=Down, Long=1 // If number of REPEAT events are greater than KEY_LONGPRESS_BOOST_THRESHOLD and BOOST is enabled. if (KEY_LONGPRESS_BOOST_THRESHOLD && (++keypad.counterBoost > KEY_LONGPRESS_BOOST_THRESHOLD)) { keypad.counterBoost = KEY_LONGPRESS_BOOST_THRESHOLD; xTimerChangePeriod(keypad.timerLong, (KEY_LONGPRESS_BOOST_TIME / portTICK_PERIOD_MS), portMAX_DELAY); xTimerReset(keypad.timerLong, portMAX_DELAY); } else { xTimerChangePeriod(keypad.timerLong, (KEY_LONGPRESS_REPEAT_TIME / portTICK_PERIOD_MS), portMAX_DELAY); xTimerReset(keypad.timerLong, portMAX_DELAY); } } } else { //-- Keypress timeout check. if (!xTimerIsTimerActive(keypad.timerDebounce)) { if ((keypad.keysReleased & KEYLONG) == 0) { keypad.keysReleased = keypad.keysDown; //Release=Down } } //-- Reset all. keypad.keysDown = 0; keypad.keysReleased &= ~KEYLONG; //Long=0 keypad.counterBoost = 0; //-- Set periods and reset timers. xTimerChangePeriod(keypad.timerDebounce, (KEY_DEBOUNCE_TIME / portTICK_PERIOD_MS), portMAX_DELAY); xTimerReset(keypad.timerDebounce, portMAX_DELAY); xTimerChangePeriod(keypad.timerLong, (KEY_LONGPRESS_TIME / portTICK_PERIOD_MS), portMAX_DELAY); xTimerReset(keypad.timerLong, portMAX_DELAY); } // Broadcast event to notify any waiters. xEventGroupClearBits(keypadEventGroup, KEY_EVENTBITMASK); xEventGroupSetBits(keypadEventGroup, (keypad.keysReleased & KEY_EVENTBITMASK)); // Send to queue to notify any receivers. xQueueOverwrite(keypadQueue, &keypad.keysReleased); // Delay. vTaskDelay(KEY_TASKDELAY_TIME / portTICK_PERIOD_MS); } } bool isKeyDown(uint16_t m) { return ((keypad.keysDown == (m)) && (keypad.keysReleased == 0)); } bool isKeyPress(uint16_t m) { return ((keypad.keysReleased == (m))); } bool isKeyHold(uint16_t m) { return ((keypad.keysReleased == (m | KEYLONG))); } #endif |
And header file follows.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
/** * @file keypad.h * @author Atakan S. * @date 01/01/2018 * @version 1.0 * @brief "PushME" Event based keypad reader module with debouncing. * * @copyright Copyright (c) 2018 Atakan SARIOGLU ~ www.atakansarioglu.com * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #ifndef _H_KEYPAD_H #define _H_KEYPAD_H #include <porty.h> #include <FreeRTOS.h> #include <event_groups.h> #include <queue.h> //-- Settings. #define KEY_TASKDELAY_TIME 5UL #define KEY_DEBOUNCE_TIME 50UL #define KEY_LONGPRESS_TIME 1000UL #define KEY_LONGPRESS_REPEAT_TIME 1000UL #define KEY_LONGPRESS_BOOST_TIME 50UL #define KEY_LONGPRESS_BOOST_THRESHOLD 8 //-- Definitions (DONT TOUCH) #if configUSE_16_BIT_TICKS == 1 #define KEY_EVENTBITMASK 0x00FFU #define KEY00 0x0001 #define KEY01 0x0002 #define KEY02 0x0004 #define KEY03 0x0008 #define KEY04 0x0010 #define KEY05 0x0020 #define KEY06 0x0040 #define KEYLONG 0x0080 #else #define KEY_EVENTBITMASK 0x00FFFFFFU #define KEY00 0x0001 #define KEY01 0x0002 #define KEY02 0x0004 #define KEY03 0x0008 #define KEY04 0x0010 #define KEY05 0x0020 #define KEY06 0x0040 #define KEY07 0x0080 #define KEY08 0x0100 #define KEY09 0x0200 #define KEY10 0x0400 #define KEY11 0x0800 #define KEY12 0x1000 #define KEY13 0x2000 #define KEY14 0x4000 #define KEYLONG 0x8000 #endif //-- Extern. extern EventGroupHandle_t keypadEventGroup; extern QueueHandle_t keypadQueue; //-- Prototypes. void keypadRead(void *param); bool isKeyDown(uint16_t m); // Key(s) is just down. bool isKeyPress(uint16_t m); // Key(s) is pressed. bool isKeyHold(uint16_t m); // Key(s) is held down. #endif |
Usage Example
Now let’s see the usage. Please check the following example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
/** * @file board.c * @author Atakan S. * @date 01/01/2018 * @version 1.0 * @brief PushME on FreeRTOS demo code. * * @copyright Copyright (c) 2018 Atakan SARIOGLU ~ www.atakansarioglu.com * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ // PORTY #include <porty.h> // FreeRTOS Kernel includes. #include <FreeRTOS.h> #include <task.h> #include <queue.h> #include <timers.h> // Definitions typedef enum { TOGGLE_LED_Blue_KEY = (KEY00), TOGGLE_LED_Green_KEY = (KEY00 | KEYLONG), } tToggleKeys; // LED Blue Toggle Task. static void prvTaskToggleLEDBlue(void * param) { uint32_t keypadValue; while (true) { if (xQueueReceive(keypadQueue, &keypadValue, portMAX_DELAY) && (keypadValue == TOGGLE_LED_Blue_KEY)) mPinWrite(LED_Blue, !mPinRead(LED_Blue)); } } // LED Blue Toggle Task. static void prvTaskToggleLEDGreen(void * param) { while (true) { // Wait on the desired key combination. xEventGroupWaitBits(keypadEventGroup, TOGGLE_LED_Green_KEY, pdTRUE, pdTRUE, portMAX_DELAY); mPinWrite(LED_Green, !mPinRead(LED_Green)); } } int main(void) { // Initialize hardware: GPIO, CLOCKS and NVIC. Board_Init(); // Create LED Toggling tasks. xTaskCreate(prvTaskToggleLEDBlue, "LEDBlue", configMINIMAL_STACK_SIZE, NULL, (tskIDLE_PRIORITY + 1), NULL); xTaskCreate(prvTaskToggleLEDGreen, "LEDGreen", configMINIMAL_STACK_SIZE, NULL, (tskIDLE_PRIORITY + 2), NULL); // Create PushME poller task with highest priority. xTaskCreate(keypadRead, "PushME", configMINIMAL_STACK_SIZE, NULL, (tskIDLE_PRIORITY + 3), NULL); // Start FreeRTOS scheduler. vTaskStartScheduler(); while (true); // Program should not reach here. return 1; } |
Download
This is an ongoing work and I want to make a united library code that can be used with both FreeRTOS and Porty/Punctual (That’s why the current version is on a different branch). You can get the whole project here that can be run on STM32-VLDiscovery board out-of-the-box. Have good time using it ?