Theory
A matrix keypad is a set of buttons arranged in rows and columns (e.g., 4x3 or 4x4). Instead of having a separate wire for each button, the matrix design reduces the number of I/O pins required.
diagram
verilog code
module keypad_scanner (
input clk,
input reset,
input [3:0] col, // Columns from keypad
output reg [3:0] row, // Rows to keypad
output reg [3:0] key, // 4-bit key code
output reg key_valid // High when a key is detected
);
reg [1:0] scan_row;
reg [19:0] debounce;
always @(posedge clk or posedge reset) begin
if (reset) begin
scan_row <= 0;
row <= 4'b1110;
debounce <= 0;
key_valid <= 0;
end else begin
debounce <= debounce + 1;
if (debounce == 0) begin
scan_row <= scan_row + 1;
row <= ~(1 << scan_row); // Activate one row at a time
end
case (row)
4'b1110: if (col != 4'b1111) decode_key(0, col);
4'b1101: if (col != 4'b1111) decode_key(1, col);
4'b1011: if (col != 4'b1111) decode_key(2, col);
4'b0111: if (col != 4'b1111) decode_key(3, col);
endcase
end
end
task decode_key;
input [1:0] row_num;
input [3:0] col_val;
begin
key_valid = 1;
case (col_val)
4'b1110: key = row_num * 4 + 0;
4'b1101: key = row_num * 4 + 1;
4'b1011: key = row_num * 4 + 2;
4'b0111: key = row_num * 4 + 3;
default: begin key = 4'b0000; key_valid = 0; end
endcase
end
endtask
endmodule
pin assignment:
Pin clock--P56
Pin reset--P57
Key 0--P58
Key 1--P59
Key 2--P60
Key 3--P61
row<0>-P62
row<1>-P63
row<2>-P64
row<3>-P65
Device utilization:
RTL schematic view:
Time analysis: