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.
前言
两个输入,包括一个时钟clk,一个高电平有效的同步置位信号reset;两个输出,包括一个进位信号ena,一个输出信号q。
代码
module top_module (
input clk,
input reset,
output [3:1] ena,
output [15:0] q);
always@(posedge clk)begin
ena<={~reset&q[11:0]==12'h998,~reset&q[7:0]==8'h98,~reset&q[3:0]==4'h8};
if(reset) begin
q<=16'd0;
end
else begin
q[3:0]<=(q[3:0]<4'h9)?q[3:0]+1'b1:4'h0;
q[7:4]<=(!ena[1])?q[7:4]:(q[7:4]<4'h9)?q[7:4]+1'b1:4'h0;
q[11:8]<=(!ena[2])?q[11:8]:(q[11:8]<4'h9)?q[11:8]+1'b1:4'h0;
q[15:12]<=(!ena[3])?q[15:12]:(q[15:12]<4'h9)?q[15:12]+1'b1:4'h0;
end
end
endmodule
总结
16个bit的变量分为四段,从低到高每段分别计数,其中对于每段信号的状态而言,有三个可能,一是无进位信号保持计数值不变,二是有进位信号且计数值小于4’h9,因此计数值+1’b1,三是有进位信号但计数值达到4’h9,循环结束回到初始值4’h0;对于进位信号ena而言,需要注意两点,一是进位信号的判断值在循环结束的前一个状态即4’h8、8’h98和12’h998,因为这样才能在时钟触发的时候正常计数,二是进位需要在无效置位情况下发生,因此每一项都要与上~reset。