Exams/2014 q3fsm_HDLbits详解(merely状态机典型例题)

merely状态机例题

1、Consider a finite state machine with inputs s and w. Assume that the FSM begins in a reset state called A, as depicted below. The FSM remains in state A as long as s = 0, and it moves to state B when s = 1. Once in state B the FSM examines the value of the input w in the next three clock cycles. If w = 1 in exactly two of these clock cycles, then the FSM has to set an output z to 1 in the following clock cycle. Otherwise z has to be 0. The FSM continues checking w for the next three clock cycles, and so on. The timing diagram below illustrates the required values of z for different values of w.

Use as few states as possible. Note that the s input is used only in state A, so you need to consider just the w input.

考虑具有输入S和W的有限状态机,假设FSM从复位状态开始,称为A,如下所示。只要s=0,FSM将保持状态A,当s=1时,FSM将移动到状态B。一旦进入状态B,FSM将在接下来的三个时钟周期中检查输入w的值。如果在两个时钟周期内w=1,则FSM必须在下一个时钟周期内将输出z设置为1。否则z必须为0。FSM继续在接下来的三个时钟周期中检查w,以此类推。下面的时序图显示了不同w值所需的z值。

使用尽可能少的状态。请注意,S输入仅在状态A中使用,因此需要考虑W输入。

Exams/2014 q3fsm_HDLbits详解(merely状态机典型例题)_第1张图片

需要添加一个求和和周期计数的reg

详解解析如下

module top_module (
    input clk,
    input reset,   // Synchronous reset
    input s,
    input w,
    output z
);
    parameter A=0,B=1;
    reg state,next_state;
    reg [1:0] cout,cle;
//三段式
//状态逻辑变化
    always @(*)
        begin
            case(state)
                	A:next_state <=(s)? B:A; 
                    B:next_state <=B;  
            endcase
        end

//触发信号到来时状态变化
    always @(posedge clk)
        begin
            if(reset) state <=A;
            else state <=next_state;
        end
//关键:需要对周期计数,也需要对3bit的数据进行求和,每接受3个触发信号需要对和清零。
    always @(posedge clk)
        begin
            if(reset|state==A) begin cout<=0; cle<=0; end
//reset和A状态时,不进行周期计数和求和。
            else  //state==B时
                begin                     
                    if(cle<=2) cle<=cle+1;   //每来一个触发信号cle就加1,当cle==3时,
                    else cle <=1; //当cle==3时,回到1开始计数而不是0,循环“1-2-3”而不是“0-1-2-3”                   
                    if(cle==3) cout <=w;  //求和cout,当一个周期结束时,cout==w,即可重新开始求和。
                    else cout <= cout+w; //求和+w。
                end
        end
    assign z = cout==2&&cle==3 ; //判断
    
endmodule

你可能感兴趣的:(Verilog例题,fpga开发)