Verilog模擬PS2協(xié)議的方法
PS2協(xié)議讀鍵盤值相當(dāng)簡單嘛,比模擬SPI、I2C簡單多了...下面介紹一下具體過程.
1.明確接線關(guān)系,只需接4根線,VCC要+5V,3.3我測試過不能用,時鐘和數(shù)據(jù)線要用bidir雙向口線,F(xiàn)PGA可以不用外接上拉電阻。另外,USB鍵盤也可以用,只要用一個轉(zhuǎn)接頭轉(zhuǎn)成PS2即可。
2.讀取基本的鍵盤數(shù)據(jù),不需要FPGA發(fā)送任何數(shù)據(jù),只需讀取鍵盤發(fā)回來的數(shù)據(jù)即可
如下面的時序圖,每次鍵盤發(fā)送11個clock信號,我們需要做的事情就是在時鐘的下降沿讀取數(shù)據(jù)
3.如何來采樣CLK低電平?
這里可以用一個FIFO來儲存數(shù)據(jù),如下面的程序,當(dāng)ps2_clk信號處于下降沿時,ps2_clk_fallingedge值將被置高
reg [2:0] ps2_clkr;//用一個fifo來采樣ps2_clk信號;
always @(posedge clk)
ps2_clkr <= {ps2_clkr[1:0], ps2_clk};
wire ps2_clk_risingedge = (ps2_clkr[2:1]==2‘b01); // now we can detect ps2_clk rising edges
wire ps2_clk_fallingedge = (ps2_clkr[2:1]==2‘b10); // and falling edges
4.當(dāng)檢測到第一個低電平時,我們只需要連續(xù)讀取11個周期值就可以了,這里用一個變量i來控制
always @(posedge clk)
if(rst)
i <= 0;
else
begin
if(ps2_clk_fallingedge)
begin
data2[i] <= data[i];
data[i] <= ps2_data;
if(i<10) i <= i+1;
else i <= 0;
end
end
最后來解釋下這11個數(shù)據(jù)的功能,如下表
5.如果想進一步區(qū)分鍵值,就需要查表了,如下表[!--empirenews.page--]
基本按鍵,鍵盤會發(fā)送“F0”+“鍵碼”
擴展按鍵,則發(fā)送“E0”+“F0”+“鍵碼”
大家都來試一下吧,一個下午就能搞定!
附程序,晶振頻率降至1MHz,用LED輸出鍵值
//==============================================================
module ps2(clk, rst, ps2_clk, ps2_data, data ,data2);
input clk, rst, ps2_clk , ps2_data;
output [10:0] data;
output [10:0] data2;
reg [3:0] i;
reg [10:0] data;//another fifo
reg [10:0] data2;
reg [2:0] ps2_clkr;//用一個fifo來采樣ps2_clk信號;
always @(posedge clk)
ps2_clkr <= {ps2_clkr[1:0], ps2_clk};
wire ps2_clk_risingedge = (ps2_clkr[2:1]==2‘b01); // now we can detect ps2_clk rising edges
wire ps2_clk_fallingedge = (ps2_clkr[2:1]==2‘b10); // and falling edges
always @(posedge clk)
if(rst)
i <= 0;
else
begin
if(ps2_clk_fallingedge)
begin
data2[i] <= data[i];
data[i] <= ps2_data;
if(i<10) i <= i+1;
else i <= 0;
end
end
endmodule