1. 基础门电路实现
任务目标
使用VHDL分别实现与门(AND)、或门(OR)、非门(NOT)三种基本逻辑门电路,并通过VHDL测试平台(testbench)对三个逻辑门进行功能仿真验证,确保真值表输出正确。
环境依赖
本案例需要VHDL仿真工具,推荐使用GHDL(开源)或ModelSim/Questa。以下命令以GHDL为例。
核心代码
将三个逻辑门实体合并写入同一文件 basic_gates.vhdl,测试平台写入 tb_basic_gates.vhdl:
-- basic_gates.vhdl
library ieee;
use ieee.std_logic_1164.all;
-- 与门实体
entity and_gate is
port (a, b : in std_logic;
y : out std_logic);
end entity;
architecture behavior of and_gate is
begin
y <= a and b;
end architecture;
-- 或门实体
entity or_gate is
port (a, b : in std_logic;
y : out std_logic);
end entity;
architecture behavior of or_gate is
begin
y <= a or b;
end architecture;
-- 非门实体
entity not_gate is
port (a : in std_logic;
y : out std_logic);
end entity;
architecture behavior of not_gate is
begin
y <= not a;
end architecture;
-- tb_basic_gates.vhdl
library ieee;
use ieee.std_logic_1164.all;
entity tb_basic_gates is
end entity;
architecture sim of tb_basic_gates is
signal a, b : std_logic;
signal y_and, y_or : std_logic;
signal y_not : std_logic;
begin
-- 实例化被测单元
uut_and : entity work.and_gate port map (a=>a, b=>b, y=>y_and);
uut_or : entity work.or_gate port map (a=>a, b=>b, y=>y_or);
uut_not : entity work.not_gate port map (a=>a, y=>y_not);
-- 激励生成与自动检查
process
begin
-- 遍历所有输入组合
for i in 0 to 3 loop
case i is
when 0 => a <= '0'; b <= '0';
when 1 => a <= '0'; b <= '1';
when 2 => a <= '1'; b <= '0';
when 3 => a <= '1'; b <= '1';
end case;
wait for 10 ns;
-- 断言检查(与门)
assert y_and = (a and b)
report "AND gate mismatch" severity error;
-- 断言检查(或门)
assert y_or = (a or b)
report "OR gate mismatch" severity error;
-- 断言检查(非门,仅当a变化时有效)
assert y_not = (not a)
report "NOT gate mismatch" severity error;
end loop;
report "All tests passed!" severity note;
wait; -- 结束仿真
end process;
end architecture;
运行与验证
在终端中依次执行以下命令(GHDL):
ghdl -a basic_gates.vhdl
ghdl -a tb_basic_gates.vhdl
ghdl -e tb_basic_gates
ghdl -r tb_basic_gates --vcd=result.vcd
通过条件:仿真运行结束后,终端输出 All tests passed! 且无 error 报告。若使用ModelSim,编译两个文件后运行仿真,在Transcript窗口观察同样信息。
也可用GTKWave打开 result.vcd 查看波形,手动核对:与门仅在 a=1, b=1 时输出1;或门在任一输入为1时输出1;非门输出与输入相反。
常见问题
- 编译顺序:必须先编译实体文件,再编译测试平台,因为测试平台引用了实体。
- 仿真不结束:确认测试平台中
wait;语句存在,否则进程会无限循环。 - 端口映射错误:检查
port map中信号名与实体端口定义一致。