FPGA(五)---BCD计数器

一、BCD码

BCD码就是将十进制中的数,转换为十六进制,都用二进制进行表示。
例如:153 转换为十六进制是99 --> 1001 1001
68 转换为十六进制是45 -->0100 0101

二、代码

模块一:四位计数器

module BCD_counter(cin,clk,rst_n,cout,q);
	input cin,clk,rst_n;
	
	output reg cout;
	output [3:0]q;
	
	reg [3:0]cnt;  //定义计数器,reg类型才能进行计数
	
	always@(posedge clk, negedge rst_n) //进行计数器加
	if(rst_n == 1'b0)
		cnt <= 4'd0;
	else if(cin == 1'b1)begin
		if(cnt == 4'd9)
			cnt <= 4'd0;
		else 
			cnt <= cnt + 4'd1;
		end
	else
		cnt <= cnt;

	always@(posedge clk, negedge rst_n)//得到计数器输出
	if(rst_n == 1'b0)
		cout <= 1'b0;
	else if(cin == 1'b1 && cnt == 4'd9)
		cout <= 1'b1;
	else 
		cout <= 1'b0;
	assign q = cnt;
endmodule

模块二:四位计数器的测试

`timescale 1ns/1ps
`define clock_period 20

module BCD_counter_tb;
	
	reg cin;
	reg clk;
	reg rst_n;
	
	wire cout;
	wire [3:0]q;
	
	BCD_counter bcd_counter1(
	.cin(cin),
	.clk(clk),
	.rst_n(rst_n),
	.cout(cout),
	.q(q)
	);
	
	initial clk = 1'b1;
	always #(`clock_period/2) clk = ~ clk;
	
	initial begin
		rst_n = 1'b0;
		cin = 1'b0;
		#(`clock_period*100);
		rst_n = 1'b1;
		repeat(20)begin
			cin = 1'b0;
			#(`clock_period*5);
			cin = ~cin;
			#(`clock_period);
			cin = 1'b0;
		end
		#(`clock_period*20);
		$stop;
	end
	
endmodule

模块三:八位计数器

module BCD_counter_top(cin,cout,rst_n,q,clk);

	input cin;
	input rst_n;
	input clk;
	
	output cout; //此模块中cout没有进行加减,不能用reg
	output [7:0]q;
	
	wire cout1;

	BCD_counter counter1(
	.cin(cin),
	.clk(clk),
	.rst_n(rst_n),
	.cout(cout1),
	.q(q[3:0])
	);
	BCD_counter counter2(
	.cin(cout1),
	.clk(clk),
	.rst_n(rst_n),
	.cout(cout),
	.q(q[7:4])
	);
endmodule

模块四:

`timescale 1ns/1ps
`define clock_period 20
module BCD_counter_top_tb;
	
	reg cin,rst_n,clk;
	
	wire [7:0]q;
	wire cout;
	
	BCD_counter_top counter_top(
	.cin(cin),
	.cout(cout),
	.rst_n(rst_n),
	.q(q),
	.clk(clk)
	);
	
	initial clk = 1'b1;
	always #(`clock_period/2) clk =~clk;
	
	initial begin
		rst_n = 1'b0;
		cin = 1'b0;
		#(`clock_period*20);
		rst_n = ~rst_n;
		#(`clock_period*5);
		repeat(20)begin
			cin = 1'b0;
			#(`clock_period*5);
			cin = ~cin;
			#(`clock_period*5);
			cin = 1'b0;
		end
		#(`clock_period*20);
		$stop;
	end

endmodule

三、出现问题

第一个问题:
在这里插入图片描述
2、上述代码展示的是两个十进制的9进行级联,但是由于每个9是由4bit进行表示的,那么高4位的9实际上不是910,而是916=144,加上低四位的9,其实最大数是十进制的153(十六进制的99)。
当0000_1001 + 1 —> 0001_0000,对于十进制而言:由9变成了16,对于十六进制而言:由09变成了10.
十进制中间跳过了一些数,所以总的计数与十六进制是相同的,最大计数都是99。

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值