HDLBits Build a 4-digit decimal counter.
hdlbits 之千位计数器
提供HDLBits千位计数器的例程代码,帮助初学者熟练Verilog代码,规范代码风格。
题目
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.
module top_module (
input clk,
input reset, // Synchronous active-high reset
output [3:1] ena,
output [15:0] q);
reg [3:0] cnt10_1 ; //十进制个位计数器
reg [3:0] cnt10_2 ; //十进制十位位计数器
reg [3:0] cnt10_3 ; //十进制百位位计数器
reg [3:0] cnt10_4 ; //十进制千位位计数器
wire ena1 ; //个位数进位使能
wire ena2 ; //十位数进位使能
wire ena3 ; //百位数进位使能
//个位数十进制计数器
always @( posedge clk ) begin
if ( reset ) begin
cnt10_1 <= 4'd0 ;
end else begin
if ( cnt10_1 == 4'd9 ) begin
cnt10_1 <= 4'd0 ;
end else begin
cnt10_1 <= cnt10_1 + 1'b1 ;
end
end
end
assign ena1 = cnt10_1 == 4'd9 ? 1'b1 : 1'b0 ;
//十位数十进制计数器
always @( posedge clk ) begin
if ( reset ) begin
cnt10_2 <= 4'd0 ;
end else if ( ena1 ) begin
if ( cnt10_2 == 4'd9 ) begin
cnt10_2 <= 4'd0 ;
end else begin
cnt10_2 <= cnt10_2 + 1'b1 ;
end
end
end
assign ena2 = cnt10_1 == 4'd9 && cnt10_2 == 4'd9 ? 1'b1 : 1'b0 ;
//百位数十进制计数器
always @( posedge clk ) begin
if ( reset ) begin
cnt10_3 <= 4'd0 ;
end else if ( ena2 ) begin
if ( cnt10_3 == 4'd9 ) begin
cnt10_3 <= 4'd0 ;
end else begin
cnt10_3 <= cnt10_3 + 1'b1 ;
end
end
end
assign ena3 = cnt10_1 == 4'd9 && cnt10_2 == 4'd9 && cnt10_3 == 4'd9 ? 1'b1 : 1'b0 ;
//千位数十进制计数器
always @( posedge clk ) begin
if ( reset ) begin
cnt10_4 <= 4'd0 ;
end else if ( ena3 ) begin
if ( cnt10_4 == 4'd9 ) begin
cnt10_4 <= 4'd0 ;
end else begin
cnt10_4 <= cnt10_4 + 1'b1 ;
end
end
end
assign q[3:0] = cnt10_1 ;
assign q[7:4] = cnt10_2 ;
assign q[11:8] = cnt10_3 ;
assign q[15:12]= cnt10_4 ;
assign ena[1] = ena1 ;
assign ena[2] = ena2 ;
assign ena[3] = ena3 ;
endmodule