笔记重点:
多位计数器,如何控制进位信号,如何设置子模块的if语句的条件。
Build a 4-digit BCD (binary-coded decimal) counter. Each decimal digit is encoded using 4 bits: q[3:0] is the ones digit, q[7:4] is the tens digit, etc. For digits [3:1], also output an enable signal indicating when each of the upper three digits should be incremented.
module top_module (
input clk,
input reset, // Synchronous active-high reset
output [3:1] ena,
output [15:0] q);
wire c0,c1,c2;
assign ena[1]=c0;
assign ena[2]=c0&c1;
assign ena[3]=c0&c1&c2;//只有当前几位都为9时,下一位使能信号才能置为高电平;
myBCD inst0(clk,reset,1,c0,q[3:0]);
myBCD inst1(clk,reset,ena[1],c1,q[7:4]);
myBCD inst2(clk,reset,ena[2],c2,q[11:8]);
myBCD inst3(clk,reset,ena[3],,q[15:12]);
endmodule
module myBCD(
input clk,
input reset, // Synchronous active-high reset
input ena,
output c,
output [3:0] q);
always@(posedge clk)begin//对于第3个实例的计数器而言,ena==1‘b1意味着,前面两个计数器都为9了;
if(reset==1'b1)
q <= 4'b0;
else if((q==4'd9)&&(ena==1'b1))//意味着3位都为9,即999,此时,第3个计数器置0
q <= 4'b0;//也意味着第二个实例的计数器为99和第一个实例的计数器为9,此时前两个计数器也分别把自己置0。
else if(ena==1'b1)
q <= q + 1'b1;
else
q <= q;
end
assign c=(q==4'd9)?1:0;
endmodule
下面几句容易写错:
assign ena[1]=c0;
assign ena[2]=c0&c1;
assign ena[3]=c0&c1&c2;//使能信号
else if((q==4'd9)&&(ena==1'b1))//什么时候清零
q <= 4'b0;
关于BCD计数器,看了别人的写法,if语句这样写,逻辑更清晰
module decade_counter (
input clk,
input reset,
input ena,
output [3:0] q
);
always@(posedge clk) begin
if(reset)
q<=4'b0;
else if(ena) begin//在使能条件下,清零和计数
if(q==4'd9)
q<=4'd0;
else
q<=q+1'b1;
end
endmodule
这种多次实例化,并且实例之间互相级联的器件,有点类似加法器。但是一般的行波加法器,只用考虑上一位加法器的进位就可以,但对于计数器而言,使能信号却是与前几位都是有关的,必须前几位都为9时,本位的使能信号才能是高电平,这一点在写的时候,容易忽略。