Search code examples
vhdlcounter

VHDL how to assign a input vector value to an integer signal


I'm new to the VHDL, I'm trying to make a counter which receives the value from the input and count to the given value then output a 1;

for example, the input is a 4-bit vector "1011"

I tried to set an integer signal a = input = 1011 = 11 in decimal, then if b = a = 11 output 1, otherwise output 0 and b=b+1

I know that I can do it by a series of if statements, but I'm wondering if there is any better way like assigning the value directly from a input vector to a integer signal? thanks for anyone who can help!


Solution

  • This is untested, but it's the general architecture it sounds like you're after. It's not bad practice to use if statements in VHDL; they're necessary to define sequential (not combinatorial) logic; you just need to be judicious in their use.

    library IEEE;
    use IEEE.STD_LOGIC_1164.ALL;
    use IEEE.NUMERIC_STD.ALL;
    
    entity Counter is port (
         enable:  in std_logic; -- Used to increment the counter. (Active high.)
         value:   in std_logic_vector(0 to 3);
         clk:     in std_logic; -- Used to clock the counter.
         reset:   in std_logic; -- Reset the counter. (Active high.)
         output:  out std_logic -- Generates a logic high once the count has been reached.
    );
    end Counter;
    
    architecture Behavioral of Counter is
    
        signal count: unsigned(0 to 3);
    
    begin
        process(clk,reset)
        begin
            -- If reset goes high, reset the count.
            if reset='1' then
                count <= "0000";                -- Reset the counter.
                output <= '0';                  -- Set the output low.
            elsif(clk'event and clk='1') then  -- If not reset, and the rising edge of the input clock...
                if enable='1' then             -- If the counter is enabled...
                    if count=unsigned(value) then        -- If the count reached the input value...
                        output <= '1';          -- Set the output high.
                    else
                        count <= count + 1;    -- Increment the counter.
                    end if;
                end if;
            end if;
        end process;
    end Behavioral;