Saturday, April 18, 2020

Verilog Tutorial 3: FSM based design

This is the third part of the Verilog Tutorials series. Click here for the first part.

Now let us assume it is not easy to manually design and obtain the complete logic diagram. Then you can implement the Finite State Machine (FSM) directly in Verilog using behavioral modelling. 
This is the primary job of an RTL Design Engineer in a VLSI industry.


Consider the sequence detector discussed in Sequential Circuit Design section.
From the state diagram, we have:
4 states S0, S1, S2, S3 encoded as 00, 01, 10, 11.
Declare them as parameter. Parameter is used to substitute a variable in place of some data as S0 notation is easier to comprehend than 00.
(Note: We will see more about parameter in part 5 of the tutorial.)

Variable 'state' is sequential as state changes only at a clock edge.
We can be in only one state at any time. So next_state (input to Flip-Flop 'state') can be implemented using a case statement as it changes based on the input (combinational).

Our sequence detector has been implemented using a Moore state machine. Hence, the output depends only on the state that we are present in.

Verilog Code:


module seq_detector(clk, rst, X, Y);
parameter S0 = 2'b00;  //encoded states as parameters
parameter S1 = 2'b01;
parameter S2 = 2'b10;
parameter S3 = 2'b11;

input clk;
input rst;
input X;
output Y;

reg [1:0] state, next_state;        //2 bits each
wire Y;  
               
assign Y = state[1] & state[0];

always @ (posedge clk or negedge rst)   //sequential part
begin
 if(!rst)
 begin
 state <= S0;
 end
 else
 begin
 state <= next_state;
 end
end

always @ (*)         //combinational part
begin
case(state)
 S0:
 next_state = X ? S1 : state;  
//if X is 1, goto S1 otherwise remain in S0
 S1:
 next_state = X ? S2 : S0;
 S2:
 next_state = X ? S3 : S0;
 S3:
 next_state = X ? S3 : S0;
 default:
 next_state = state;
endcase
end
endmodule

From the above code, consider this line:
next_state = X ? S1 : state;

Here, ? is a ternary operator. If X is 1, then next_state gets S1 otherwise next_state gets state.
It is a short version of the if-else statement.
However, the generated logic is the same (mux):
mux logic in verilog






Analyzing the entire code, we have one big mux for the case statement. And then within each case, we have small muxes as shown above for each ternary operator condition.

With this simple code, we have implemented the '111' sequence detector using a Moore Machine.
In the next tutorial, I will explain how to write a testbench inorder to simulate and verify the operation of the sequence detector.

No comments:

Post a Comment