HDLbits: Fsm ps2

本题目理解起来有点难,要观察题目中给的三个时序图,通过时序图可以发现,状态有四个:byte1、byte2、byte3,还有一个“?”状态。其中,byte1的下一个状态一定是byte2,byte2的下一个状态一定是byte3,但是byte3的下一个状态可能是“?”,需要通过in[3]来确定。于是先写出下面的代码(运行错误):

module top_module(
    input clk,
    input [7:0] in,
    input reset,    // Synchronous reset
    output done); //
    
    parameter byte1=4'b0001, byte2=4'b0010, byte3=4'b0100, byte_fault=4'b1000;

    
    reg [3:0] state,next_state;

    // State transition logic (combinational)
    always@(*)begin
        case(state)
            byte1: next_state = byte2;
            byte2: next_state = byte3;
            byte3: next_state = in[3]?byte1:byte_fault;
            byte_fault: next_state = in[3]?byte1:byte_fault; 
            default: next_state = byte1;
        endcase
    end

    // State flip-flops (sequential)
    always@(posedge clk)begin
        if(reset)
            state <= byte1;
        else
            state <= next_state;
    end
    
    always@(posedge clk)begin
        if(state == byte3)
            done <= 1;
        else
            done <= 0;
    end
    // Output logic
    //assign done = (state == byte3);

endmodule

通过对比大神写的代码,发现两个问题:1、reset时,state不是byte1而是byte_fault,这一点题目没说明白。2、done判断条件为什么不能用我写的always块而是assign?

module top_module(
    input clk,
    input [7:0] in,
    input reset,    // Synchronous reset
    output done); //
    
    parameter byte1=4'b0001, byte2=4'b0010, byte3=4'b0100, byte_fault=4'b1000;

    
    reg [3:0] state,next_state;

    // State transition logic (combinational)
    always@(*)begin
        case(state)
            byte1: next_state = byte2;
            byte2: next_state = byte3;
            byte3: next_state = in[3]?byte1:byte_fault;
            byte_fault: next_state = in[3]?byte1:byte_fault; 
            default: next_state = byte1;
        endcase
    end

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

endmodule

你可能感兴趣的:(verilog学习)