Detecting pattern is come in Digital design and it is most commonly question during the interview.
Here is one example of detecting " 100110 " pattern using a FSM.
Click below to get the code
Here is one example of detecting " 100110 " pattern using a FSM.
Click below to get the code
Verilog Code for FSM ->
/// ------------------------- Disclaimer--------------------------------
// CopyRight to Rahul Jain
// Do not use this code in any product , this is just a sample code
/// ------------------------- Start -------------------------------------
module pattern_det (
input din,
input clk,
input rstn,
output pat_det
);
parameter ST0 = 3'd0;
parameter ST1 = 3'd1;
parameter ST2 = 3'd2;
parameter ST3 = 3'd3;
parameter ST4 = 3'd4;
parameter ST5 = 3'd5;
reg [2:0] cur_st;
reg [2:0] next_st;
always @(posedge clk or negedge rstn ) begin
if(!rstn)
cur_st <= 3'b0;
else
cur_st <= next_st;
end
always @(*) begin
case(cur_st)
ST0 : if (din == 1'b1 )
next_st = ST1;
else
next_st = ST0;
ST1: if (din == 1'b0 )
next_st = ST2;
else
next_st = ST1;
ST2: if (din == 1'b0 )
next_st = ST3;
else
next_st = ST1;
ST3: if (din == 1'b1 )
next_st = ST4;
else
next_st = ST0;
ST4: if (din == 1'b1 )
next_st = ST5;
else
next_st = ST2;
ST5: if (din == 1'b0 )
next_st = ST0;
else
next_st = ST1;
default : next_st = ST0;
endcase
end
assign pat_det = (cur_st == ST5 && next_st == ST0 );
endmodule
module tb;
reg clk =0 ;
reg rstn =0 ;
reg din =0;
reg [31:0] stim =0 ;
reg inst =0;
always #5 clk = ~clk ;
always @(posedge clk ) begin
#1;
stim[30:0] = stim[31:1] ;
stim[31] = stim[22] + stim [24] + stim[2];
if(inst)
stim[30:25] = 6'b011001 ;
end
initial begin
#100;
rstn =1 ;
#100;
inst =1 ;
#10 ;
inst =0 ;
#1000;
$finish;
end
initial begin
$recordfile("fsm.trn");
$recordvars();
end
pattern_det DUT(
.clk(clk),
.rstn(rstn),
.din(stim[0])
);
endmodule
/// ------------------------- End -------------------------------------
Simulation Result :
Thanks for reading my Blog.
Thanks for sharing the code .. Nice blog
ReplyDeleteSir how can I count how many times the pattern is detected in fsm
ReplyDelete777900
ReplyDelete