电子说
那些年,你总是不停的说序列检测,每当有人谈到序列检测你便说自己会一、二、三段式moore、mealy型状态机,茴字有几种写法...
假设需要一个01101010比特流检测电路,并输出检测成果标志
当你开始考虑使用几个状态的时候,并好不容易写出以下代码的时候:
module detect2(
input clk,
input rst_n,
input din,
output reg flag
);
//reg [2:0]state=3'b000;
parameter IDLE=3'b000, //0
state1=3'd1, //1
state2=3'd2, //0
state3=3'd3, //1
state4=3'd4, //0
state5=3'd5, //1
state6=3'd6, //1
state7=3'd7; //0
reg [2:0]cur_state;
reg [2:0]nxt_state;
//第一个always块用于状态转移
always@(posedge clk or negedge rst_n)
if(~rst_n)
cur_state<=IDLE;
else
cur_state<=nxt_state;
/*
检测8'b01101010
*/
always@(*)
begin
case(cur_state)
IDLE:
begin
if(din==1'b0)
nxt_state=state1; //0
else
nxt_state=IDLE;
end
state1:
begin
if(1'b1==din)
nxt_state=state2; //10
else
nxt_state=IDLE;
end
state2:
begin
if(1'b0==din)
nxt_state=state3; //010
else
nxt_state=IDLE;
end
state3: //有三个正确的接收数字
begin
if(1'b1==din)
nxt_state<=state4; //1010
else
nxt_state=IDLE;
end
state4:
begin
if(1'b0==din)
nxt_state=state5; //01010
else
nxt_state=IDLE;
end
state5:
begin
if(1'b1==din)
nxt_state=state6; //101010
else
nxt_state=IDLE;
end
state6:
begin
if(1'b1==din)
nxt_state=state7; //110_1010
else
nxt_state<=state3; //010
end
state7:
begin
nxt_state=IDLE;
end
default:;
endcase
end
always@(posedge clk or negedge rst_n)
if(~rst_n)
flag<=1'b0;
else if(cur_state==state7&&(1'b0==din))
flag<=1'b1;
else
flag<=1'b0;
endmodule