// 全局信号量,记录按键事件
osSemaphoreId_t g_keySem;
void KeyPressed(char *arg) {
(void)arg;
//释放一个信号量,注意这里是中断上下文,最好别调用太多东西
osSemaphoreRelease(g_keySem);
}
void handlePressKeyTask(void* arg) {
(void)arg;
while(true) {
// 这里去消费按键事件
osStatus_t status = osSemaphoreAcquire(g_keySem,65535);
if(status != 0) {
}
while(true) {
unsigned short data = 0;
AdcRead(ANALOG_KEY_CHAN_NAME, &data, WIFI_IOT_ADC_EQU_MODEL_4, WIFI_IOT_ADC_CUR_BAIS_DEFAULT, 0);
float voltage = (float)data * 1.8 * 4 / 4096;
if(voltage < 0.8f) {
ssd1306_Fill(Black);
ssd1306_SetCursor(0, 0);
ssd1306_DrawString("Key1 Pressed!", Font_7x10, White);
ssd1306_UpdateScreen();
} else if(voltage < 2.0f) {
ssd1306_Fill(Black);
ssd1306_SetCursor(0, 0);
ssd1306_DrawString("Key2 Pressed!", Font_7x10, White);
ssd1306_UpdateScreen();
} else {
ssd1306_Fill(Black);
ssd1306_SetCursor(0, 0);
ssd1306_DrawString("Released!", Font_7x10, White);
ssd1306_UpdateScreen();
break;
}
}
}
}
void initKey() {
// 端口设置为GPIO
IoSetFunc(WIFI_IOT_IO_NAME_GPIO_5, WIFI_IOT_IO_FUNC_GPIO_5_GPIO);
// 设置为输入
GpioSetDir(WIFI_IOT_IO_NAME_GPIO_5, WIFI_IOT_GPIO_DIR_IN);
// 设置在下降沿中断。(其实我想设置下降沿和上升沿中断的,然而接口居然不允许)
osSemaphoreAttr_t semAttr = {
.name = "KeyPressSemi",
.attr_bits = 0,
.cb_mem = NULL,
.cb_size = 0
};
g_keySem = osSemaphoreNew(8, 0, &semAttr);
GpioRegisterIsrFunc(WIFI_IOT_IO_NAME_GPIO_5, WIFI_IOT_INT_TYPE_EDGE, WIFI_IOT_GPIO_EDGE_FALL_LEVEL_LOW, KeyPressed, NULL);
// 这里启动一个task处理按键事件
osThreadAttr_t attr;
attr.name = "KeyHandleTask";
attr.attr_bits = 0U;
attr.cb_mem = NULL;
attr.cb_size = 0U;
attr.stack_mem = NULL;
attr.stack_size = 2048;
attr.priority = osPriorityNormal;
if (osThreadNew(handlePressKeyTask, NULL, &attr) == NULL) {
printf("[%s]Falied to create KeyHandleTask!n", __func__);
}
}