工控機通常要接標(biāo)準(zhǔn)鍵盤,但是為了方便操作,常常需要外接一個專用鍵盤。此實例介紹了在工控PC機到PS/2總線上再接入一個自制專用鍵盤的應(yīng)用方法。
用于工控機的PS/2鍵盤接口電路
該設(shè)計應(yīng)能保證兩個鍵盤單獨工作,而且相互不能影響。因此,不能直接把專用鍵盤和標(biāo)準(zhǔn)鍵盤一起接到工控PC的PS/2口。鑒于這種情況,本設(shè)計使用模擬開關(guān)CD4052并通過時分復(fù)用工控PC的PS/2口,來使在同一個時刻只有一個鍵盤有效,從而解決上述問題。其硬件原理圖如圖所示。其中P2口和P1口用于鍵盤掃描電路(圖中未畫出),P0.0為數(shù)據(jù)端,P0.1為時鐘端,P0.2為模擬開關(guān)選通端。由于專用鍵盤不需要接收工控PC機的命令,所以軟件中并不需要寫這部分相應(yīng)的代碼。
通過軟件可在專用鍵盤復(fù)位后把P0.2清0,以使模擬開關(guān)CD4052打開相應(yīng)的通道。這時工控PC的標(biāo)準(zhǔn)鍵盤將開始工作。標(biāo)準(zhǔn)鍵盤可以完成工控PC剛啟動時對外設(shè)檢測的應(yīng)答。復(fù)位后的專用鍵盤不停地掃描有沒有按鍵,如果有鍵按下則識別按鍵,并且按照預(yù)先的設(shè)計進行編碼,同時調(diào)用發(fā)送程序并通過PS/2口發(fā)送到工控PC。此時模擬開關(guān)關(guān)閉相應(yīng)通道(將P0.2置1),專用鍵盤接入工控PC PS/2口的時鐘線和數(shù)據(jù)線而工作,但標(biāo)準(zhǔn)鍵盤被模擬開關(guān)從PS/2的時鐘線和數(shù)據(jù)線中斷而不工作,這樣,雙鍵盤便可時分復(fù)用同一個工控PC機的PS/2口.相應(yīng)的發(fā)送子程序如下:
1 #define DATA P00 用P0.0做數(shù)據(jù)線
2 #define CLK P01 用P0.1做時鐘線
3 #define INHIBIT P02 用P0.2做CD4052的INH端
4 #define PORTR P1 用P1口做讀入口
5 #define PORTW P2 用P2口做寫出口 可以實現(xiàn)64個自定義鍵
6 void send(uchar x)/***function for send a char da-ta***/
7 {
8 uchar i,temp,char_temp;
9 bit flag_check=1;
10 INHIBIT=1;//disable standard keyboard
11 delay_ ms(3);
12 temp=x;
13 for(i=0;i<8;i++)//find the number of 1 in this uchar x is odd or not
14 {
15 char_temp=temp&0x01;
16 if(char_temp==0x01)
17 {
18 flag_check=!flag_check;
19 }
20 temp=temp>>1;
21 }
22 CLK=1;//send 1 to P1 then read P1
23 while (!CLK) //if CLK is low wait
24 {
25 ;
26 }
27 CLK=1;DATA=1;//send 1 to P1 then read P1
28 if(CLK==1)
29 {
30 delay_us(30);//
31 }
32 if(CLK==1&&DATA==1)//send data
33 {
34 DATA=0;//start bit 0
35 delay_us(10);
36 CLK=0;
37 delay_us(5);//
38 temp=x;
39 for(i=0;i<8;i++)//send 8 bits LSBfirst
40 {
41 CLK=1;
42 delay_us(5);
43 char_temp=temp&0x01;
44 if(char_temp==0x01)
45 {
46 DATA=1;
47 }
48 else
49 {
50 DATA=0;
51 }
52 //DATA=(bit)(temp&0x01);
53 //LSB
54 delay_us(10);
55 CLK=0;
56 delay_us(5);
57 temp=temp>>1;
58 }
59 CLK=1;//send check bit
60 delay_us(5);?
61 DATA=flag_check;
62 delay_us(10);?
63 CLK=0;
64 delay_us(5)
65 CLK=1;//send stop bit
66 delay_us(5);?
67 DATA=1;
68 delay us?10 ?
69 CLK=0?
70 delay_us(5);?
71 CLK=1;
72 delay_us(30);? ?
73 CLK=1;DATA=1;//send 1 to P1 then read P1
74 if(CLK==1&&DATA==0)
75 {
76 return; //pc is sending data to mcu, go to
77 receiving function
78 }
79 INHIBIT=0; //enable standard keyboard
80 }