verilog HDLBits刷题[Finite State Machines]“Exams/2014 q3fsm”---Q3a:FSM

📅 2026/8/3 0:29:46 👁️ 阅读次数 📝 编程学习
verilog HDLBits刷题[Finite State Machines]“Exams/2014 q3fsm”---Q3a:FSM

1、题目

Consider a finite state machine with inputssandw. Assume that the FSM begins in a reset state calledA, as depicted below. The FSM remains in stateAas long ass= 0, and it moves to stateBwhens= 1. Once in stateBthe FSM examines the value of the inputwin the next three clock cycles. Ifw= 1 in exactly two of these clock cycles, then the FSM has to set an outputzto 1 in the following clock cycle. Otherwisezhas to be 0. The FSM continues checkingwfor the next three clock cycles, and so on. The timing diagram below illustrates the required values ofzfor different values ofw.

Use as few states as possible. Note that thesinput is used only in stateA, so you need to consider just thewinput.

2、分析

s=0,进入号状态A,s=1,进入状态B,接着观察三个时钟周期内w为1的个数,如果三个时钟周期内刚好有2个w为1,则在第四个时钟周期将z拉高,其它时候z=0.

故可以四种状态

A:复位状态

B:第一个w

C:第二个w

D:第三个w,第三个w结束后从第一个w开始三个时钟周期

3、代码

module top_module ( input clk, input reset, // Synchronous reset input s, input w, output z ); parameter A=0,B=1,C=2,D=3; reg [2:0]state,next_state; reg [2:0]cnt;//计算有多少个w为1 always@(posedge clk)begin if(reset) state<=A; else state<=next_state; end always@(*)begin case(state) A:next_state=s?B:A; B:next_state=C; C:next_state=D; D:next_state=B; default:next_state=A; endcase end always@(posedge clk)begin if(reset) cnt<=3'd0; else begin case(state) A:cnt<=3'd0; B:cnt<=w; C:cnt<=cnt+w; D:cnt<=cnt+w; default:cnt<=3'd0; endcase end end assign z=(state==B&cnt==2); endmodule