Wednesday, July 14, 2010

VHDL examples

============
single port ram
============

library ieee;
use ieee.std_logic_1164.all;

entity single_port_ram is
port
(
data : in std_logic_vector(7 downto 0);
addr : in natural range 0 to 63;
we : in std_logic := '1';
clk : in std_logic;
q : out std_logic_vector(7 downto 0)
);

end entity;

architecture rtl of single_port_ram is

-- Build a 2-D array type for the RAM
subtype word_t is std_logic_vector(7 downto 0);
type memory_t is array(63 downto 0) of word_t;

-- Declare the RAM signal.
signal ram : memory_t;

-- Register to hold the address
signal addr_reg : natural range 0 to 63;

begin

process(clk)
begin
if(rising_edge(clk)) then
if(we = '1') then
ram(addr) <= data;
end if;

-- Register the address for reading
addr_reg <= addr;
end if;

end process;

q <= ram(addr_reg);

end rtl;

=====================
FSM : moore -> BCD counter
=====================

library IEEE;
use IEEE.std_logic_1164.all;
use IEEE.std_logic_arith.all;

entity bcd is
port (
clk : in std_logic;
rst : in std_logic;
count: out std_logic_vector);
end bcd;

architecture beh_bcd of bcd is

-- enumeration of states
type state is (zero,one,two,three,four,five,six,seven,eight,nine);
signal pr_state,nxt_state: state;

--coding starts here
begin

-- sequential part
process(clk,rst)
begin
if(rst = '1') then
pr_state <= zero;
elsif rising_edge(clk) then
pr_state <= nxt_state;
end if;
end process;

-- combinational part
process(pr_state)
begin
case pr_state is
when zero =>
count <= "0000";
nxt_state <= one;
when one =>
count <= "0001";
nxt_state <= two;
when two =>
count <= "0010";
nxt_state <= three;
when three =>
count <= "0011";
nxt_state <= four;
when four =>
count <= "0100";
nxt_state <= five;
when five =>
count <= "0101";
nxt_state <= six;
when six =>
count <= "0110";
nxt_state <= seven;
when seven =>
count <= "0111";
nxt_state <= eight;
when eight =>
count <= "1000";
nxt_state <= nine;
when nine =>
count <= "1001";
nxt_state <= zero;
end case;

end process;

end beh_bcd;

============
2-bit grey code:
============

library IEEE;
use IEEE.Std_logic_1164.all;



entity grey is
port(
x: in std_logic_vector(1 downto 0);
y: out std_logic_vector(1 downto 0)
);
end entity;

architecture beh of grey is
begin
y(1) <= x(1);
y(0) <= x(0) xor x(1);
end beh;

Constraint to have N elements distributed in M bins

Code to distribute N elements into M bins, you add unique keyword to have each bin will have unique number of elements. class test; param...