从ps/2接口的键盘输入,然后根据接收到的扫描码将输入的键值显示在oHEX0七段译码管。(只实现了数字键0-9的识别)
View Code
1 module ps2_keyboard(clk,clrn,ps2_clk,ps2_data,oHEX0);
2 input clk,clrn,ps2_clk,ps2_data;
3 output reg [6:0] oHEX0;
4
5 reg [7:0] data;
6 reg ready;
7 reg overflow; // fifo overflow
8 reg [3:0] count; // count ps2_data bits
9
10 // internal signal, for test
11 reg [9:0] buffer; // ps2_data bits
12 reg [7:0] fifo[7:0]; // data fifo
13 reg [2:0] w_ptr,r_ptr; // fifo write and read pointers
14 // detect falling edge of ps2_clk
15 reg [2:0] ps2_clk_sync;
16
17 //show the input to oHEX0
18 function [6:0] ps2_keyboard_show;
19 input [7:0] key_data;
20
21 begin
22 case (key_data)
23 8'b00010110 : ps2_keyboard_show = 7'b1111001;//1
24 8'b00011110 : ps2_keyboard_show = 7'b0100100;//2
25 8'b00100110 : ps2_keyboard_show = 7'b0110000;//3
26 8'b00100101 : ps2_keyboard_show = 7'b0011001;//4
27 8'b00101110 : ps2_keyboard_show = 7'b0010010;//5
28 8'b00110110 : ps2_keyboard_show = 7'b0000010;//6
29 8'b00111101 : ps2_keyboard_show = 7'b1111000;//7
30 8'b00111110 : ps2_keyboard_show = 7'b0000000;//8
31 8'b01000110 : ps2_keyboard_show = 7'b0010000;//9
32 8'b01000101 : ps2_keyboard_show = 7'b1000000;//0
33 default : ps2_keyboard_show = 7'b1111111;//other input
34 endcase
35 end
36 endfunction
37
38 //detect the falling edge of ps2_clk
39 always @ (posedge clk)
40 begin
41 ps2_clk_sync <= {ps2_clk_sync[1:0],ps2_clk};
42 end
43 wire sampling = ps2_clk_sync[2] & ~ps2_clk_sync[1];//falling edge:last time 1 this time 0
44
45 always @ (posedge clk)
46 begin
47 if (clrn == 0) // reset
48 begin
49 count <= 0; w_ptr <= 0; r_ptr <= 0; overflow <= 0;
50 end
51 else if (sampling)
52 begin
53 if (count == 4'd10)//10bits
54 begin
55 if ((buffer[0] == 0) && // start bit
56 (ps2_data) && // stop bit
57 (^buffer[9:1])) // odd parity
58 begin
59 fifo[w_ptr] <= buffer[8:1]; // kbd scan code
60 w_ptr <= w_ptr+3'b1;
61 ready <= 1'b1;
62 overflow <= overflow | (r_ptr == (w_ptr + 3'b1));
63 end
64 count <= 0; // for next
65 end
66 else
67 begin
68 buffer[count] <= ps2_data; // store ps2_data
69 count <= count + 3'b1;
70 end
71 end
72 if ( ready ) // read to output next data
73 begin
74 data = fifo[r_ptr];
75 r_ptr <= r_ptr + 3'd1;
76 ready <= 1'b0;
77 oHEX0 = ps2_keyboard_show(data);
78 end
79 end
80 endmodule