module key_1(
    input wire sys_clk,  // U18
    input wire sys_rst,  //J15
    //         d20,d19,b19,a20
    output reg c4, c3, c2, c1,
    //         f16,f17,e18,e19
    output reg r4, r3, r2, r1,

    //          f20 f19 b20 c20 j16 k16 m18 m17 l17 l16 l15 l14 m15 m14 n16 n15
    //          x4  x2          x1      x3  x6          x7      x5          x8   
    //                  y2  y3      y5          y8  y7      y1      y6  y4                  
    output wire o1, o2, o3, o4, o5, o6, o7, o8, o16,o15,o14,o13,o12,o11,o10,o9
);
reg [7:0] KEY_CODE;

parameter GET_START = 4'b0001 << 0;
parameter GET_ROW = 4'b0001 << 1;
parameter GET_COL = 4'b0001 << 2;
parameter GET_END = 4'b0001 << 3;
reg STATUS = 4'b0000;


always @(posedge sys_clk or negedge sys_rst) begin
    if (sys_rst == 1'b0) begin
        STATUS <= GET_START;
    end
    else begin
    end
end


// 每个时钟周期�?查行
always @(posedge sys_clk or negedge sys_rst) begin
    // todo �?查锁
    // todo 可能会一次按多个按键, 后面再处理吧
    if (STATUS == GET_START) begin
        STATUS <= GET_ROW;
        {c4, c3, c2, c1} <= 4'b1111;
        {r4, r3, r2, r1} <= 4'b0000;
        KEY_CODE <= 8'b00000000;
    end
    else if (STATUS == GET_ROW && {c4, c3, c2, c1} != 4'b1111) begin
        KEY_CODE[7:4] <= {c4, c3, c2, c1};
        STATUS <= GET_COL;

        {c4, c3, c2, c1} <= 4'b0000;
        {r4, r3, r2, r1} <= 4'b1111;
    end
    else if (STATUS == GET_COL && {r4, r3, r2, r1} != 4'b1111) begin
        KEY_CODE[3:0] <= {r4, r3, r2, r1};
        STATUS <= GET_END;
    end
    else if (STATUS == GET_END) begin
        STATUS <= GET_START;
    end
    else begin
    end
end


reg [7:0] x;
reg [7:0] y;
always @(posedge sys_clk or negedge sys_rst) begin
    if (sys_rst == 1'b0) begin
        x <= 8'b0000_0000;
        y <= 8'b1111_1111;
    end
    else begin
        x <= KEY_CODE;
    end
end

lm u_lm(
    .x (x),
    .y (y),
    .o1 (o1),
    .o2 (o2),
    .o3 (o3),
    .o4 (o4),
    .o5 (o5),
    .o6 (o6),
    .o7 (o7),
    .o8 (o8),
    .o9 (o9),
    .o10 (o10),
    .o11 (o11),
    .o12 (o12),
    .o13 (o13),
    .o14 (o14),
    .o15 (o15),
    .o16 (o16)
);

endmodule