目錄
- 一、如何分辨GPIO輸入使用什么電頻
- 二、輸入抖動問題如何消抖
- 三、示例代碼
一、如何分辨GPIO輸入使用什么電頻
先看原理圖
即可知道他的初始輸入狀態需要高電平
判斷可知使用上拉輸入
二、輸入抖動問題如何消抖
- 電路圖中, 按鍵輸入有額外的電容電阻, 是為了消抖
-
消抖方案:
-
硬件消抖1,
RC
電路 -
硬件消抖2, 施密特觸發器
-
軟件消抖: 延時法, 狀態法, 統計法
-
一般軟硬件配合
三、示例代碼
.h
#ifndef _DRV_BTN_H_
#define _DRC_BTN_H_#include "stm32f10x.h"
#include "drv_systick.h"#define BTN_K1_Port GPIOA
#define BTN_K2_Port GPIOC
#define BTN_K1_Pin GPIO_Pin_0
#define BTN_K2_Pin GPIO_Pin_13/*** @brief 初始化* */
void BTN_Init(void);/*** @brief 按下后談起* * @param keyport * @param keypin * @return ErrorStatus */
ErrorStatus BTN_IsClicked(GPIO_TypeDef *keyport,uint16_t keypin);/*** @brief 是否按下* * @param keyport * @param keypin * @return ErrorStatus */
ErrorStatus BTN_IsPressed(GPIO_TypeDef *keyport,uint16_t keypin);/*** @brief 是否放開* * @param keyport * @param keypin * @return ErrorStatus */
ErrorStatus BTN_IsReleased(GPIO_TypeDef *keyport,uint16_t keypin);#endif
.c
#include "drv_btn.h"void BTN_Init(void)
{//RCC時鐘配置RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOC,ENABLE);GPIO_InitTypeDef BTN_InitStruct;BTN_InitStruct.GPIO_Mode = GPIO_Mode_IPU;BTN_InitStruct.GPIO_Pin = BTN_K1_Pin;GPIO_Init(BTN_K1_Port, &BTN_InitStruct);// 配置K2BTN_InitStruct.GPIO_Pin = BTN_K2_Pin;GPIO_Init(BTN_K2_Port, &BTN_InitStruct);}ErrorStatus BTN_IsClicked(GPIO_TypeDef *keyport,uint16_t keypin)
{uint8_t ret;// 先判斷是否按下, 注意按下是高電平ret = GPIO_ReadInputDataBit(keyport, keypin);if (!ret)return ERROR;// 如果當前是按下, 開始等待10msMYSTK_DelayMs(10);// 再次判斷ret = GPIO_ReadInputDataBit(keyport, keypin);if (!ret)return ERROR;// 如果仍然是按下, 再等待彈起while (0 != GPIO_ReadInputDataBit(keyport, keypin)){}return SUCCESS;
}ErrorStatus BTN_IsPressed(GPIO_TypeDef *keyport, uint16_t keypin)
{uint8_t ret;ret = GPIO_ReadInputDataBit(keyport, keypin);if (!ret)return ERROR;return SUCCESS;
}ErrorStatus BTN_IsReleased(GPIO_TypeDef *keyport, uint16_t keypin)
{uint8_t ret;ret = GPIO_ReadInputDataBit(keyport, keypin);if (ret)return ERROR;return SUCCESS;
}