Wednesday, February 29, 2012

Verilog Code for FSMs


Verilog code for an FSM with a single process.
 module fsm (clk, reset, x1, outp);
 input        clk, reset, x1;
 output       outp;
 reg          outp;
 reg    [1:0] state;
 parameter s1 = 2’b00; parameter s2 = 2’b01;
 parameter s3 = 2’b10; parameter s4 = 2’b11;
 always @(posedge clk or posedge reset)
 begin
    if (reset) begin
       state <= s1; outp <= 1’b1;
    end 
    else begin
       case (state)
   s1: begin 
   if (x1 == 1’b1) begin
      state <= s2;
                           outp  <= 1’b1;
   end
   else begin
      state <= s3;
                           outp  <= 1’b1;
   end
       end
   s2: begin
   state <= s4; 
                        outp  <= 1’b0;
       end
   s3: begin
   state <= s4; 
                        outp  <= 1’b0;
       end
   s4: begin
   state <= s1; 
                        outp  <= 1’b1;
       end
       endcase
    end
 end
        endmodule
        

Verilog code for an FSM with two processes.
 module fsm (clk, reset, x1, outp);
 input        clk, reset, x1;
 output       outp;
 reg          outp;
 reg    [1:0] state;
 parameter s1 = 2’b00; parameter s2 = 2’b01;
 parameter s3 = 2’b10; parameter s4 = 2’b11;
 always @(posedge clk or posedge reset)
 begin
    if (reset)
       state <= s1;
    else begin
       case (state)
   s1: if (x1 == 1’b1)
   state <= s2;
       else
   state <= s3;
   s2: state <= s4;
   s3: state <= s4;
   s4: state <= s1;
       endcase
    end
 end
 always @(state) begin
    case (state)
       s1: outp = 1’b1;
       s2: outp = 1’b1;
       s3: outp = 1’b0;
       s4: outp = 1’b0;
    endcase
 end
        endmodule
        

Verilog code for an FSM with three processes.
 module fsm (clk, reset, x1, outp);
 input        clk, reset, x1;
 output       outp;
 reg          outp;
 reg    [1:0] state;
 reg    [1:0] next_state;
 parameter s1 = 2’b00; parameter s2 = 2’b01;
 parameter s3 = 2’b10; parameter s4 = 2’b11;
 always @(posedge clk or posedge reset)
 begin
    if (reset)
       state <= s1;
    else 
       state <= next_state;
 end

 always @(state or x1)
 begin
    case (state)
       s1: if (x1 == 1’b1)
       next_state = s2;
    else
       next_state = s3;
       s2: next_state = s4;
       s3: next_state = s4;
       s4: next_state = s1;
    endcase
        end
        

No comments:

Post a Comment

Popular Posts