[HDLbits]——Exams/2014 q3fsm

@HDLbits

Exams/2014 q3fsm

Question: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.
[HDLbits]——Exams/2014 q3fsm_第1张图片
分析:首先可以将这个问题分为两个部分,一个是包含A、B两个状态的状态机,另一个是关于输出z。第一个部分比较简单,第二个部分不仅需要一个counter1对三个周期内的w计数,还需要第二个counter2对周期进行计数,使得每3个周期将所有的counter重置一次。因此,该题写成了下面的形式:
(我写完后,看了一些其他博主的答案,还有一种思路是多加几个状态,来代替counter2,也是一种不错的思路)
注意assign z = cnt==2 && cntr==3;看似是对第三个时钟周期的z进行输出,但counter输出是比state慢一个周期的,因此该输出是在第三个周期的下一个周期,也就是第四个周期。

module top_module (
    input clk,
    input reset,   // Synchronous reset
    input s,
    input w,
    output z
);
	parameter A=1'b0,B=1'b1;
    reg state,nstate;
    reg [1:0] cnt,cntr;
    
    always @(*) begin
        case(state)
            A: nstate = s?B:A;
            B: nstate = B;
            default: nstate = B;
        endcase
    end
    
    always @(posedge clk) begin
        if(reset)
            state <= A;
        else
            state <= nstate;
    end
    
    always @(posedge clk) begin
        if(reset) begin
            cnt <= 2'b0;
            cntr <= 2'b0;
        end
        else if(state==A) begin
            cnt <= 2'b0;
            cntr <= 2'b0;
        end
        else if(cntr==3) begin
            cntr<=2'b1;
            cnt <= w;
        end
        else begin
            cntr <= cntr + 1'b1;
            cnt <= cnt + w;
        end
    end
      
    assign z = cnt==2&&cntr==3;
          
endmodule

你可能感兴趣的:(verilog)