vhdl(以格雷码和二进制码互相转换为例)
完整代码:
LIBRARY IEEE;
USE IEEE.STD_LOGIC_1164.ALL;
USE IEEE.STD_LOGIC_UNSIGNED.ALL;
USE IEEE.STD_LOGIC_ARITH.ALL;
ENTITY B2G IS
GENERIC(n:INTEGER :=4);
PORT(
clk : IN STD_LOGIC;
input : IN STD_LOGIC_VECTOR(n-1 DOWNTO 0);
output : OUT STD_LOGIC_VECTOR(n-1 DOWNTO 0)
USE IEEE.STD_LOGIC_1164.ALL;
USE IEEE.STD_LOGIC_UNSIGNED.ALL;
USE IEEE.STD_LOGIC_ARITH.ALL;
ENTITY B2G IS
GENERIC(n:INTEGER :=4);
PORT(
clk : IN STD_LOGIC;
input : IN STD_LOGIC_VECTOR(n-1 DOWNTO 0);
output : OUT STD_LOGIC_VECTOR(n-1 DOWNTO 0)
);
END B2G;
ARCHITECTURE behave OF B2G IS
SIGNAL temp_input : STD_LOGIC_VECTOR(n-1 DOWNTO 0);
SIGNAL temp_output : STD_LOGIC_VECTOR(n-1 DOWNTO 0);
BEGIN
PROCESS(clk,input)
BEGIN
temp_input <= input;
temp_output(n-1) <= temp_input(n-1);
IF clk = '1'THEN
FOR i IN n-2 DOWNTO 0 LOOP
temp_output(i) <= temp_input(i+1) xor temp_input(i);
END LOOP;
ELSE
temp_output(n-2) <= temp_input(n-1) xor temp_input(n-2);
temp_output(n-3) <= temp_input(n-1) xor temp_input(n-2) xor temp_input(n-3);
temp_output(n-4) <= temp_input(n-1) xor temp_input(n-2) xor temp_input(n-3) xor temp_input(n-4);
END IF;
output <= temp_output;
END B2G;
ARCHITECTURE behave OF B2G IS
SIGNAL temp_input : STD_LOGIC_VECTOR(n-1 DOWNTO 0);
SIGNAL temp_output : STD_LOGIC_VECTOR(n-1 DOWNTO 0);
BEGIN
PROCESS(clk,input)
BEGIN
temp_input <= input;
temp_output(n-1) <= temp_input(n-1);
IF clk = '1'THEN
FOR i IN n-2 DOWNTO 0 LOOP
temp_output(i) <= temp_input(i+1) xor temp_input(i);
END LOOP;
ELSE
temp_output(n-2) <= temp_input(n-1) xor temp_input(n-2);
temp_output(n-3) <= temp_input(n-1) xor temp_input(n-2) xor temp_input(n-3);
temp_output(n-4) <= temp_input(n-1) xor temp_input(n-2) xor temp_input(n-3) xor temp_input(n-4);
END IF;
output <= temp_output;
END PROCESS;
END behave;
END behave;
代码解读:
首先vhdl代码的结构有三部分,分别为库使用说明,实体说明,构造体。
库使用说明的功能是包含后面代码所使用的库。格式简单。
实体说明的作用是声明使用的端口,即输入与输出端口,需要说明端口名,方向,数据类型。在说明端口前可以先定义参数,即变量或者信号,说明它的数据类型以及可以给他赋初值。
最后一个部分是构造体,用来说明电路的功能。
构造体中用进程语句结构进行说明。其中的敏感量表用来表示变化的参数,即该参数的值发生变化时就执行进程语句。