请给出用verilog语言实现以下功能的代码:由按键KEY0、KEY1控制计数器的值并在数码管上显示,每按下抬起一次KEY0计数加1,每按下抬起一次KEY1计数减1,计数加到100时归零,按照十进制在数码管的两位上动态显示,先显示十位再显示个位,其中两个数码管共阴极,其它管脚接在一起实现段选复用,由位选选择控制两位数码管的动态显示,按下复位按钮后计数归零,并给出响应的检测其功能的testbentch测试文件代码
时间: 2024-03-06 12:52:19 浏览: 70
计数器verilog 代码
4星 · 用户满意度95%
以下是用Verilog语言实现功能的代码:
```
module counter(
input CLK, //时钟信号
input RST, //复位信号
input KEY0, //按键0
input KEY1, //按键1
output reg [6:0] SEG, //数码管显示数据
output reg [1:0] SEL //位选信号
);
reg [7:0] cnt; //计数器
//时钟上升沿计数
always @(posedge CLK) begin
if (RST) //复位信号有效
cnt <= 0;
else if (KEY0) //按键0有效
cnt <= (cnt == 99) ? 0 : cnt + 1;
else if (KEY1) //按键1有效
cnt <= (cnt == 0) ? 99 : cnt - 1;
end
//数码管动态显示
integer i;
reg [1:0] digit;
reg [6:0] code [0:9]; //数码管段码表
initial begin
code[0] = 7'b111_1110;
code[1] = 7'b011_0000;
code[2] = 7'b110_1101;
code[3] = 7'b111_1001;
code[4] = 7'b011_0011;
code[5] = 7'b101_1011;
code[6] = 7'b101_1111;
code[7] = 7'b111_0000;
code[8] = 7'b111_1111;
code[9] = 7'b111_1011;
end
always @(posedge CLK) begin
if (RST) //复位信号有效
digit <= 2'b00;
else begin
if (digit == 2'b01) //个位
SEG <= code[cnt % 10];
else //十位
SEG <= code[cnt / 10];
for (i = 0; i < 500; i = i + 1) //延时
SEL <= digit;
digit <= (digit == 2'b01) ? 2'b00 : 2'b01; //切换位选信号
end
end
endmodule
```
以下是检测功能的testbench测试文件代码:
```
module testbench;
reg CLK;
reg RST;
reg KEY0;
reg KEY1;
wire [6:0] SEG;
wire [1:0] SEL;
counter c(CLK, RST, KEY0, KEY1, SEG, SEL);
initial begin
CLK = 0;
RST = 1;
KEY0 = 0;
KEY1 = 0;
#10 RST = 0;
#100;
KEY0 = 1;
#10 KEY0 = 0;
#100;
KEY1 = 1;
#10 KEY1 = 0;
#100;
KEY0 = 1;
#10 KEY0 = 0;
#100;
KEY1 = 1;
#10 KEY1 = 0;
#100;
KEY0 = 1;
#10 KEY0 = 0;
#100;
KEY1 = 1;
#10 KEY1 = 0;
#100;
KEY0 = 1;
#10 KEY0 = 0;
#100;
KEY1 = 1;
#10 KEY1 = 0;
#100;
KEY0 = 1;
#10 KEY0 = 0;
#100;
KEY1 = 1;
#10 KEY1 = 0;
#100;
KEY0 = 1;
#10 KEY0 = 0;
#100;
KEY1 = 1;
#10 KEY1 = 0;
#100;
KEY0 = 1;
#10 KEY0 = 0;
#100;
KEY1 = 1;
#10 KEY1 = 0;
#100;
KEY0 = 1;
#10 KEY0 = 0;
#100;
KEY1 = 1;
#10 KEY1 = 0;
#100;
KEY0 = 1;
#10 KEY0 = 0;
#100;
KEY1 = 1;
#10 KEY1 = 0;
#100;
KEY0 = 1;
#10 KEY0 = 0;
#100;
KEY1 = 1;
#10 KEY1 = 0;
#100;
KEY0 = 1;
#10 KEY0 = 0;
#100;
KEY1 = 1;
#10 KEY1 = 0;
#100;
KEY0 = 1;
#10 KEY0 = 0;
#100;
KEY1 = 1;
#10 KEY1 = 0;
#100;
KEY0 = 1;
#10 KEY0 = 0;
#100;
KEY1 = 1;
#10 KEY1 = 0;
#100;
KEY0 = 1;
#10 KEY0 = 0;
#100;
KEY1 = 1;
#10 KEY1 = 0;
#100;
KEY0 = 1;
#10 KEY0 = 0;
#100;
KEY1 = 1;
#10 KEY1 = 0;
#100;
KEY0 = 1;
#10 KEY0 = 0;
#100;
KEY1 = 1;
#10 KEY1 = 0;
#100;
KEY0 = 1;
#10 KEY0 = 0;
#100;
KEY1 = 1;
#10 KEY1 = 0;
#100;
KEY0 = 1;
#10 KEY0 = 0;
#100;
KEY1 = 1;
#10 KEY1 = 0;
#100;
KEY0 = 1;
#10 KEY0 = 0;
#100;
KEY1 = 1;
#10 KEY1 = 0;
#100;
$finish;
end
always #5 CLK = ~CLK;
endmodule
```
该测试文件模拟了按下抬起按键的过程,通过检查数码管的显示结果来验证计数器的功能是否正确。
阅读全文