【STM32】GPIO输入(按键)

目录

一、如何分辨GPIO输入使用什么电频

先看原理图

即可知道他的初始输入状态需要高电平

判断可知使用上拉输入

二、输入抖动问题如何消抖

  • 电路图中, 按键输入有额外的电容电阻, 是为了消抖
  • 消抖方案:

    • 硬件消抖1, RC电路

    • 硬件消抖2, 施密特触发器

    • 软件消抖: 延时法, 状态法, 统计法

一般软硬件配合

三、示例代码

.h

c 复制代码
#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

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;
}
相关推荐
沐欣工作室_lvyiyi16 小时前
基于物联网的智能衣柜系统的设计(论文+源码)
stm32·单片机·嵌入式硬件·物联网·毕业设计·智能衣柜
sheepwjl17 小时前
《嵌入式驱动(二):驱动开发基本概念》
arm开发·驱动开发·单片机·嵌入式硬件·imx6ull·驱动·裸机
来自嵌入式的zyz18 小时前
STM32学习-UART串口通信:物理层/协议层/UART基本架构/代码实战
stm32·嵌入式硬件·学习
La Pulga18 小时前
【STM32】USART串口(上)
c语言·stm32·单片机·嵌入式硬件·mcu
茯苓gao18 小时前
STM32G4 电流环闭环(二) 霍尔有感运行
笔记·stm32·单片机·嵌入式硬件·学习
涂山苏苏⁠19 小时前
STM32软件I2C读写AT24C64
stm32·单片机·at24c64
京雨19 小时前
关于RISC-V 中断处理的分析
单片机·嵌入式硬件·risc-v
cellurw19 小时前
Day51 时钟系统与定时器(EPIT/GPT)
单片机·嵌入式硬件·gpt
lingzhilab19 小时前
零知IDE——基于STM32F407VET6和MCP2515实现CAN通信与数据采集
stm32·单片机·嵌入式硬件
big\hero20 小时前
基于STM32设计的智能手环(ESP8266+华为云IOT)
stm32·物联网·华为云