有限オートマトンで4進カウンタ
Verilogで有限オートマトン(FSM)を書く練習。クロックが立ち上がるたびに0→1→2→3→0→1とカウントアップしていく4進カウンタ。
code:counter.sv
// 4進カウンタ
// iverilog counter_test.sv && ./a.out
module counter(
input clk, reset,
);
// ステートをenumで定義
typedef enum {s0, s1, s2, s3} counter_state;
// stateとnext_stateを宣言
counter_state state_reg, state_next;
// クロックの立ち上がりの度にステートを更新
always_ff @(posedge clk)
if (reset)
state_reg <= s0;
else
state_reg <= state_next;
// 入力とstateの組み合わせに応じたnext_stateを定義
// (今回は入力が無いので現在のステートでのみnext_stateが決定される)
always_comb
case (state_reg)
s0: state_next = s1;
s1: state_next = s2;
s2: state_next = s3;
s3: state_next = s0;
default: state_next = s0;
endcase
// ステートを出力に変換
assign y = (state_reg == s0) ? 2'b00 :
(state_reg == s1) ? 2'b01 :
(state_reg == s2) ? 2'b10
: 2'b11;
endmodule
module counter_test();
logic clk = 0;
logic reset = 0;
counter c(
.clk(clk),
.reset(reset),
.y(y)
);
initial begin
$display("%d", y); //=> 0
$display("%d", y); //=> 1
$display("%d", y); //=> 2
$display("%d", y); //=> 3
$display("%d", y); //=> 0
$display("%d", y); //=> 1
end
endmodule