前提知识
基本概念
一个函数作为另外一个函数的一个参数;
是一种异步机制。
例如,一个按键初始化函数
1
| void button_init(struct Button* handle, uint8_t(*pin_level)(void), uint8_t active_level);
|
1 2 3 4 5 6 7 8 9
| void button_init(struct Button* handle, uint8_t(*pin_level)(void), uint8_t active_level) { memset(handle, 0, sizeof(struct Button)); handle->event = (uint8_t)NONE_PRESS; handle->hal_button_Level = pin_level; handle->button_level = handle->hal_button_Level(); handle->active_level = active_level; }
|
参数 |
作用 |
说明 |
struct Button* handle |
按键句柄 |
表示每个具体的按键 |
uint8_t (*pin_level)(void) |
读取引脚电平值 |
回调函数/函数指针,uint8_t为返回值,pin_level为函数名,void为参数 |
uint8_t active_level |
按键按下是高or低电平 |
0表示低电平时,按键按下;1表示高电平时,按键按下 |
使用方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| struct Button btn1;
uint8_t read_button1_GPIO() { return HAL_GPIO_ReadPin(B1_GPIO_Port, B1_Pin); }
button_init(&btn1, read_button1_GPIO, 0);
|
简化声明
typedef:给数据类型起别名
简化
1 2 3 4 5 6 7 8 9 10 11
| typedef uint8_t (*pin_level)(void);
void button_init(struct Button* handle,pin_level my_cb, uint8_t active_level) { memset(handle, 0, sizeof(struct Button)); handle->event = (uint8_t)NONE_PRESS; handle->hal_button_Level = my_cb; handle->button_level = handle->hal_button_Level(); handle->active_level = active_level; }
|
使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| struct Button btn1;
uint8_t read_button1_GPIO() { return HAL_GPIO_ReadPin(B1_GPIO_Port, B1_Pin); }
button_init(&btn1, read_button1_GPIO, 0);
|
数组形式
数组
数组:数据结构,存储相同数据类型的元素,
数据类型 数组名称[数组大小]
其中数组名称为首元素的地址,即 &数组名称[0],&为取该地址的值
回调函数的数组
按键触发事件有:单击、双击、长按、短按、按下、弹起等,每个事件触发以后,要做什么事情,由用户决定
能否同时建立多个回调函数,分别执行对应的触发事件,
使用数组:参数
1 2 3 4 5 6 7
| typedef void (*BtnCallback)(void*);
BtnCallback cb[number_of_event];
|