Pages

Tuesday 22 August 2017

Verilog code for Moore-Finite State Machines (FSM)

 State Diagram

 

Verilog Code

module moore(Clock,Reset, next_state,Input,Output);

input Clock,Reset,Input;
output Output;
output reg[1:0] next_state =2'b00;
reg [1:0] state;
reg Output;
parameter s0 = 2'b00,
             s1 = 2'b01,
             s2 = 2'b10,
             s3 = 2'b11;

always@(posedge Clock,negedge Reset)

begin
if(Reset==0)
state <= s0;
else
begin
case(state)
s0:
    if(Input) // if Inputput = 1 then state go to 01
        begin
        next_state <= s1;
        state =2'b01;
        end
     else
        begin
        next_state <= s2;
        state =2'b10;
        end
s1 :
    if(Input)
        begin
         next_state <= s3;
        state =2'b11;      
        end
    else
        begin
        next_state <= s2;
        state =2'b10;
        end
s2:
     if(Input)
        begin
        next_state <= s1;
        state =2'b01;
        end
     else
        begin
         next_state <= s3;
        state =2'b11;      
        end
s3:
    if(Input)
        begin
        next_state <= s1;
        state =2'b01;
        end
     else
        begin
        next_state <= s2;
        state =2'b10;
        end
endcase
end
end
always @(posedge Clock, negedge Reset)
begin
     if(Reset==0)
         Output <= 0;
    else if(state ==2'b11)
        Output <= 1;
    else
         Output <= 0;
    end
endmodule

Test Bench

module moore_tb();
reg Clock,Reset,Input;

wire[0:0] Output ;
wire[1:0] next_state ;
moore test (Clock,Reset,next_state,Input,Output);
initial
begin
Clock = 0;
forever #50 Clock =~Clock;
end
initial
begin
Reset = 0;
#50 Reset = 1;

#100 Input = 1;
#100 Input = 0;
#100 Input = 1;
#100 Input = 1;
#100 Input = 0;
#100 Input = 1;
#100 Input = 1;
#100 Input = 1;
#100 Input = 1;
#100 Input = 1;
#100 Input = 1;
#100 Input = 0;
#100 Input = 0;
#100 Input = 0;
#100 Input = 0;
end
initial
$monitor ("CLOCK = %b, Reset = %b,Input = %b,state =%d,Output = %b", Clock,Reset, Input,next_state,Output);
endmodule

RTL Viewer

 

 

 

 RTL Simulation

 

No comments:

Post a Comment