4.按键模块

文章介绍了使用STM32开发板中的GPIO引脚实现的按键扫描功能,区分短按键和长按键,并利用TIM3定时器的周期性回调进行状态更新。
摘要由CSDN通过智能技术生成

1.短按键

定时器调为定时10ms

#include "fun.h"
struct keys key[4]={0,0,0};
void key_scan()
{
  key[0].key_sta=HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_0);
  key[1].key_sta=HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_1);
  key[2].key_sta=HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_2);
  key[3].key_sta=HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_0);
  for(int i=0;i<4;i++)
	{
	  switch(key[i].judge_sta)
	  {
		  case 0:
		  {
		  if(key[i].key_sta==0)key[i].judge_sta=1; 
		  }
		  break;
	      case 1:
		  {
		  if(key[i].key_sta==0)
		  {
		  key[i].judge_sta=2;
	      key[i].single_sta=1;
		  } 
		  else{
		  key[i].judge_sta=0;
		  }
		  }
		  break;
		  case 2:
		  {
		  if(key[i].key_sta==1)key[i].judge_sta=0; 
		  }
		  break;
        }
     }

}
#include "fun.h"//该段代码在定义fun.h的头文件中
struct keys{
uchar judge_sta;
bool key_sta;
bool single_sta;
};
#include "inter.h"
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
	if(htim->Instance==TIM3)
	{
	key_scan();
	}
}

2.长按键

struct keys{
uchar judge_sta;
bool key_sta;
bool single_sta;
bool long_sta;
uint16_t key_time;
};

struct keys key[4]={0,0,0,0,0};

void key_scan()
{
  key[0].key_sta=HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_0);
  key[1].key_sta=HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_1);
  key[2].key_sta=HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_2);
  key[3].key_sta=HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_0);
  for(int i=0;i<4;i++)
	{
	  switch(key[i].judge_sta)
	  {
		  case 0:
		  {
		  if(key[i].key_sta==0)
		  {
		  key[i].judge_sta=1; 
		  key[i].key_time=0;
		  }
		  }
		  break;
	      case 1:
		  {
		  if(key[i].key_sta==0)
		  {
		  key[i].judge_sta=2;
		  } 
		  else{
		  key[i].judge_sta=0;
		  }
		  }
		  break;
		  case 2:
		  {
		  if(key[i].key_sta==1)
		  {
		    key[i].judge_sta=0; //很关键,必须放在if的外面
		   if(key[i].key_time<70)
		   {
		   key[i].single_sta=1;
		   }
	       }
		   else{
		   key[i].key_time++;
		   if(key[i].key_time>70)
		   {
		   key[i].long_sta=1;
		   }
		   }
		 }
		  break;
        }
     }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值