状态机的实例之序列检测器
通过百度百科的查阅:状态机由状态寄存器和组合逻辑电路构成,能够根据控制信号按照预先设定的状态进行状态转移,是协调相关信号动作、完成特定操作的控制中心。有限状态机简写为FSM(Finite State Machine),主要分为2大类:
第一类,若输出只和状态有关而与输入无关,则称为Moore状态机
第二类,输出不仅和状态有关而且和输入有关系,则称为Mealy状态机
状态机的小实例
设计序列检测器:有“101”序列输入时输出为1,其他输入情况下,输出为0。画出状态转移图,并用Verilog描述。
要输出101序列,由状态图可知,S3状态时刚好为101序列,因此
flag_101 = (state == S3)? 1’b1: 1’b0;
因为是101三位,则设计四个状态即可,用00,01,10,11即可表示,所以选择 reg [1:0] state;
Verilog代码
module Dectect_101(
input clk,
input rst_n,
input data,
output flag_101
);
parameter S0 = 0,
S1 = 1,
S2 = 2,
S3 = 3;
reg [1:0] state;
always @(posedge clk or negedge rst_n)begin
if(rst_n == 1'b0)begin
state <= S0;
end
else begin
case(state)
S0:
if(data == 1)
state <= S1;
else
state <= S0;
S1:
if(data == 0)
state <= S2;
else
state <= S1;
S2:
if(data == 1)
state <= S3;
else
state <= S0;
S3:
if(data == 1)
state <= S1;
else
state <= S2;
endcase
end
end
assign flag_101 = (state == S3)? 1'b1: 1'b0;
endmodule
testbench
`timescale 1ns/1ns
`define clock_period 20
module Dectect_101_tb;
reg clk;
reg rst_n;
reg [1:0] s;
wire flag_101;
Dectect_101 Dectect_101(
.clk(clk),
.rst_n(rst_n),
.flag_101(flag_101),
.data(s)
);
initial clk=1;
always #(`clock_period/2) clk = ~clk;
initial begin
rst_n = 0;
s = 2'd0;
#(`clock_period*200)
rst_n = 1;
#(`clock_period*200)
forever begin
s = 2'd1;
#(`clock_period)
s = 2'd2;
#(`clock_period)
s = 2'd3;
#(`clock_period)
s = 2'd0;
#(`clock_period)
s = 2'd0;
#(`clock_period)
s = 2'd1;
#(`clock_period)
s = 2'd3;
#(`clock_period)
s = 2'd2;
end
end
endmodule
因为我们想得到的是101序列为1,其余为0,则S3时高电平,其余低电平,同时S3用3来表示的,则当S=3时输出为高电平,其余情况均为低电平。
波形图