计数器练习
设计目标
计数器练习1:计数器位宽为8,计数器持续计数观测效果。
计数器练习2:计数器位宽为8,持续计数,使用缩减运算符&cnt。
计数器练习3:计数器位宽为8,计数器计数到6回到0,以此循环,要求输出一个信号,计数器一个循环里拉高三个时钟周期。
计数器练习4:根据计数器,做出闪光灯,LED灯1s亮灭。
练习1
TEST_CNT代码
module TEST_CNT (
input wire clk,
input wire rst_n
);
reg [7:0]cnt;
always @(posedge clk or negedge rst_n) begin
if (~rst_n) begin
cnt <= 8'd0;
end
else begin
cnt <= cnt + 8'd1;
end
end
endmodule
tb文件
`timescale 1ns/1ps
module TEST_CNT_tb ();
reg clk;
reg rst_n;
initial begin
clk = 1'b0;
rst_n = 1'b0;
#2
rst_n = 1'b1;
end
always #10 clk = ~clk;
TEST_CNT TEST_CNT_1(
.clk(clk),
.rst_n(rst_n)
);
endmodule
仿真结果
练习2
TEST_CNT2代码
module TEST_CNT2 (
input wire clk,
input wire rst_n
);
reg [7:0]cnt;
always @(posedge clk or negedge rst_n) begin
if (~rst_n) begin
cnt <= 8'd253;
end
else if(&cnt == 1)begin
cnt <= 8'd0;
end
else begin
cnt <= cnt + 1;
end
end
endmodule
tb文件
`timescale 1ns/1ps
module TEST_CNT2_tb ();
reg clk;
reg rst_n;
initial begin
clk = 1'b0;
rst_n = 1'b0;
#2
rst_n = 1'b1;
end
always #10 clk = ~clk;
TEST_CNT2 TEST_CNT2_1(
.clk(clk),
.rst_n(rst_n)
);
endmodule
仿真结果
练习3
TEST_CNT3代码
module TEST_CNT3 (
input wire clk,
input wire rst_n,
output reg Y
);
reg [7:0]cnt;
//if语句实现计数器(计6个数)
always @(posedge clk or negedge rst_n) begin
if (~rst_n) begin
cnt <= 8'd0;
end
else if(cnt == 8'd6)begin
cnt <= 8'd0;
end
else begin
cnt <= cnt + 8'd1;
end
end
//输出波形
always @(posedge clk or negedge rst_n) begin
if (~rst_n) begin
Y <= 8'd0;
end
else if(cnt == 8'd1||cnt == 8'd3||cnt == 8'd4||cnt == 8'd6)begin
Y <= 8'd0;
end
else begin
Y <= 8'd1;
end
end
endmodule
tb文件
`timescale 1ns/1ps
module TEST_CNT3_tb ();
reg clk;
reg rst_n;
wire Y;
initial begin
clk = 1'b0;
rst_n = 1'b0;
#2
rst_n = 1'b1;
end
always #10 clk = ~clk;
TEST_CNT3 TEST_CNT3_1(
.clk(clk),
.rst_n(rst_n),
.Y(Y)
);
endmodule
仿真结果
练习四
TEST_CNT4
module TEST_CNT4 (
input wire clk,
input wire rst_n,
output reg Y
);
reg [31:0]cnt = 32'd0;
//32位计数器来控制计数器到达2s
always @(posedge clk or negedge rst_n) begin
if (~rst_n) begin
cnt <= 32'd0;
end
else if (cnt == 100000000 - 1) begin
cnt <= 32'd0;
end
else begin
cnt <= cnt + 32'd1;
end
end
//控制LED灯的亮灭
always @(posedge clk or negedge rst_n) begin
if (~rst_n) begin
Y <= 1'b0;
end
else if(cnt >= 32'd50000000-1)begin
Y <= 1'b0;
end
else begin
Y <= 1'b1;
end
end
endmodule
tb问价
`timescale 1ns/1ps
module TEST_CNT4_tb ();
reg clk;
reg rst_n;
wire Y;
initial begin
clk = 1'b0;
rst_n = 1'b0;
#2
rst_n = 1'b1;
#2000000000
$stop;
end
always #10 clk = ~clk;
TEST_CNT4 TEST_CNT4_1(
.clk(clk),
.rst_n(rst_n),
.Y(Y)
);
endmodule