module BinaryCounter (
input wire clk,
input wire reset,
output reg [3:0] count
);
// 定义状态
typedef enum logic [1:0] {
S0, S1, S2, S3
} State;
// 定义状态寄存器
reg [1:0] current_state, next_state;
// 初始化状态寄存器
initial begin
current_state = S0;
next_state = S0;
count = 4'b0000;
end
// 状态机逻辑
always @(posedge clk or posedge reset) begin
if (reset) begin
current_state <= S0;
count <= 4'b0000;
end
else begin
current_state <= next_state;
case (current_state)
S0: next_state <= S1;
S1: next_state <= S2;
S2: next_state <= S3;
S3: next_state <= S0;
default: next_state <= S0;
endcase
end
end
// 输出逻辑
always @(posedge clk) begin
case (current_state)
S0: count <= count + 1;
S1: count <= count + 1;
S2: count <= count + 1;
S3: count <= count + 1;
default: count <= 4'b0000;
endcase
end
endmodule
在这个例子中,BinaryCounter 模块是一个有限状态机,它有四个状态 S0、S1、S2 和 S3。状态之间的转移是通过 case 语句实现的。状态机的输出是一个4位的计数器 count,在每个状态上按照不同的规则递增。在上升沿触发的时钟信号下,状态机根据当前状态和输入信号进行状态转移,并计算新的计数器值。
状态机是数字电路中常用的设计模式,可用于描述系统中复杂的控制逻辑。
转载请注明出处:http://www.pingtaimeng.com/article/detail/11037/Verilog