首页 > 代码库 > 利用中断实现的4*4矩阵键盘扫描

利用中断实现的4*4矩阵键盘扫描

#include <reg51.h>
#include <intrins.h>
typedef unsigned char UINT8;
typedef unsigned int UINT16;

UINT8 num = 0, temp = 0, key = 16, t0 = 0, t1 = 0, shu = 0;

/* 数码管编码 */

UINT8 code table[]=
{
	0x3f,0x06,0x5b,0x4f,
	0x66,0x6d,0x7d,0x07,
	0x7f,0x6f,0x77,0x7c,
	0x39,0x5e,0x79,0x71,0x00
};

/* 初始化函数 */
void init()
{			
	P1 = 0xf0;
	/* 初始化定时器 */
	TMOD = 0x01;					/* 定时器0和定时器1同时设置为16位定时方式 */
	TH0 = (65536 - 50000) / 256; 	  // 放在高八位当中 
	TL0 = (65536 - 50000) % 256;
	EA = 1;						//开总中断
	ET0 = 1;					//开定时器0中断
	TR0 =1;						//启动定时器0
}

/* 显示函数 */
/* 按键扫描函数 */
UINT8 scan_key()
{
		P1 = 0xef;
		temp = P1;
		temp = temp&0xf0;
		if (temp != 0xf0)
		{
			temp = P1;
			switch(temp)
			{
				  case 0xee:
					   key=0;
					   break;
				  case 0xed:
					   key=1;
					   break;
				  case 0xeb:
					   key=2;
					   break;
				  case 0xe7:
					   key=3;
					   break;
				  default:					  
					  break;
			}
			P1=0xfe;
		}
		P1 = 0xdf;
		temp = P1;
		temp = temp&0x0f;
		if(temp != 0x0f)
		{
			temp = P1;
			switch(temp)
			{
				  case 0xde:
					   key = 4;
					   break;
				  case 0xdd:
					   key = 5;
					   break;
				  case 0xdb:
					   key = 6;
					   break;
				  case 0xd7:
					   key = 7;
					   break;
				  default:
					  break;
			 }
		}
		P1 = 0xbf;
		temp = P1;
		temp = temp&0x0f;
		if(temp != 0x0f)
		{
			temp = P1;
			switch(temp)
			{
				  case 0xbe:
					   key = 8;
					   break;

				  case 0xbd:
					   key = 9;
					   break;

				  case 0xbb:
					   key = 10;
					   break;

				  case 0xb7:
					   key = 11;
					   break;
				  default:
					   break;
			}
		}
		P1 = 0x7f;
		temp = P1;
		temp = temp&0x0f;
		if(temp != 0x0f)
		{		  
			temp = P1;
			switch(temp)
			{
				  case 0x7e:
					   key = 12;
					   break;

				  case 0x7d:
					   key = 13;
					   break;

				  case 0x7b:
					   key = 14;
					   break;

				  case 0x77:
					   key = 15;
					   break;
				  
				  default:
					  break;
			}
		}
		return key;
}

/* 显示函数 */
void display(unsigned char num)
{
     P0 = table[num];
}

/* 定时器0的中断 */
void timer0() interrupt 1
{
	/* 装初值 */
	TH0 = (65536 - 50000) / 256;
	TL0 = (65536 - 50000) % 256;
	t0++;
	display(key);
	if ( t0 == 1)
	{
		t0 = 0;
		key = scan_key();
		P1 = 0x00;										
	}
}

void main()
{
	init();
	
	while(1)
	{
		;
	}
}

利用中断实现的4*4矩阵键盘扫描