+
+module PS2(
+ input pixclk,
+ input inclk,
+ input indata,
+ output reg wr,
+ output reg [7:0] data
+ );
+
+ reg [3:0] bitcount = 0;
+ reg [7:0] key = 0;
+ reg keyarrow = 0, keyup = 0, parity = 0;
+
+
+ /* Clock debouncing */
+ reg lastinclk = 0;
+ reg [6:0] debounce = 0;
+ reg fixedclk = 0;
+ reg [11:0] resetcountdown = 0;
+
+ reg [6:0] unshiftedrom [127:0]; initial $readmemh("scancodes.unshifted.hex", unshiftedrom);
+ reg [6:0] shiftedrom [127:0]; initial $readmemh("scancodes.shifted.hex", shiftedrom);
+
+ reg mod_lshift = 0;
+ reg mod_rshift = 0;
+ reg mod_capslock = 0;
+ wire mod_shifted = (mod_lshift | mod_rshift) ^ mod_capslock;
+
+ reg nd = 0;
+ reg lastnd = 0;
+
+ always @(posedge pixclk) begin
+ if (inclk != lastinclk) begin
+ lastinclk <= inclk;
+ debounce <= 1;
+ resetcountdown <= 12'b111111111111;
+ end else if (debounce == 0) begin
+ fixedclk <= inclk;
+ resetcountdown <= resetcountdown - 1;
+ end else
+ debounce <= debounce + 1;
+
+ if (nd ^ lastnd) begin
+ lastnd <= nd;
+ wr <= 1;
+ end else
+ wr <= 0;
+ end
+
+ always @(negedge fixedclk) begin
+ if (resetcountdown == 0)
+ bitcount <= 0;
+ else if (bitcount == 10) begin
+ bitcount <= 0;
+ if(parity != (^ key)) begin
+ if(keyarrow) begin
+ casex(key)
+ 8'hF0: keyup <= 1;
+ 8'hxx: keyarrow <= 0;
+ endcase
+ end
+ else begin
+ if(keyup) begin
+ keyup <= 0;
+ keyarrow <= 0;
+ casex (key)
+ 8'h12: mod_lshift <= 0;
+ 8'h59: mod_rshift <= 0;
+ endcase
+ // handle this? I don't fucking know
+ end
+ else begin
+ casex(key)
+ 8'hE0: keyarrow <= 1; // handle these? I don't fucking know
+ 8'hF0: keyup <= 1;
+ 8'h12: mod_lshift <= 1;
+ 8'h59: mod_rshift <= 1;
+ 8'h14: mod_capslock <= ~mod_capslock;
+ 8'b0xxxxxxx: begin nd <= ~nd; data <= mod_shifted ? shiftedrom[key] : unshiftedrom[key]; end
+ 8'b1xxxxxxx: begin /* AAAAAAASSSSSSSS */ end
+ endcase
+ end
+ end
+ end
+ else begin
+ keyarrow <= 0;
+ keyup <= 0;
+ 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