Feedback

VHDL: Behavioral Counter

This example implements a behavioral counter with load, clear, and up/down features. It has not been optimized for a particular device architecture, so performance may vary. Altera recommends using the lpm_counter function to implement a counter (see VHDL: Down Counter). This example is provided to show counter implementation that does not require the LPM.

For more information on using this example in your project, go to:


counters.vhd

ENTITY counters IS
    PORT(   
        d       : IN    INTEGER RANGE 0 TO 255;
        clk     : IN    BIT;
        clear   : IN    BIT;
        load    : IN    BIT;
        up_down : IN    BIT;
        qd      : OUT   INTEGER RANGE 0 TO 255);
END counters;

ARCHITECTURE a OF counters IS
BEGIN
    -- An up/down counter
    PROCESS (clk)
         VARIABLE    cnt       : INTEGER RANGE 0 TO 255;
         VARIABLE    direction : INTEGER;
    BEGIN
        IF (up_down = '1') THEN  --Generate up/down counter
            direction := 1;
            ELSE
                direction := -1;
        END IF;
            IF (clk'EVENT AND clk = '1') THEN
                IF (load = '1') THEN         --Generate loadable 
                    cnt := d;                --counter. Take these 
                    ELSE                     --lines out to increase performance.
                    cnt := cnt + direction; 
                 END IF;
                --The following lines will produce a synchronous 
                --clear on the counter
                  IF (clear = '0') THEN     
                     cnt := 0;
                  END IF;
             END IF;
    qd <= cnt;   --Generate outputs
    END PROCESS;
END a;

Design Examples Disclaimer

These design examples may only be used within Altera Corporation devices and remain the property of Altera. They are being provided on an “as-is” basis and as an accommodation; therefore, all warranties, representations, or guarantees of any kind (whether express, implied, or statutory) including, without limitation, warranties of merchantability, non-infringement, or fitness for a particular purpose, are specifically disclaimed. Altera expressly does not recommend, suggest, or require that these examples be used in combination with any other product not provided by Altera.