下面以上图一个简单的FSM说明三段式Verilog状态机范式:
1 `timescale 1ns / 1ps 2 module FSM( 3 clk,rst_n, 4 in1,in2, 5 out1,out2, 6 CS,NS 7 ); 8 input clk,rst_n; 9 input in1,in2; 10 output out1,out2; 11 output [1:0] CS,NS; 12 13 reg [1:0] CS,NS; 14 reg out1,out2; 15 16 parameter St0 = 2'b00, 17 St1 = 2'b01, 18 St2 = 2'b10, 19 St3 = 2'b11; 20 21 // 1、状态切换 22 always @(posedge clk or negedge rst_n) 23 if(!rst_n) 24 begin 25 CS<=St0; 26 end 27 else 28 CS<=NS; 29 30 // 2、次态转移 31 always @ (*) 32 begin 33 case(CS) 34 St0: 35 begin 36 if(in1==1'b1) NS=St1; 37 else NS=St0; 38 end 39 St1: 40 begin 41 NS=St2; 42 end 43 St2: 44 begin 45 NS=St3; 46 end 47 St3: 48 begin 49 if(in2==1'b1) NS=St0; 50 else NS=St3; 51 end 52 default:NS=St0; 53 endcase 54 end 55 56 //3、输出逻辑 57 always @(*) 58 begin 59 if(CS==St1) out1=1'b1; 60 else out1=1'b0; 61 if(CS==St2) out2=1'b1; 62 else out2=1'b0; 63 end 64 65 endmodule