library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.std_logic_arith.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;


entity myfirst_niosii is port (
		clk: in std_logic;
		rst: in std_logic;
		pio_led: out std_logic_vector(31 downto 0);
		toggle_button: in std_logic;
		toggle_led: out std_logic
	);
end myfirst_niosii;

architecture behav of myfirst_niosii is
    component nios2_uc is
        port (
            clk_clk                 : in  std_logic                     := 'X'; -- clk
            pio_led_ext_conn_export : out std_logic_vector(31 downto 0);        -- export
            reset_reset_n           : in  std_logic                     := 'X'  -- reset_n
        );
    end component nios2_uc;
	 
	 signal toggle_led_s: std_logic := '0';
	 signal state: std_logic := '0';
	 signal counter: integer range 0 to 2**15-1 := 0;

begin
	 
	     u0 : component nios2_uc
        port map (
            clk_clk                 => clk,                 --              clk.clk
            pio_led_ext_conn_export => pio_led, -- pio_led_ext_conn.export
            reset_reset_n           => rst            --            reset.reset_n
        );
		  
		  
		  toggle: process(clk, rst)

				
		  begin
				if rst = '0' then
					counter <= 0;
					state <= '0';
				elsif rising_edge(clk) then
					if counter = 2**15-1 then
						counter <= 0;
						if toggle_button = not state then
							state <= toggle_button;
							if toggle_button = '1' then
								toggle_led_s <= not toggle_led_s;
							end if;
						end if;
					else
						counter <= counter + 1;
					end if;
				end if;
		  end process;
		  
		  toggle_led <= toggle_led_s;
end behav;

