verilog PS2鍵盤解碼源程序
之前探討過PS/2鍵盤編解碼以及數(shù)據(jù)傳輸協(xié)議,這次自己動(dòng)手實(shí)現(xiàn)了利用FPGA接收鍵盤編碼,然后通過串口傳輸?shù)絇C。做的比較簡(jiǎn)單,只是通過FPGA把大寫字母A-Z轉(zhuǎn)換成相應(yīng)的ASCII碼,只要字母按鍵被按下,就能在串口調(diào)試助手里顯示相應(yīng)大寫字母。下面就共享代碼吧!
除了頂層模塊,三個(gè)底層模塊分別為PS/2傳輸處理模塊、串口傳輸模塊以及串口波特率選擇模塊(下面只給出頂層模塊和PS/2傳輸處理模塊的verilog代碼)。
module ps2_key(clk,rst_n,ps2k_clk,ps2k_data,rs232_tx);
input clk; //50M時(shí)鐘信號(hào)
input rst_n; //復(fù)位信號(hào)
input ps2k_clk; //PS2接口時(shí)鐘信號(hào)
input ps2k_data; //PS2接口數(shù)據(jù)信號(hào)
output rs232_tx; // RS232發(fā)送數(shù)據(jù)信號(hào)
wire[7:0] ps2_byte; // 1byte鍵值
wire ps2_state; //按鍵狀態(tài)標(biāo)志位
wire bps_start; //接收到數(shù)據(jù)后,波特率時(shí)鐘啟動(dòng)信號(hào)置位
wire clk_bps; // clk_bps的高電平為接收或者發(fā)送數(shù)據(jù)位的中間采樣點(diǎn)
ps2scan ps2scan( .clk(clk), //按鍵掃描模塊
.rst_n(rst_n),
.ps2k_clk(ps2k_clk),
.ps2k_data(ps2k_data),
.ps2_byte(ps2_byte),
.ps2_state(ps2_state)
);
speed_select speed_select( .clk(clk),
.rst_n(rst_n),
.bps_start(bps_start),
.clk_bps(clk_bps)
);
my_uart_tx my_uart_tx( .clk(clk),
.rst_n(rst_n),
.clk_bps(clk_bps),
.rx_data(ps2_byte),
.rx_int(ps2_state),
.rs232_tx(rs232_tx),
.bps_start(bps_start)
);
Endmodule
module ps2scan(clk,rst_n,ps2k_clk,ps2k_data,ps2_byte,ps2_state);
input clk; //50M時(shí)鐘信號(hào)
input rst_n; //復(fù)位信號(hào)
input ps2k_clk; //PS2接口時(shí)鐘信號(hào)
input ps2k_data; //PS2接口數(shù)據(jù)信號(hào)
output[7:0] ps2_byte; // 1byte鍵值,只做簡(jiǎn)單的按鍵掃描
output ps2_state; //鍵盤當(dāng)前狀態(tài),ps2_state=1表示有鍵被按下
//------------------------------------------
reg ps2k_clk_r0,ps2k_clk_r1,ps2k_clk_r2; //ps2k_clk狀態(tài)寄存器
//wire pos_ps2k_clk; // ps2k_clk上升沿標(biāo)志位
wire neg_ps2k_clk; // ps2k_clk下降沿標(biāo)志位
always @ (posedge clk or negedge rst_n) begin
if(!rst_n) begin
ps2k_clk_r0 = 1'b0;
ps2k_clk_r1 = 1'b0;
ps2k_clk_r2 = 1'b0;
end
else begin //鎖存狀態(tài),進(jìn)行濾波
ps2k_clk_r0 = ps2k_clk;
ps2k_clk_r1 = ps2k_clk_r0;
ps2k_clk_r2 = ps2k_clk_r1;
end
end
assign neg_ps2k_clk = ~ps2k_clk_r1 ps2k_clk_r2; //下降沿
//------------------------------------------
reg[7:0] ps2_byte_r; //PC接收來自PS2的一個(gè)字節(jié)數(shù)據(jù)存儲(chǔ)器
reg[7:0] temp_data; //當(dāng)前接收數(shù)據(jù)寄存器
reg[3:0] num; //計(jì)數(shù)寄存器
always @ (posedge clk or negedge rst_n) begin
if(!rst_n) begin
num = 4'd0;
temp_data = 8'd0;
end
else if(neg_ps2k_clk) begin //檢測(cè)到ps2k_clk的下降沿
case (num)
4'd0: num = num+1'b1;
4'd1: begin
num = num+1'b1;
temp_data[0] = ps2k_data; //bit0
end
4'd2: begin
num = num+1'b1;
temp_data[1] = ps2k_data; //bit1
end
4'd3: begin
num = num+1'b1;
temp_data[2] = ps2k_data; //bit2
end
4'd4: begin
num = num+1'b1;
temp_data[3] = ps2k_data; //bit3
end
4'd5: begin
num = num+1'b1;
temp_data[4] = ps2k_data; //bit4
end
4'd6: begin
num = num+1'b1;
temp_data[5] = ps2k_data; //bit5
end
4'd7: begin
num = num+1'b1;
temp_data[6] = ps2k_data; //bit6
end
DIY機(jī)械鍵盤相關(guān)社區(qū):機(jī)械鍵盤DIY
評(píng)論