【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;
}
相关推荐
电子小白1238 小时前
第13期PCB layout工程师初级培训-1-EDA软件的通用设置
笔记·嵌入式硬件·学习·pcb·layout
清风6666668 小时前
基于单片机的多传感器智能云梯逃生控制器设计
单片机·嵌入式硬件·毕业设计·智能家居·课程设计
小何code8 小时前
STM32入门教程,第10课(上),OLED显示屏
stm32·单片机·嵌入式硬件
来自晴朗的明天8 小时前
高速画板-USB模块的PCB设计5-USB2.0/3.0布局布线要求
单片机·嵌入式硬件·硬件工程
早日退休!!!10 小时前
ARM Cortex-M核 【保存上下文&恢复上下文】
arm开发·单片机·嵌入式硬件
来自晴朗的明天11 小时前
差分控多少Ω阻抗
单片机·嵌入式硬件·硬件工程
SystickInt12 小时前
mosbus复习总结(20260110)
stm32
点灯小铭12 小时前
基于单片机的多功能智能婴儿车设计
单片机·嵌入式硬件·毕业设计·课程设计·期末大作业
π同学13 小时前
基于RT-Thread的STM32开发第十一讲——编码器模式
stm32·rt_thread·双相编码器
码农小韩15 小时前
基于Linux的C++学习——动态数组容器vector
linux·c语言·开发语言·数据结构·c++·单片机·学习