栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

(蓝桥杯嵌入式)KEY模块

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

(蓝桥杯嵌入式)KEY模块

目录

1.key.c

2.key.h

3.长短按的实现


1.key.c
#include "key.h"

//按键相关GPIO初始化
void KEY_GPIO_Init(void)
{
	GPIO_InitTypeDef GPIO_InitStructure;
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB, ENABLE);
	
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_8;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
	GPIO_Init(GPIOA, &GPIO_InitStructure);
	
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_2;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
	GPIO_Init(GPIOB, &GPIO_InitStructure);
}

//Trg 用于单次按下响应一次,Cont用于长按。
u16 Trg=0;
u16 Cont=0;
u16 ReadDate=0;
void KEY_Read(void)
{
	ReadDate=KEYPORT^0xff;
	Trg=ReadDate&(ReadDate^Cont);
	Cont=ReadDate;
	
}

2.key.h
#ifndef __KEY_H
#define __KEY_H

#include "stm32f10x.h"

#define  KB1  GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_0)
#define  KB2  GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_8)
#define  KB3  GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_1)
#define  KB4  GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_2)

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

extern u16 Trg;
extern u16 Cont;
extern u16 ReadDate;

void KEY_GPIO_Init(void);
void KEY_Read(void);


#endif 

3.长短按的实现
void ReadKeyFun(void)
{
	if(read_key_count>=10)//10ms读取一次按键状态
	{
		read_key_count=0;
		KEY_Read();
		//KB1长按
		if(Cont==0x01)
		{
			key_time_flag=1;
			if(key_time>=800)
			{
				key_value+=1;
			}
		}
		//KB2长按
		if(Cont==0x02)
		{
			key_time_flag=2;
			if(key_time>=800)
			{
				key_value+=1;
			}			
		}
		//KB3长按
		if(Cont==0x04)
		{
			key_time_flag=3;
			if(key_time>=800)
			{
				key_value+=1;
			}			
		}
		//KB4长按
		if(Cont==0x08)
		{
			key_time_flag=4;
			if(key_time>=800)
			{
				key_value+=1;
			}			
		}
		//松手检测(短按处理)
		if(0==Trg&&0==Cont)
		{
			       //KB1
			if(1==key_time_flag)
			{
				if(key_time<800)
				{
                   key_value+=1;					
				}
			}
						//KB2
			if(2==key_time_flag)
			{
				if(key_time<800)
				{
                   key_value+=1;					
				}
			}
						//KB3
			if(3==key_time_flag)
			{
				if(key_time<800)
				{
                   key_value+=1;					
				}       
			}
						//KB4
			if(4==key_time_flag)
			{
				if(key_time<800)
				{
                   key_value+=1;					
				}
			}
				key_time_flag=0;
				key_time=0;
		}
	}
			    sprintf((char*)DisBuff,"DisBuff:%2d",key_value);
		LCD_DisplayStringLine(Line5,DisBuff);	
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/971240.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号