----------------------------------------------------------------------------------
-- Company: 
-- Engineer: 
-- 
-- Create Date: 05/30/2018 12:50:15 PM
-- Design Name: 
-- Module Name: bpm - Behavioral
-- Project Name: 
-- Target Devices: 
-- Tool Versions: 
-- Description: 
-- 
-- Dependencies: 
-- 
-- Revision:
-- Revision 0.01 - File Created
-- Additional Comments:
-- 
----------------------------------------------------------------------------------


library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;
USE ieee.numeric_std.ALL;

-- Uncomment the following library declaration if using
-- arithmetic functions with Signed or Unsigned values
--use IEEE.NUMERIC_STD.ALL;

-- Uncomment the following library declaration if instantiating
-- any Xilinx leaf cells in this code.
--library UNISIM;
--use UNISIM.VComponents.all;

entity bpm is
    Port ( btnu : in STD_LOGIC;
           btnd : in STD_LOGIC;
           clk : in STD_LOGIC;
           countOut : out std_logic_vector(7 downto 0));
end bpm;

architecture Behavioral of bpm is
component clk_div_bpm is
    Port(clk : in std_logic;
         sclk : out std_logic);
end component;

signal sclk : std_logic;
signal count : std_logic_vector(7 downto 0) := "00111100";

begin
    clkdiv : clk_div_bpm
    Port map(clk => clk,
             sclk => sclk);
             

    process(sclk) begin
    if (rising_edge(sclk)) then
        if (btnu = '1' and count < "11001000") then
            count <= count + "101";
        elsif (btnd = '1' and count > "101") then
            count <= count - "101";
        end if;
        countOut <= count;
    end if;
    end process;
end Behavioral;

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
USE ieee.numeric_std.ALL;
-----------------------------------------------------------------------
-- Module to divide the clock 
-----------------------------------------------------------------------
entity clk_div_bpm is
    Port (  clk : in std_logic;
           sclk : out std_logic);
end clk_div_bpm;

architecture my_clk_div of clk_div_bpm is
   constant max_count : integer := 20000000;  
   signal tmp_clk : std_logic := '0'; 
begin
   my_div: process (clk,tmp_clk)              
      variable div_cnt : integer := 0;   
   begin
      if (rising_edge(clk)) then   
         if (div_cnt = MAX_COUNT) then 
            tmp_clk <= not tmp_clk; 
            div_cnt := 0; 
         else
            div_cnt := div_cnt + 1; 
         end if; 
      end if; 
      sclk <= tmp_clk; 
   end process my_div; 
end my_clk_div;
