实际上在蓝牙样板程序中已经包含了按键部分的初始化,我们只需要根据自己的板子做很少的配置工作,buttons_init()函数如下:
最后,按键初始化好之后,还需要调用app_button_enable()函数,按键才能正常使用。
static void buttons_init(void)
{
// Note: Array must be static because a pointer to it will be saved in the Button handler
// module.
static app_button_cfg_t buttons[] =
{
{WAKEUP_BUTTON_PIN, APP_BUTTON_ACTIVE_LOW, BUTTON_PULL, NULL},
// YOUR_JOB: Add other buttons to be used:
// {MY_BUTTON_PIN, false, BUTTON_PULL, button_event_handler}
{BUTTON_0, APP_BUTTON_ACTIVE_LOW, BUTTON_PULL, button_event_handler},
{BUTTON_1, APP_BUTTON_ACTIVE_LOW, BUTTON_PULL, button_event_handler},
{BUTTON_2, APP_BUTTON_ACTIVE_LOW, BUTTON_PULL, button_event_handler},
{BUTTON_3, APP_BUTTON_ACTIVE_LOW, BUTTON_PULL, button_event_handler},
};
APP_BUTTON_INIT(buttons, sizeof(buttons) / sizeof(buttons[0]), BUTTON_DETECTION_DELAY, true);
// Note: If the only use of buttons is to wake up, the app_button module can be omitted, and
// the wakeup button can be configured by
// GPIO_WAKEUP_BUTTON_CONFIG(WAKEUP_BUTTON_PIN);
}
这里我们新增了4个按键,这4个按键所对应的GPIO口分别是30、21、22和23,这4个按键的中断处理函数为button_event_handler(),代码如下:
void button_event_handler(uint8_t pin_no, uint8_t button_action)
{
if (button_action == APP_BUTTON_PUSH) {
switch (pin_no) {
case BUTTON_0:
printf("button_0 down\r\n");
break;
case BUTTON_1:
printf("button_1 down\r\n");
break;
case BUTTON_2:
printf("button_2 down\r\n");
break;
case BUTTON_3:
printf("button_3 down\r\n");
break;
default:
break;
}
} else {
switch (pin_no) {
case BUTTON_0:
printf("button_0 up\r\n");
break;
case BUTTON_1:
printf("button_1 up\r\n");
break;
case BUTTON_2:
printf("button_2 up\r\n");
break;
case BUTTON_3:
printf("button_3 up\r\n");
break;
default:
break;
}
}
}
在按键的中断处理函数中,收到按键按下、抬起事件后打印一点消息,方便我们调试。最后,按键初始化好之后,还需要调用app_button_enable()函数,按键才能正常使用。