按键长按,短按处理(最简单代码)

/*****************key1.c*****************/

#include "key1.h"
#include "main.h"

unsigned char Key_Scan(void)
{
    static int count1=0;
    static int count2=0;
    static int count3=0;
    static int count4=0;
   
    char key_value = 0;
   
    /* key1 */
    if(B1 == 0)
    { 
        HAL_Delay(10);//去抖
        if(B1 == 0)
        {
            count1++;     
            }
    }
    else
    {

if(count1 > 40)//长按
            {
               key_value = 11;
               
            }
        if(count1 >=1 && count1<=30)//短按
        {   
           key_value = 1;
            
        }
        count1 = 0;//恢复置零
    }

  /* key2 */
    if(B2 == 0)
    { 
        HAL_Delay(10);//去抖
        if(B2 == 0)
        {
            count2++;
        }
    }
    else
    {

if(count2> 40)//长按
            {
               key_value = 22;
               
            }
        if(count2 >=1 && count2<=30)//短按
        {   
           key_value = 2;
            
        }
        count2 = 0;//恢复置零
    }

    return key_value;
}

/****************key1.h**************/

#ifndef __KEY1_H_
#define __KEY1_H_
#include "main.h"

unsigned char Key_Scan(void);
//uint8_t KEY_Scan(void);
#define KEY1_PRES     1        //KEY0按下
#define KEY1_LONG_PRES     2    //KEY0长按,长按时间大于1s
#define KEY2_PRES     3        //KEY0按下
#define KEY2_LONG_PRES     4    //KEY0长按,长按时间大于1s
#define KEY3_PRES     5        //KEY0按下
#define KEY3_LONG_PRES     6    //KEY0长按,长按时间大于1s
#define KEY4_PRES     7        //KEY0按下
#define KEY4_LONG_PRES     8    //KEY0长按,长按时间大于1s

#define  B1    HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_0)
#define  B2    HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_1)
#define  B3    HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_2)
#define  B4    HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0)

#endif

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值