下图是键盘时序图,上面是PS2发送时序,下面是PS2键盘接纳时序.
下面的代码是用PS2键盘操控LED显现按键编码.按住显现的是通码.铺开显现的是断码.但由于断码最终8位是通码相同(不包括多位通码).所以显现一般是相同的.
单片机P3.3接PS2按口的5为时钟CLK,P3.4接PS2接口的1为数据DA
代码如下:
#include
#include
#define ESC_CO
sbit PS2_DA
sbit PS2_CLK = P3^3; //PS2时钟线
sbit BEEP = P3^7; //蜂鸣器驱动线
unsigned char TEMP;
unsigned char KeyCode; //键盘键值
unsigned char co
0x1c,0x32,0x21,0x23,0x24,0x2b,0x34,0x33,0x43,0x3b,0x42,
0x4b,0x3a,0x31,0x44,0x4d,0x15,0x2d,0x1b,0x2c,0x3c,0x2a,0x1d,0x22,0x35,0x1a, //a-z
0x45,0x16,0x1e,0x26,0x25,0x2e,0x36,0x3d,0x3e,0x46, //0-9
0x0e,0x4e,0x55,0x5d,0x29,0x54,0x5b,0x4c,0x52,0x41,0x49,0x4a,0x71, //标点符号
0x70,0x69,0x72,0x7a,0x6b,0x73,0x74,0x6c,0x75,0x7d, //右边数字键0-9
0xff };
void delay(unsigned int x)
{
unsigned char i;
while(x–)
{
for (i=0; i<13; i++) ;
}
}
void beep()
{
unsigned char i;
for (i=0;i<100;i++)
{
delay(5);
BEEP=!BEEP; //BEEP取反
}
BEEP=1; //封闭蜂鸣器
}
unsigned char ReadPS2()
{
unsigned char i; //位数
while(PS2_CLK); //等候键盘把时钟第一次拉低,表明
for(i=8; i!=0; i–) // 把开始位算入
{
while(!PS2_CLK); //等候一个有用的下跳沿,这两条while是半个周期,主设备在下降沿读数据
while( PS2_CLK);
KeyCode >>= 1; //数据低位在前
if(PS2_DA
KeyCode |= 0x80; // 得到有用的数据位
}
for(i=2;i!=0;i–) //等候键盘发送效验位和停止位
{
while(!PS2_CLK);
while( PS2_CLK);
}
while(!PS2_CLK); //等候键盘把时钟线拉高
TEMP = KeyCode;
TEMP = ~TEMP;
P2=TEMP; //显现键码
return(KeyCode); //回来按键值
}
void PS2KEY()
{
unsigned char y;
for(y=0 ;y<60 ;y++) //键值变换为次序码
{
if(KeyCode==TABLE_D[y])
{
delay(1000);
beep() ; //查找有用,蜂鸣器响一声
}
}
}
void main()
{
P2 = 0xff; //封闭一切LED
while(1)
{
ReadPS2();
if(KeyCode==ESC_CO
{
P2 = 0xff; //封闭一切LED
}
PS2KEY();
}
}
/*********************************************************/