单片机独立按键扫描程序

为了方便,写一些方便的程序片段以便以后使用

首先是定时器扫描按键给两个例子:

一:

#include 
#include 

typedef unsigned char uchar;
typedef unsigned int uint;


sbit S0=P1^0;
sbit S1=P1^1;
sbit S2=P1^2;


enum{K_GT, K_AS, K_WA}keyState = K_GT;
uchar tmpKey = 0, keyCnt, key = 0;

int GetKey()
{
	if(S0 == 0) return 1;
	if(S1 == 0) return 2;
	if(S2 == 0) return 3;
	return 0;
}


void Timer0Handle() interrupt 1
{
	//重装初值
	TH0 = (65536-1000)/256;		//设置定时初值
	TL0 = (65536-1000)%256;		//设置定时初值
	switch(keyState)
	{
		case K_GT:
				keyCnt = 0;
				tmpKey = GetKey();
				keyState = K_AS;
		break;

		case K_AS:
				if(keyCnt++ < 10);
				else if(tmpKey == GetKey())
				{
					if(tmpKey != key)
					{
						key = tmpKey;
						keyState = K_WA;
					}	
					else
					keyState = K_GT;
				}
				else
				keyState = K_GT;
		break;
	}
}

//定时器0的1ms定时
void Timer0Init(void)		//1毫秒@11.0592MHz
{
	TMOD &= 0xF0;		//设置定时器模式
	TMOD |= 0x01;		//设置定时器模式
	TH0 = (65536-1000)/256;		//设置定时初值
	TL0 = (65536-1000)%256;		//设置定时初值
	TF0 = 0;		//清除TF0标志
	TR0 = 1;		//定时器0开始计
	ET0 = 1;
	EA  = 1;
}

void main()
{
	Timer0Init();
	while(1)
	{
		if(keyState == K_WA)
		{
			switch(key)
			{
				case 1:
					
				break;

				case 2:
					
				break;
				
				case 3:
					
				break;
			}	
			keyState = K_GT;
		}
	}
}


二:

#include 
#include 
#include 
#include 


typedef unsigned char u8;
typedef unsigned int u16;

sbit K0=P1^0;
sbit K1=P1^1;
sbit K2=P1^2;
sbit K3=P1^3;

enum{KEY_PRESS, KEY_UP}keymode = KEY_UP;
int key = 0;

u8 Independentkey()
{
	u8 keynum=0;
	if(K0==0){keynum=1;}
	if(K1==0){keynum=2;}
	if(K2==0){keynum=3;}
	return keynum;
}
void Timer0Handle() interrupt 1
{
	static int tmpKey = 0, keyCnt = 0;
	// 重装初值
	TH0 = (65536 - 1000) / 256;
	TL0 = (65536 - 1000) % 256;
	if(Independentkey() != 0 && keymode == KEY_UP)
	{
		tmpKey = Independentkey();
		keymode = KEY_PRESS;
	}
	else if(keymode == KEY_PRESS && keyCnt < 10)
	{
		keyCnt++;
	}
	else
	{
		keyCnt = 0;
		keymode = KEY_UP;
		if(tmpKey == Independentkey())
		{
			key = tmpKey;
		}
		else
			key = 0;
	}	
}

// 定时器0的1ms定时
void Timer0Init(void) // 1毫秒@11.0592MHz
{
	TMOD &= 0xF0;				// 设置定时器模式
	TMOD |= 0x01;				// 设置定时器模式
	TH0 = (65536 - 1000) / 256; // 设置定时初值
	TL0 = (65536 - 1000) % 256; // 设置定时初值
	TF0 = 0;					// 清除TF0标志
	TR0 = 1;					// 定时器0开始计
	ET0 = 1;
	EA = 1;
}

void main()
{
	Timer0Init();
	while (1)
	{
		if (key != 0 && Independentkey() == 0)
		{
			if (key == 1) 
			{
				
			}
			else if (key == 2)
			{
				
			}
			else if (key == 3)
			{
	
			}
			key = 0;
		}
	}
}

你可能感兴趣的:(单片机,嵌入式硬件)