那些年,你總是不停的說序列檢測,每當有人談到序列檢測你便說自己會一、二、三段式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