STM32之三行独立按键

三行代码

#define KEYPORT  KB1 | (KB2<<1) | (KB3<<2) | (KB4<<3) | 0xf0

void Key_Read( void )
{
    unsigned char ReadData = (KEYPORT)^0xff;  		    //  1
    Trg = ReadData & (ReadData ^ Cont);      			//  2 
    Cont = ReadData;                         			//  3
}

Name : Key_Read
Function:
(1) No key : ReadData=0;Trg=0;Cont=0;
(2) D0 is 0 : KEYPORT=0xfe; ReadDate=0x01; Trg=0x01&(0x01^0x00) = 0x01; Cont=0x01;
(3) when D0 is always 0 : Trg=0x01&(0x01^0x01)=0 ; Cont=0x01;
(4) when D0 is 1: Trg=0x00&(0x00^0x01)=0 Cont=0;

运用

		u16 key_time=0;     //来统计B1按键长按的时间
		if(key_flag)		//10ms调用一次  key_time 
		{
			key_flag=0;
			Key_Read();
			if(Trg==0x01)						//B1按键
			{
				
			}
			if(Trg==0x02)						//B2按键
			{
				
			}
			if(Trg==0x04)						//B3按键
			{
				
			}
			if(Trg==0x08)						//B4按键
			{
				
			}
			
			if(Cont==0x01)						//B1的长按检测
			{
				key_time++;						//小细节 每次key_flag10ms检测按键所以在这里key_time++相当于10ms加一次
				if(key_time>=50)				//超过500ms
				{
					key_time=0;
					
				}
			}
			
			if(Trg==0x00 && Cont==0x00)			//松手检测
			{
				key_time=0;
			}
		}

长按单次触发

_Bool key1_release=1;
			if(Cont==0x01)						
			{
				key_time++;
				if(key_time>=50 && key_release==1)			
				{
					key_time = 0;
					key_release = 0;							
					lcd_number+=10;
				}
			}
			
			if(Trg==0x00 && Cont==0x00)			
			{
				key_time=0;
				key_release = 1;
			}

区别长按与短按(长按单次)

			if(Cont==0x01)						
			{
				key_time++;
				if(key_time>=50 && key_release==1 )		
				{
					key1_release = 0;							
					lcd_number+=10;
				}
			}
						
			if(Trg==0x00 && Cont==0x00)			
			{
				if(key_time>0 && key_time<50 && key_release==1)	
				{
					lcd_number++;
				}
				key_time=0;
				key_release=1;
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值