一、如何分辨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);
// 配置K2
BTN_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;
// 如果当前是按下, 开始等待10ms
MYSTK_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;
}