分享一款嵌入式開源按鍵框架代碼工程MultiButton

来源:https://www.cnblogs.com/Sharemaker/p/18137037
-Advertisement-
Play Games

一、工程簡介 MultiButton 是一個小巧簡單易用的事件驅動型按鍵驅動模塊。 Github地址:https://github.com/0x1abin/MultiButton 這個項目非常精簡,只有兩個文件: (1)可無限擴展按鍵; (2)按鍵事件的回調非同步處理方式可以簡化程式結構,去除冗餘的按 ...


一、工程簡介

  MultiButton 是一個小巧簡單易用的事件驅動型按鍵驅動模塊。

  Github地址:https://github.com/0x1abin/MultiButton

  這個項目非常精簡,只有兩個文件:

  (1)可無限擴展按鍵;

  (2)按鍵事件的回調非同步處理方式可以簡化程式結構,去除冗餘的按鍵處理硬編碼,讓按鍵業務邏輯更清晰。

  通過此工程可以學習到以下知識點:

  (1)按鍵各種類型事件;

  (2)狀態機的思想;

  (3)單向鏈表語法。

  工程支持如下的按鍵事件:

   MultiButton 的按鍵狀態及軟體流程圖:

 二、工程代碼分析

  註:在使用源碼工程時稍微修改了兩個點,後續貼出修改後的完整代碼,有需要查看修改的同學可以將源碼工程下載後進行對比,修改的點如下:

  (1)將按鍵時間的相關參數通過介面定義進行初始化;

  (2)修改按鍵長按期間一直觸發事件為真正的長按按鍵定時觸發事件。

  在頭文件multi_button.h中包括:

  (1)定義了按鍵時間相關參數;

  (2)定義了按鍵的事件類型;

  (3)定義按鍵鏈表結構體,這裡使用了位域操作,解決位元組的存儲空間問題。

 1 #ifndef _MULTI_BUTTON_H_
 2 #define _MULTI_BUTTON_H_
 3  
 4 #include <stdint.h>
 5 #include <string.h>
 6  
 7 typedef struct ButtonPara {
 8   uint8_t ticks_interval;
 9   uint8_t debounce_ticks;
10   uint16_t short_ticks;
11   uint16_t long_ticks;
12 }ButtonPara;
13  
14 typedef void (*BtnCallback)(void*);
15  
16 typedef enum {
17   PRESS_DOWN = 0,
18   PRESS_UP,
19   PRESS_REPEAT,
20   SINGLE_CLICK,
21   DOUBLE_CLICK,
22   LONG_PRESS_START,
23   LONG_PRESS_HOLD,
24   number_of_event,
25   NONE_PRESS
26 }PressEvent;
27  
28 typedef struct Button {
29   uint16_t ticks;
30   uint8_t  repeat : 4;
31   uint8_t  event : 4;
32   uint8_t  state : 3;
33   uint8_t  debounce_cnt : 3;
34   uint8_t  active_level : 1;
35   uint8_t  button_level : 1;
36   uint8_t  button_id;
37   uint8_t  (*hal_button_Level)(uint8_t button_id_);
38   BtnCallback  cb[number_of_event];
39   struct Button* next;
40 }Button;
41  
42 #ifdef __cplusplus
43 extern "C" {
44 #endif
45 void button_para_init(struct ButtonPara para);
46 void button_init(struct Button* handle, uint8_t(*pin_level)(uint8_t), uint8_t active_level, uint8_t button_id);
47 void button_attach(struct Button* handle, PressEvent event, BtnCallback cb);
48 PressEvent get_button_event(struct Button* handle);
49 int  button_start(struct Button* handle);
50 void button_stop(struct Button* handle);
51 void button_ticks(void);
52  
53 #ifdef __cplusplus
54 }
55 #endif
56  
57 #endif

  在源碼文件multi_button.c中包括:

  (1)對按鍵時間參數進行初始化;

  (2)對按鍵對象結構體進行初始化,初始化成員包括按鍵句柄,綁定GPIO電平讀取函數,設置有效觸發電平;

  (3)初始化按鍵完成之後,進行按鍵綁定操作,將綁定按鍵結構體成員,按鍵觸發事件,按鍵回調函數;

  (4)按鍵啟動:也就是將按鍵加入鏈表當中,啟動按鍵。這裡選擇的插入方式是頭部插入法,在鏈表的頭部插入按鍵節點,效率高,時間複雜度為O(1);

  (5)按鍵刪除:將按鍵從當前鏈表中刪除。使用到了二級指針刪除一個按鍵元素。與鏈表中成員刪除方法相同;

  (6)按鍵滴答函數:每間隔Nms觸發一次按鍵事件,驅動狀態機運行;

  (7)讀取當前引腳的狀態,獲取按鍵當前屬於哪種狀態;

  (8)按鍵處理核心函數,驅動狀態機。

  1 #include "multi_button.h"
  2  
  3 #define EVENT_CB(ev)   if(handle->cb[ev])handle->cb[ev]((void*)handle)
  4 #define PRESS_REPEAT_MAX_NUM  15 /*!< The maximum value of the repeat counter */
  5  
  6 static struct ButtonPara buttonpara;
  7 //button handle list head.
  8 static struct Button* head_handle = NULL;
  9  
 10 static void button_handler(struct Button* handle);
 11  
 12  
 13 void button_para_init(struct ButtonPara para)
 14 {
 15   buttonpara.ticks_interval = para.ticks_interval;
 16   buttonpara.debounce_ticks = para.debounce_ticks;
 17   buttonpara.short_ticks = para.short_ticks;
 18   buttonpara.long_ticks = para.long_ticks;
 19 }
 20 /**
 21   * @brief  Initializes the button struct handle.
 22   * @param  handle: the button handle struct.
 23   * @param  pin_level: read the HAL GPIO of the connected button level.
 24   * @param  active_level: pressed GPIO level.
 25   * @param  button_id: the button id.
 26   * @retval None
 27   */
 28 void button_init(struct Button* handle, uint8_t(*pin_level)(uint8_t), uint8_t active_level, uint8_t button_id)
 29 {
 30   memset(handle, 0, sizeof(struct Button));
 31   handle->event = (uint8_t)NONE_PRESS;
 32   handle->hal_button_Level = pin_level;
 33   handle->button_level = handle->hal_button_Level(button_id);
 34   handle->active_level = active_level;
 35   handle->button_id = button_id;
 36 }
 37  
 38 /**
 39   * @brief  Attach the button event callback function.
 40   * @param  handle: the button handle struct.
 41   * @param  event: trigger event type.
 42   * @param  cb: callback function.
 43   * @retval None
 44   */
 45 void button_attach(struct Button* handle, PressEvent event, BtnCallback cb)
 46 {
 47   handle->cb[event] = cb;
 48 }
 49  
 50 /**
 51   * @brief  Inquire the button event happen.
 52   * @param  handle: the button handle struct.
 53   * @retval button event.
 54   */
 55 PressEvent get_button_event(struct Button* handle)
 56 {
 57   return (PressEvent)(handle->event);
 58 }
 59  
 60 /**
 61   * @brief  Button driver core function, driver state machine.
 62   * @param  handle: the button handle struct.
 63   * @retval None
 64   */
 65 static void button_handler(struct Button* handle)
 66 {
 67   uint8_t read_gpio_level = handle->hal_button_Level(handle->button_id);
 68  
 69   //ticks counter working..
 70   if((handle->state) > 0) handle->ticks++;
 71  
 72   /*------------button debounce handle---------------*/
 73   if(read_gpio_level != handle->button_level) { //not equal to prev one
 74     //continue read 3 times same new level change
 75     if(++(handle->debounce_cnt) >= buttonpara.debounce_ticks) {
 76       handle->button_level = read_gpio_level;
 77       handle->debounce_cnt = 0;
 78     }
 79   } else { //level not change ,counter reset.
 80     handle->debounce_cnt = 0;
 81   }
 82  
 83   /*-----------------State machine-------------------*/
 84   switch (handle->state) {
 85   case 0:
 86     if(handle->button_level == handle->active_level) {  //start press down
 87       handle->event = (uint8_t)PRESS_DOWN;
 88       EVENT_CB(PRESS_DOWN);
 89       handle->ticks = 0;
 90       handle->repeat = 1;
 91       handle->state = 1;
 92     } else {
 93       handle->event = (uint8_t)NONE_PRESS;
 94     }
 95     break;
 96  
 97   case 1:
 98     if(handle->button_level != handle->active_level) { //released press up
 99       handle->event = (uint8_t)PRESS_UP;
100       EVENT_CB(PRESS_UP);
101       handle->ticks = 0;
102       handle->state = 2;
103     } else if(handle->ticks > buttonpara.long_ticks) {
104       handle->event = (uint8_t)LONG_PRESS_START;
105       EVENT_CB(LONG_PRESS_START);
106       handle->state = 5;
107     }
108     break;
109  
110   case 2:
111     if(handle->button_level == handle->active_level) { //press down again
112       handle->event = (uint8_t)PRESS_DOWN;
113       EVENT_CB(PRESS_DOWN);
114       if(handle->repeat != PRESS_REPEAT_MAX_NUM) {
115         handle->repeat++;
116       }
117       EVENT_CB(PRESS_REPEAT); // repeat hit
118       handle->ticks = 0;
119       handle->state = 3;
120     } else if(handle->ticks > buttonpara.short_ticks) { //released timeout
121       if(handle->repeat == 1) {
122         handle->event = (uint8_t)SINGLE_CLICK;
123         EVENT_CB(SINGLE_CLICK);
124       } else if(handle->repeat == 2) {
125         handle->event = (uint8_t)DOUBLE_CLICK;
126         EVENT_CB(DOUBLE_CLICK); // repeat hit
127       }
128       handle->state = 0;
129     }
130     break;
131  
132   case 3:
133     if(handle->button_level != handle->active_level) { //released press up
134       handle->event = (uint8_t)PRESS_UP;
135       EVENT_CB(PRESS_UP);
136       if(handle->ticks < buttonpara.short_ticks) {
137         handle->ticks = 0;
138         handle->state = 2; //repeat press
139       } else {
140         handle->state = 0;
141       }
142     } else if(handle->ticks > buttonpara.short_ticks) { // SHORT_TICKS < press down hold time < LONG_TICKS
143       handle->state = 1;
144     }
145     break;
146  
147   case 5:
148     if(handle->button_level == handle->active_level) {
149       //continue hold trigger
150       if(handle->ticks > buttonpara.long_ticks) {
151       handle->event = (uint8_t)LONG_PRESS_HOLD;
152       EVENT_CB(LONG_PRESS_HOLD);
153       handle->ticks = 0;
154       }
155     } else { //released
156       handle->event = (uint8_t)PRESS_UP;
157       EVENT_CB(PRESS_UP);
158       handle->state = 0; //reset
159     }
160     break;
161   default:
162     handle->state = 0; //reset
163     break;
164   }
165 }
166  
167 /**
168   * @brief  Start the button work, add the handle into work list.
169   * @param  handle: target handle struct.
170   * @retval 0: succeed. -1: already exist.
171   */
172 int button_start(struct Button* handle)
173 {
174   struct Button* target = head_handle;
175   while(target) {
176     if(target == handle) return -1;  //already exist.
177     target = target->next;
178   }
179   handle->next = head_handle;
180   head_handle = handle;
181   return 0;
182 }
183  
184 /**
185   * @brief  Stop the button work, remove the handle off work list.
186   * @param  handle: target handle struct.
187   * @retval None
188   */
189 void button_stop(struct Button* handle)
190 {
191   struct Button** curr;
192   for(curr = &head_handle; *curr; ) {
193     struct Button* entry = *curr;
194     if(entry == handle) {
195       *curr = entry->next;
196 //      free(entry);
197       return;//glacier add 2021-8-18
198     } else {
199       curr = &entry->next;
200     }
201   }
202 }
203  
204 /**
205   * @brief  background ticks, timer repeat invoking interval 5ms.
206   * @param  None.
207   * @retval None
208   */
209 void button_ticks(void)
210 {
211   struct Button* target;
212   for(target=head_handle; target; target=target->next) {
213     button_handler(target);
214   }
215 }

三、工程代碼應用

  以在freertos中應用為例,包括:

  (1)按鍵對象的定義及時間參數定義;

  (2)按鍵回調函數包括讀取按鍵電平函數和各按鍵事件處理函數的編寫;

  (3)按鍵初始化操作及啟動按鍵功能;

  (4)在while(1)中添加按鍵滴答函數。

  1 #define TICKS_INTERVAL    5  //按鍵狀態輪詢周期,單位ms
  2 #define DEBOUNCE_TICKS    3  //MAX 7 (0 ~ 7) 去抖時間次數,此為15ms/TICKS_INTERVAL=3次
  3 #define SHORT_TICKS       (300 /TICKS_INTERVAL) //短按時間次數,300ms/TICKS_INTERVAL 
  4 #define LONG_TICKS        (2000 /TICKS_INTERVAL) //長按時間次數,2000ms/TICKS_INTERVAL
  5          
  6 enum Button_IDs {
  7   btn1_id,
  8   btn2_id,
  9   btn3_id,
 10 };
 11 struct ButtonPara btnpara = {TICKS_INTERVAL, DEBOUNCE_TICKS, SHORT_TICKS, LONG_TICKS};
 12 struct Button btn1;
 13 struct Button btn2;
 14 struct Button btn3;
 15  
 16 //According to your need to modify the constants.
 17  
 18 uint8_t read_button_GPIO(uint8_t button_id)
 19 {
 20   // you can share the GPIO read function with multiple Buttons
 21   switch(button_id)
 22   {
 23     case btn1_id:
 24       return GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_4);
 25     case btn2_id:
 26       return GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_3);
 27     case btn3_id:
 28       return GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_2);
 29     default:
 30       return 0;
 31   }
 32 }
 33  
 34 void BTN1_PRESS_DOWN_Handler(void* btn)
 35 {
 36   printf("BTN1_PRESS_DOWN_Handler!\r\n");
 37 }
 38  
 39 void BTN1_PRESS_UP_Handler(void* btn)
 40 {
 41   printf("BTN1_PRESS_UP_Handler!\r\n");
 42 }
 43  
 44 void BTN1_PRESS_REPEAT_Handler(void* btn)
 45 {
 46   printf("BTN1_PRESS_REPEAT_Handler, repeatcount = %d!\r\n",btn1.repeat);
 47 }
 48  
 49 void BTN1_SINGLE_Click_Handler(void* btn)
 50 {
 51   printf("BTN1_SINGLE_Click_Handler!\r\n");
 52 }
 53  
 54 void BTN1_DOUBLE_Click_Handler(void* btn)
 55 {
 56   printf("BTN1_DOUBLE_Click_Handler!\r\n");
 57 }
 58  
 59 void BTN1_LONG_PRESS_START_Handler(void* btn)
 60 {
 61   printf("BTN1_LONG_PRESS_START_Handler!\r\n");
 62 }
 63  
 64 void BTN1_LONG_PRESS_HOLD_Handler(void* btn)
 65 {
 66   printf("BTN1_LONG_PRESS_HOLD_Handler!\r\n");
 67 }
 68  
 69 void BTN2_SINGLE_Click_Handler(void* btn)
 70 {
 71   printf("BTN2_SINGLE_Click_Handler!\r\n");
 72 }
 73  
 74 void BTN2_DOUBLE_Click_Handler(void* btn)
 75 {
 76   printf("BTN2_DOUBLE_Click_Handler!\r\n");
 77 }
 78  
 79 void BTN3_LONG_PRESS_START_Handler(void* btn)
 80 {
 81   printf("BTN3_LONG_PRESS_START_Handler!\r\n");
 82 }
 83  
 84 void BTN3_LONG_PRESS_HOLD_Handler(void* btn)
 85 {
 86   printf("BTN3_LONG_PRESS_HOLD_Handler!\r\n");
 87 }
 88  
 89 int main(void)
 90 { 
 91   button_para_init(btnpara);
 92   button_init(&btn1, read_button_GPIO, 0, btn1_id);
 93   button_init(&btn2, read_button_GPIO, 0, btn2_id);
 94   button_init(&btn3, read_button_GPIO, 0, btn3_id);
 95  
 96   button_attach(&btn1, PRESS_DOWN,       BTN1_PRESS_DOWN_Handler);
 97   button_attach(&btn1, PRESS_UP,         BTN1_PRESS_UP_Handler);
 98   button_attach(&btn1, PRESS_REPEAT,     BTN1_PRESS_REPEAT_Handler);
 99   button_attach(&btn1, SINGLE_CLICK,     BTN1_SINGLE_Click_Handler);
100   button_attach(&btn1, DOUBLE_CLICK,     BTN1_DOUBLE_Click_Handler);
101   button_attach(&btn1, LONG_PRESS_START, BTN1_LONG_PRESS_START_Handler);
102   button_attach(&btn1, LONG_PRESS_HOLD,  BTN1_LONG_PRESS_HOLD_Handler);
103  
104   button_attach(&btn2, PRESS_REPEAT,     BTN2_PRESS_REPEAT_Handler);
105   button_attach(&btn2, SINGLE_CLICK,     BTN2_SINGLE_Click_Handler);
106   button_attach(&btn2, DOUBLE_CLICK,     BTN2_DOUBLE_Click_Handler);
107   
108   button_attach(&btn3, LONG_PRESS_START, BTN3_LONG_PRESS_START_Handler);
109   button_attach(&btn3, LONG_PRESS_HOLD,  BTN3_LONG_PRESS_HOLD_Handler);
110  
111   button_start(&btn1);
112   button_start(&btn2);
113   button_start(&btn3);
114   
115  
116   xTaskCreate((TaskFunction_t )key_task,             
117                 (const char*    )"key_task",           
118                 (uint16_t       )KEY_STK_SIZE,        
119                 (void*          )NULL,                  
120                 (UBaseType_t    )KEY_TASK_PRIO,        
121                 (TaskHandle_t*  )&KeyTask_Handler);              
122     vTaskStartScheduler();          
123 }
124  
12

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • LiteDB 是一個輕量級的嵌入式 NoSQL 資料庫,其設計理念與 MongoDB 類似,但它是完全使用 C# 開發的,因此與 C# 應用程式的集成非常順暢。與 SQLite 相比,LiteDB 提供了 NoSQL(即鍵值對)的數據存儲方式,並且是一個開源且免費的項目。它適用於桌面、移動以及 We ...
  • 經過前面幾篇的學習,我們瞭解到指令的大概分類,如:參數載入指令,該載入指令以 Ld 開頭,將參數載入到棧中,以便於後續執行操作命令。參數存儲指令,其指令以 St 開頭,將棧中的數據,存儲到指定的變數中,以方便後續使用。創建實例指令,其指令以 New 開頭,用於在運行時動態生成並初始化對象。方法調用指... ...
  • 為.net6在CentOS7上面做準備,先在vmware虛擬機安裝CentOS 7.9 新建CentOS764位的系統 因為CentOS8不更新了,所以安裝7;簡單就一筆帶過了 選擇下載好的操作系統的iso文件,下載地址https://mirrors.aliyun.com/centos/7.9.20 ...
  • 引言 上一章節介紹了 TDD 的三大法則,今天我們講一下在單元測試中模擬對象的使用。 Fake Fake - Fake 是一個通用術語,可用於描述 stub或 mock 對象。 它是 stub 還是 mock 取決於使用它的上下文。 也就是說,Fake 可以是 stub 或 mock Mock - ...
  • 概述:WPF界面綁定和渲染大量數據可能導致性能問題。通過啟用UI虛擬化、非同步載入和數據分頁,可以有效提高界面響應性能。以下是簡單示例演示這些優化方法。 在WPF中,當你嘗試綁定和渲染大量的數據項時,性能問題可能出現。以下是一些可能導致性能慢的原因以及優化方法: UI 虛擬化: WPF提供了虛擬化技術 ...
  • 1.Linux上安裝Docken 伺服器系統版本以及內核版本:cat /etc/redhat-release 查看伺服器內核版本:uname -r 安裝依賴包:yum install -y yum-utils device-mapper-persistent-data lvm2 設置阿裡雲鏡像源:y ...
  • 概述:通過使用`SemaphoreSlim`,可以簡單而有效地限制非同步HTTP請求的併發量,確保在任何給定時間內不超過20個網頁同時下載。`ParallelOptions`不適用於非同步操作,但可考慮使用`Parallel.ForEach`,儘管在非同步場景中謹慎使用。 對於併發非同步 I/O 操作的數量 ...
  • 隨著Aspire發佈preview5的發佈,Microsoft.Extensions.ServiceDiscovery隨之更新, 服務註冊發現這個屬於老掉牙的話題解決什麼問題就不贅述了,這裡主要講講Microsoft.Extensions.ServiceDiscovery(preview5)以及如何 ...
一周排行
    -Advertisement-
    Play Games
  • GoF之工廠模式 @目錄GoF之工廠模式每博一文案1. 簡單說明“23種設計模式”1.2 介紹工廠模式的三種形態1.3 簡單工廠模式(靜態工廠模式)1.3.1 簡單工廠模式的優缺點:1.4 工廠方法模式1.4.1 工廠方法模式的優缺點:1.5 抽象工廠模式1.6 抽象工廠模式的優缺點:2. 總結:3 ...
  • 新改進提供的Taurus Rpc 功能,可以簡化微服務間的調用,同時可以不用再手動輸出模塊名稱,或調用路徑,包括負載均衡,這一切,由框架實現並提供了。新的Taurus Rpc 功能,將使得服務間的調用,更加輕鬆、簡約、高效。 ...
  • 本章將和大家分享ES的數據同步方案和ES集群相關知識。廢話不多說,下麵我們直接進入主題。 一、ES數據同步 1、數據同步問題 Elasticsearch中的酒店數據來自於mysql資料庫,因此mysql數據發生改變時,Elasticsearch也必須跟著改變,這個就是Elasticsearch與my ...
  • 引言 在我們之前的文章中介紹過使用Bogus生成模擬測試數據,今天來講解一下功能更加強大自動生成測試數據的工具的庫"AutoFixture"。 什麼是AutoFixture? AutoFixture 是一個針對 .NET 的開源庫,旨在最大程度地減少單元測試中的“安排(Arrange)”階段,以提高 ...
  • 經過前面幾個部分學習,相信學過的同學已經能夠掌握 .NET Emit 這種中間語言,並能使得它來編寫一些應用,以提高程式的性能。隨著 IL 指令篇的結束,本系列也已經接近尾聲,在這接近結束的最後,會提供幾個可供直接使用的示例,以供大伙分析或使用在項目中。 ...
  • 當從不同來源導入Excel數據時,可能存在重覆的記錄。為了確保數據的準確性,通常需要刪除這些重覆的行。手動查找並刪除可能會非常耗費時間,而通過編程腳本則可以實現在短時間內處理大量數據。本文將提供一個使用C# 快速查找並刪除Excel重覆項的免費解決方案。 以下是實現步驟: 1. 首先安裝免費.NET ...
  • C++ 異常處理 C++ 異常處理機制允許程式在運行時處理錯誤或意外情況。它提供了捕獲和處理錯誤的一種結構化方式,使程式更加健壯和可靠。 異常處理的基本概念: 異常: 程式在運行時發生的錯誤或意外情況。 拋出異常: 使用 throw 關鍵字將異常傳遞給調用堆棧。 捕獲異常: 使用 try-catch ...
  • 優秀且經驗豐富的Java開發人員的特征之一是對API的廣泛瞭解,包括JDK和第三方庫。 我花了很多時間來學習API,尤其是在閱讀了Effective Java 3rd Edition之後 ,Joshua Bloch建議在Java 3rd Edition中使用現有的API進行開發,而不是為常見的東西編 ...
  • 框架 · 使用laravel框架,原因:tp的框架路由和orm沒有laravel好用 · 使用強制路由,方便介面多時,分多版本,分文件夾等操作 介面 · 介面開發註意欄位類型,欄位是int,查詢成功失敗都要返回int(對接java等強類型語言方便) · 查詢介面用GET、其他用POST 代碼 · 所 ...
  • 正文 下午找企業的人去鎮上做貸後。 車上聽同事跟那個司機對罵,火星子都快出來了。司機跟那同事更熟一些,連我在內一共就三個人,同事那一手指桑罵槐給我都聽愣了。司機也是老社會人了,馬上聽出來了,為那個無辜的企業經辦人辯護,實際上是為自己辯護。 “這個事情你不能怪企業。”“但他們總不能讓銀行的人全權負責, ...