# 计数器¶

## 计数器规则¶

### 计数器规则1: 计数器逐一考虑三要素–初值、加1条件、结束条件¶

• 初值：计数器的默认值或者开始计数的值

• 加1条件：计数器执行加1条件

• 结束值：计数器计数周期的最后一个值 设计计数器，要逐一考虑这三个要素，一般是先考虑初值，再考虑加1条件，最后再考虑结束值。

### 计数器规则8：设计步骤¶

VHDL

```process(clk,rst_n)
begin
if(rst_n = '0')then
cnt <= 0;
elsif(clk'event and clk = '1')then
if(加1条件)then
if(结束条件)then
cnt <= 0;
else
cnt <= cnt + 1;
end if;
end if;
end if;
end process;
```

verilog

```always @(posedge clk or negedge rst_n) begin
if(!rst_n) begin
cnt <= 0;
end
else if(加1条件) begin
if(结束条件)
cnt <= 0;
else
cnt <= cnt + 1;
end
end
```

VHDL

```process(clk,rst_n)
begin
if(rst_n = '0')then
cnt <= 0;
elsif(clk'event and clk = '1')then
if(end_cnt)then
cnt <= 0;
else
cnt <= cnt + 1;
end if;
end if;
end if;
end process;
```

verilog

```always @(posedge clk or negedge rst_n) begin
if(!rst_n) begin
cnt <= 0;
end
if(end_cnt)
cnt <= 0;
else
cnt <= cnt + 1;
end
end
```

VHDL

```add_cnt <=  a=2;--add 1
```

verilog

```assign add_cnt = a==2;//add 1
```

VHDL

```end_cnt <= add_cnt and (cnt =  10-1);--end
```

verilog

```assign end_cnt = add_cnt && cnt == 10-1; //end
```

VHDL

```signal cnt : integer range 0 to  ;--max number
signal end_cnt : boolean;

process(clk,rst_n)
begin
if(rst_n = '0')then
cnt <= 0;
elsif(clk'event and clk = '1')then
if(end_cnt)then
cnt <= 0;
else
cnt <= cnt + 1;
end if;
end if;
end if;
end process;

end_cnt <= add_cnt and (cnt =  -1);--end
```

```signal cnt : integer range 0 to  ;--在 to 后面补充计数器的最大计数范围
end_cnt <= add_cnt and (cnt =  -1);--补充计数器数多少数
```

verilog

```reg [  :0]   cnt    ;
wire         end_cnt;

always @(posedge clk or negedge rst_n) begin
if(!rst_n) begin
cnt <= 0;
end
if(end_cnt)
cnt <= 0;
else
cnt <= cnt + 1;
end
end

assign end_cnt = add_cnt && cnt ==  -1; //End condition, last value
```

```reg [  :0]   cnt    ;//补充计数器的最大计数范围
assign end_cnt = add_cnt && cnt ==  -1; //补充计数器数多少数
```