Programmable Devices
CPLDs, FPGAs, SoC FPGAs, Configuration, and Transceivers

Counters

Altera_Forum
Honored Contributor II
1,254 Views

Hello, 

 

I need help at writing counters in hdl. 

The Altera Coding Guidelines suggest to code "out <= out + (count_up ? 1 : -1);" 

instead of "out <= count_up ? out + 1 : out - 1;" 

1.) How do I write the code, if I need to increment in certain states of a fsm? 

 

2.) How do I write the code if I need to load certain values in certain states? 

 

At the moment I simply write it in this way: 

signal cnt : integer range 0 to 1024;  

(IEEE 1076.6 says: "INTEGER range 9 to 10” should be synthesized using an equivalent vector length of 4 bits") 

1.  

case state is 

when... => 

cnt <= cnt + 1;  

when... => 

cnt <= cnt + 1; 

when... => 

-- cnt <= cnt + 1; 

end case; 

 

Is this style better (is it similar to the altera suggestion)? 

case state is 

when... => 

cnt_tmp <= ONE;  

when... => 

cnt_tmp <= ONE;  

when... => 

cnt_tmp <= ZERO; 

end case; 

cnt <= cnt + cnt_tmp; 

 

Will the RTL viewer instantiate a counter primitive if I write correct code? 

 

TIA 

Axel
0 Kudos
1 Reply
Altera_Forum
Honored Contributor II
371 Views

Scenario# 1 is "asking" for three adders. The synthesis tools will most likely recognize that they are the same and merge them. Scenario# 2 is "asking" for one adder and a multiplexer driving cnt_tmp. The multiplexer will be (probably 32 bits) wide at first, then collapse rapidly due to all of the constant inputs. # 2 is better than# 1 because it more closely resembles the best hardware implementation. There is less chance for something to go wrong. 

 

An even better implemenation is to build a standalone counter, with 1 bit increment and decrement control signals. Use the state machine to drive these control lines. This gives the tools absolutely no chance to make a mistake.
0 Kudos
Reply