Altera_Forum
Honored Contributor
8 years agoVerilog down counter checking for carry
Hi,
this is so basic I'm embarrassed to ask but half an hour googling did not find the answer so here goes. Conventional wisdom says down counters are most efficient way to implement for example delays and what not. Be that as it may, this involves checking when the counter underflows and then re-loading the counter. My question is that how to do that in Verilog? I can of course check the MSB of the counter but that implies that I need to 'know' what is the counter size in bits when I check it. What I mean is that not only do I have to write down the size of the counter where I define it but also in where I do the checking and that is ugly to me. I principle if the value is signed I can check for the counter being <0 or >= 0 but the question is if the synthesiser is smart enough to implement this check on the MSB? A further question is if there is a way to avoid the -1 value of the counter from appearing in the 'output'. What I mean is that if I code it like this: reg signed [3:0] counter = 4'sd16;
always @(posedge sys_clk) begin
counter <= counter + $signed({1'd0, 1'd1});
if ((counter < $signed({1'd0, 1'd0}))) begin
counter <= (counter - $signed({1'd0, 1'd1}));
end else begin
counter <= 3'd7;
the counter will have the value of -1 for one clock cycle so re-loading the counter with the value 7 will produce not 7 not 8 but 9 states, which is ugly to me. Is there a way to avoid that state without increasing resource usage? wbr Kusti (Never mind the $signed, that code is machine generated)