Verilog刷题HDLBits——Fsm ps2data

Verilog刷题HDLBits——Fsm ps2data

  • 题目描述
  • 代码
  • 结果

题目描述

See also: PS/2 packet parser.

Now that you have a state machine that will identify three-byte messages in a PS/2 byte stream, add a datapath that will also output the 24-bit (3 byte) message whenever a packet is received (out_bytes[23:16] is the first byte, out_bytes[15:8] is the second byte, etc.).

out_bytes needs to be valid whenever the done signal is asserted. You may output anything at other times (i.e., don’t-care).

For example:
Verilog刷题HDLBits——Fsm ps2data_第1张图片

代码

// 解法一
module top_module(
    input clk,
    input [7:0] in,
    input reset,    // Synchronous reset
    output [23:0] out_bytes,
    output done); //

    // FSM from fsm_ps2
    parameter b1=0,b2=1,b3=2,bd=3;
    reg[1:0] state,next_state;
    // State transition logic (combinational)
    always@(*)
        case(state)
            b1:next_state=(in[3]==1)?b2:b1;
            b2:next_state=b3;
            b3:next_state=bd;
            bd:next_state=(in[3]==1)?b2:b1;
        endcase

    // State flip-flops (sequential)
    always@(posedge clk)
        if(reset)
            state<=b1;
    	else
            state<=next_state;
 
    // Output logic
    assign done = (state==bd);

    // New: Datapath to store incoming bytes.
    always@(posedge clk)
        if(reset)
            out_bytes<=24'b0;
    	else
            out_bytes<={out_bytes[15:0],in};

endmodule

// 解法二
module top_module(
    input clk,
    input [7:0] in,
    input reset,    // Synchronous reset
    output [23:0] out_bytes,
    output done); //

    // FSM from fsm_ps2
    parameter b1=0,b2=1,b3=2,bd=3;
    reg[1:0] state,next_state;
    // State transition logic (combinational)
    always@(*)
        case(state)
            b1:next_state=(in[3]==1)?b2:b1;
            b2:next_state=b3;
            b3:next_state=bd;
            bd:next_state=(in[3]==1)?b2:b1;
        endcase

    // State flip-flops (sequential)
    always@(posedge clk)
        if(reset)
            state<=b1;
    	else
            state<=next_state;
 
    // Output logic
    assign done = (state==bd);

    // New: Datapath to store incoming bytes.
    always@(posedge clk)
        if(reset)
            out_bytes<=24'b0;
    	else
            case(state)
                b1:out_bytes[23:16]<=in;
                b2:out_bytes[15:8]<=in;
                b3:out_bytes[7:0]<=in;
                bd:out_bytes[23:16]<=in;
            endcase

endmodule

结果

Verilog刷题HDLBits——Fsm ps2data_第2张图片

你可能感兴趣的:(fpga开发)