library IEEE ;
use IEEE.STD_LOGIC_1164.ALL ;
use IEEE.STD_LOGIC_ARITH.ALL ;
use IEEE.STD_LOGIC_UNSIGNED.ALL ;
entity posenc is
    Port (   nCS : in std_logic ;
          nRD : in std_logic ;
          In0 : in std_logic ;
          In1 : in std_logic ;
          Clk : in std_logic ;
          Dout : out std_logic_vector ( 7 downto 0 ) ) ;
end posenc ;
architecture beh of posenc is
    signal counter : std_logic_vector ( 3 downto 0 ) := "0000" ;
    signal out_latch : std_logic_vector ( 3 downto 0 ) := "0000" ;
    signal in0_sync, in1_sync, old_in0_sync, old_in1_sync : std_logic := '0' ;
    signal changed : std_logic ;
    signal direction : std_logic ;
    signal reading : std_logic ;
begin
    -- control signal for reading
    reading <= '1' when ( nCS='0' and nRD='0' ) else '0' ;
    -- remember old input levels and synchronize inputs
    sync : process( Clk )
    begin
        if ( Clk'event and Clk='1' ) then
            old_in0_sync <= in0_sync ;
            old_in1_sync <= in1_sync ;
            in0_sync <= In0 ;
            in1_sync <= In1 ;
        end if ;
    end process sync ;
    -- change detection
    changed <= '1' when ( ( in0_sync /= old_in0_sync ) or
                        ( in1_sync /= old_in1_sync ) ) else '0' ;
    -- determine the direction
    direction <= in0_sync xor old_in1_sync ;
    -- count up or down. async clear when reading
    count : process( Clk, reading )
    begin
        if ( reading='1' ) then
            counter <= "0000" ;
        elsif ( Clk'event and Clk='1' and changed='1' ) then
            if direction='1' then
                counter <= counter + 1 ;
            else
                counter <= counter - 1 ;
            end if ;
        end if ;
    end process count ;
    -- latch counter value when reading
    latch : process( reading )
    begin
        if ( reading'event and reading='1' ) then
            out_latch <= counter ;
        end if ;
    end process latch ;
    Dout( 3 downto 0 ) <= out_latch ;
    Dout( 4 ) <= out_latch( 3 ) ;
    Dout( 5 ) <= out_latch( 3 ) ;
    Dout( 6 ) <= out_latch( 3 ) ;
    Dout( 7 ) <= out_latch( 3 ) ;
end beh ;
HTML Source generated with the hdl2html perl script from
Millogic