單片機和PS2鍵盤通信
下面的代碼是用PS2鍵盤控制LED顯示按鍵編碼.按住顯示的是通碼.放開顯示的是斷碼.但由于斷碼最后8位是通碼一樣(不包括多位通碼).所以顯示一般是一樣的.
單片機P3.3接PS2按口的5為時鐘CLK,P3.4接PS2接口的1為數(shù)據(jù)DA
代碼如下:
#include
#include
#define ESC_CO
sbit PS2_DA
sbit PS2_CLK = P3^3; //PS2時鐘線
sbit BEEP = P3^7; //蜂鳴器驅(qū)動線
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, //右邊數(shù)字鍵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; //關(guān)閉蜂鳴器
}
unsigned char ReadPS2()
{
unsigned char i; //位數(shù)
while(PS2_CLK); //等待鍵盤把時鐘第一次拉低,表示
for(i=8; i!=0; i--) // 把起始位算入
{
while(!PS2_CLK); //等待一個有效的下跳沿,這兩條while是半個周期,主設(shè)備在下降沿讀數(shù)據(jù)
while( PS2_CLK);
KeyCode >>= 1; //數(shù)據(jù)低位在前
if(PS2_DA
KeyCode |= 0x80; // 得到有效的數(shù)據(jù)位
}
for(i=2;i!=0;i--) //等待鍵盤發(fā)送效驗位和終止位
{
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; //關(guān)閉所有LED
while(1)
{
ReadPS2();
if(KeyCode==ESC_CO
{
P2 = 0xff; //關(guān)閉所有LED
}
PS2KEY();
}
}
/*********************************************************/
評論