k0b0's record.

Computer Engineering, Arts and Books

Introduction to SystemVerilog. Counter, Finite State Machine (FSM) (Moor Machine, Mealy Machine)

カウンタ、有限状態マシン

 SystemVerilogでカウンタ、有限状態マシンを記述してみる。

カウンタ

カウンタ(counterN.sv)

 Nビットカウンタの記述。クロック信号(clk)の立ち上がり時にカウンター値(q)がカウントされる。なお、カウンターのリセットはリセット信号(reset)により行う。

/* counterN.sv */
module counterN #(parameter WIDTH = 8)
                 (input  logic clk,
		  input  logic reset,
	          output logic [WIDTH-1:0] q);

always_ff @(posedge clk, posedge reset)
begin
    if (reset) q <= 0;
    else       q <= q + 1;
end
endmodule

有限状態マシン(FSM : Finite State Machine)

FSM(fsm3.sv)

 3状態の有限状態マシンの記述。typedefによって定義されたstatetype型で各状態(S0、S1、S2)を定義している。クロック信号(clk)の立ち上がり時に現状態は次状態に遷移する。現状態がS0の場合に出力(y)は'1'となる。次状態はalways_comb文+case文で記述した組合わせ回路によって決定する。

/* fsm3.sv */
module fsm3 (input  logic clk,
             input  logic reset,
	     output logic y);

typedef enum logic [1:0] {S0, S1, S2} statetype;

statetype state, nextstate;

// State Register
always_ff @(posedge clk, posedge reset)
begin
    if(reset) state = S0;
    else      state = nextstate;
end

// Determine the next state
always_comb
begin
    case(state)
	S0: nextstate = S1;
	S1: nextstate = S2;
	S2: nextstate = S0;
	default: nextstate = S0;
    endcase
end

//output
assign y = (state == S0);
endmodule

moore FSM(moore_fsm3.sv)

 ムーア型有限状態マシン(出力が現状態によってのみ決定するマシン)の記述例。

/* moore_fsm3.sv */
module moore_fsm3 (input  logic clk,
                   input  logic reset,
		   input  logic a,
	           output logic y);

typedef enum logic [1:0] {S0, S1, S2} statetype;

statetype state, nextstate;

// State Register
always_ff @(posedge clk, posedge reset)
begin
    if(reset) state = S0;
    else      state = nextstate;
end

// Determine the next state
always_comb
begin
    case(state)
	S0: if(a) nextstate = S1;
	    else  nextstate = S0;
	S1: if(a) nextstate = S2;
	    else  nextstate = S1;
	S2: if(a) nextstate = S0;
	    else  nextstate = S1;
	default:  nextstate = S0;
    endcase
end

//The output is determined by the current state.
assign y = (state == S2);
endmodule

mealy FSM(mealy_fsm3.sv)

 ミーリ型有限状態マシン(出力が現状態と入力によって決定するマシン)の記述例。

/* mealy_fsm3.sv */
module mealy_fsm3 (input  logic clk,
                   input  logic reset,
		   input  logic a,
	           output logic y);

typedef enum logic [1:0] {S0, S1, S2} statetype;

statetype state, nextstate;

// State Register
always_ff @(posedge clk, posedge reset)
begin
    if(reset) state = S0;
    else      state = nextstate;
end

// Determine the next state
always_comb
begin
    case(state)
	S0: if(a) nextstate = S1;
	    else  nextstate = S0;
	S1: if(a) nextstate = S2;
	    else  nextstate = S0;
	S2: if(a) nextstate = S1;
	    else  nextstate = S0;
	default:  nextstate = S0;
    endcase
end

//The output is determined by the current state and input.
assign y = (a & (state == S2));
endmodule