VHDL - Incrementing Register Value on Push Button Event

John Roberts picture John Roberts · Jan 24, 2013 · Viewed 15.3k times · Source

I am very new to VHDL and am trying to figure out how to do something fairly basic on an Altera Cyclone II. The FPGA has four push buttons - two of them need to be programmed to increase and decrease the selected register (0-F), and the two need to be programmed to increase and decrease the value (from 00 to FF) that will be in that register. Here is what I have so far:

entity raminfr is
    port (
        clk : in std_logic;
        we : in std_logic;
        a : in unsigned(3 downto 0);
        di : in unsigned(7 downto 0);
        do : out unsigned(7 downto 0)
    );
end raminfr;

architecture rtl of raminfr is
type ram_type is array (0 to 15) of unsigned(7 downto 0);
signal RAM : ram_type;
signal read_a : unsigned(3 downto 0);

begin

process (clk)
begin
    if rising_edge(clk) then
        if we = '1' then
            RAM(to_integer(a)) <= di;
        end if;
        read_a <= a;
    end if;
end process;

do <= RAM(to_integer(read_a));

end rtl;

Could someone provide some basic sample code as to how to go about programming the push buttons?

Answer

sonicwave picture sonicwave · Jan 24, 2013

You can do a simple edge-detection in a clocked process, and then just react to rising edges. For instance:

signal lastButtonState    : std_logic := '0';

process(clk)
begin
  if(rising_edge(clk)) then
    if(buttonState = '1' and lastButtonState = '0') then      --assuming active-high
      --Rising edge - do some work...
    end if;
    lastButtonState <= buttonState;
  end if;
end process;

To get everything working correctly, you'll need to make sure that your pushbuttons are debounced in some way though. Many development boards have a hardware RC circuit for this, but otherwise you'll need to do it in your code (which isn't that hard though - there should be plenty examples of this around on the net).