module PS2Button( input clk, input inclk, input indata, output wire [7:0] buttons ); reg [3:0] bitcount = 0; reg [7:0] key = 0; reg keyarrow = 0, keyup = 0, parity = 0; reg key_a = 0,key_b = 0,key_st = 0,key_sel = 0,key_up = 0,key_dn = 0,key_l = 0,key_r = 0; assign buttons = {key_st,key_sel,key_b,key_a,key_dn,key_up,key_l,key_r}; /* Clock debouncing */ reg lastinclk = 0; reg [5:0] debounce = 0; reg fixedclk = 0; reg [9:0] resetcountdown = 0; always @(posedge clk) begin if (inclk != lastinclk) begin lastinclk <= inclk; debounce <= 1; resetcountdown <= 10'b1111111111; end else if (debounce == 0) begin fixedclk <= inclk; resetcountdown <= resetcountdown - 1; end else debounce <= debounce + 1; end always @(negedge fixedclk) begin if (resetcountdown == 0) bitcount <= 0; else if (bitcount == 10) begin bitcount <= 0; if(parity != (^ key)) begin if(keyarrow) begin keyarrow <= 0; case(key) 8'hF0: keyup <= 1; 8'h75: key_up <= 1; 8'h74: key_r <= 1; 8'h72: key_dn <= 1; 8'h6B: key_l <= 1; endcase end else begin if(keyup) begin keyup <= 0; case(key) 8'h75: key_up <= 0; 8'h74: key_r <= 0; 8'h72: key_dn <= 0; 8'h6B: key_l <= 0; 8'h1C: key_a <= 0; 8'h1B: key_b <= 0; 8'h5A: key_st <= 0; 8'h59: key_sel <= 0; endcase end else begin case(key) 8'hE0: keyarrow <= 1; 8'hF0: keyup <= 1; 8'h1C: key_a <= 1; 8'h1B: key_b <= 1; 8'h5A: key_st <= 1; 8'h59: key_sel <= 1; endcase end end end else begin keyarrow <= 0; keyup <= 0; {key_a,key_b,key_st,key_sel,key_up,key_dn,key_l,key_r} <= 8'b0; end end else bitcount <= bitcount + 1; case(bitcount) 1: key[0] <= indata; 2: key[1] <= indata; 3: key[2] <= indata; 4: key[3] <= indata; 5: key[4] <= indata; 6: key[5] <= indata; 7: key[6] <= indata; 8: key[7] <= indata; 9: parity <= indata; endcase end endmodule