⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 keycan.c

📁 最经典的键盘扫描程序
💻 C
字号:
	  #include <REG51.h>
#include <stdio.h>	
#include <math.h>

// 键盘行列
sbit P1_0=P1^0;
sbit P1_1=P1^1;
sbit P1_2=P1^2;
sbit P1_3=P1^3;
sbit P1_4=P1^4;
sbit P1_5=P1^5;
sbit P1_6=P1^6;
sbit P1_7=P1^7;
sbit P2_0=P2^0;
sbit P2_1=P2^1;
sbit P2_2=P2^2;
sbit P2_3=P2^3;

#define uchar unsigned char
#define uint unsigned int

uchar digbit;
uchar key;
uchar temp;
uchar keycode81;
unsigned int i; 
unsigned char code tab[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xa7,0xa1,0x86,0x8e};  
  

void Delay(unsigned int i)
{    unsigned int j;
    for(;i>0;i--)
        for(j=0;j<125;j++)
       {;}
}
void Display(unsigned int i)
{   
	P0=tab[i];
	P2_0=1;
	P2_1=1;
	P2_2=1;
	P2_3=1;
	Delay(0.05);
 }

 uchar keyscan(void)
{
	uchar scancode,tmpcode;
	P1 = 0xf0;			 					// 发全0行扫描码
	if ((P1&0xf0)!=0xf0)					// 若有键按下
	{
		Delay(20);							// 延时去抖动
		if ((P1&0xf0)!=0xf0)				// 延时后再判断一次,去除抖动影响
		{
			scancode = 0xfe;				 //第一行变低
			while((scancode&0x10)!=0)		// 逐行扫描
			{
				P1 = scancode;				// 输出行扫描码
				if ((P1&0xf0)!=0xf0)		// 本行有键按下
				{
					tmpcode = (P1&0xf0)|0x0f;

					/* 返回特征字节码,为1的位即对应于行和列 */
					return((~scancode)+(~tmpcode));
				}
				else scancode = (scancode<<1)|0x01;		// 行扫描码左移一位
			}
		}
	}
	return(0);						// 无键按下,返回值为0 	
}
uchar keycode(void)
{
      keycode81= keyscan();
	  switch(keycode81)
        {      		
           case 0x11:key=0;break;						// 1行1列,数字0
		   case 0x21:key=1;break;						// 1行2列,数字1
		   case 0x41:key=2;break;						// 1行3列,数字2
		   case 0x81:key=3;break;						// 1行4列,数字3

		   case 0x12:key=4;break;						// 2行1列,数字4
		   case 0x22:key=5;break;						// 2行2列,数字5
		   case 0x42:key=6;break;						// 2行3列,数字6
		   case 0x82:key=7;break;						// 2行4列,数字7

		   case 0x14:key=8;break;						// 3行1列,数字8
		   case 0x24:key=9;break;						// 3行2列,数字9
		   case 0x44:key=10;break;						// 3行3列,数字a
		   case 0x84:key=11;break;						// 3行4列,数字b

		   case 0x18:key=12;break;						// 4行1列,数字c
		   case 0x28:key=13;break;						// 4行2列,数字d
		   case 0x48:key=14;break;						// 4行3列,数字e
		   case 0x88:key=15;break;						// 4行4列,数字f
		  			
		}
		return(key);
}

/* 主程序 */
void main()
{	
    while(1)
	{
	  	 digbit=keycode();
      	 Display(digbit);
		}
}



⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -