题目
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.
You may want to instantiate or modify some one-digit decade counters.
构建一个4位BCD(二进制编码的十进制)计数器。每个十进制数字用4位编码:q[3:0]是个位数,q[7:4]是十位,等等。对于数字[3:1],还输出一个enable信号,指示何时应增加前三位数字中的每一位。
您可能希望实例化或修改一些十位计数器。
十位计数器
module counters (
input clk,
input ena,
input reset, // Synchronous active-high reset
output reg [3:0] q
);
always @(posedge clk) begin
if (reset == 1) begin
q <= 4'b0;
end else if (ena == 1'b1) begin
if (q == 4'd9) begin
q <= 4'b0;
end else begin
q <= q + 1'b1;
end
end
end
endmodule
将计数到9清零写进使能为一里面。
解法一:
module top_module (
input clk,
input reset, // Synchronous active-high reset
output reg [3:1] ena,
output reg [15:0] q
);
wire [3:0] q1, q2, q3, q4;
wire ena1;
counters instance1(clk, ena1, reset, q1);
counters instance2(clk, ena[1], reset, q2);
counters instance3(clk, ena[2], reset, q3);
counters instance4(clk, ena[3], reset, q4);
assign ena1=1;
always @(posedge clk) begin
if (reset == 1) begin
q <= 16'b0;
end
else if (q4 == 4'd8 && q1 == 4'd8 && q2 == 4'd8 && q3 == 4'd8) begin
q <= 16'b0;
end
else
if (q1 == 4'd8 && q2 == 4'd8 && q3 == 4'd8) begin
ena <= 3'b111;
end
else if (q1 == 4'd8 && q2 == 4'd8) begin
ena <= 3'b011;
end
else if (q1 == 4'd8) begin
ena <= 3'b001;
end
else begin
ena<=3'b000;
end
q <= {q4, q3, q2, q1};
end
endmodule
注意点1:always块里面是顺序执行,else if 语句中应按照千位、百位、十位、个位的顺序。
注意点2;因为始终具有延后性,所以在if条件中,当本位计数到8时,激活下一位计数器使能端,在下个时钟信号来临时下一位计数器+1。
解法二:组合逻辑电路
module top_module (
input clk,
input reset, // Synchronous active-high reset
output reg [3:1] ena,
output reg [15:0] q
);
wire [3:0] q1, q2, q3, q4;
wire ena1;
counters instance1(clk, ena1, reset, q1);
counters instance2(clk, ena[1], reset, q2);
counters instance3(clk, ena[2], reset, q3);
counters instance4(clk, ena[3], reset, q4);
assign ena1=1;
assign ena[1]=(q1==4'd9);
assign ena[2]=(q1==4'd9 && q2==4'd9);
assign ena[3]=(q1==4'd9 && q2==4'd9 && q3==4'd9);
assign q={q4,q3,q2,q1};
endmodule