掌握VHDL Case-When语句:高效多路选择器设计
Case-When语句根据信号、变量或表达式引导VHDL程序沿多条路径之一执行。它为冗长的if-then-elsif-else链提供更清晰、可读的替代方案,尤其在处理多个离散值时。
许多编程语言用switch或case构造;在VHDL中,case构造是构建多路选择器和其他选择逻辑的主食。
本文属基础VHDL教程系列。
基本语法
case语句规范结构:
case <expression> is when <choice> => -- code for this branch when <choice> => -- code for this branch ... end case;
<expression>通常为信号或变量。虽然case可含多个when分支,但仿真时仅执行一个。
每个<choice>可以是:
- 单值,如
when "11" => - 范围,如
when 5 to 10 => - 值列表,如
when 1|3|5 => others关键字,匹配未显式列出的任何值。
实战练习:构建4选1多路选择器
下面完整VHDL代码演示用if-then-elsif和case两种方法实现4选1多路选择器。
library ieee; use ieee.std_logic_1164.all; use ieee.numeric_std.all; entity T14_CaseWhenTb is end entity; architecture sim of T14_CaseWhenTb is signal Sig1 : unsigned(7 downto 0) := x"AA"; signal Sig2 : unsigned(7 downto 0) := x"BB"; signal Sig3 : unsigned(7 downto 0) := x"CC"; signal Sig4 : unsigned(7 downto 0) := x"DD"; signal Sel : unsigned(1 downto 0) := (others => '0'); signal Output1 : unsigned(7 downto 0); signal Output2 : unsigned(7 downto 0); begin -- Stimuli for the selector signal process is begin wait for 10 ns; Sel <= Sel + 1; wait for 10 ns; Sel <= Sel + 1; wait for 10 ns; Sel <= Sel + 1; wait for 10 ns; Sel <= Sel + 1; wait for 10 ns; Sel <= "UU"; wait; end process; -- MUX using if-then-else process(Sel, Sig1, Sig2, Sig3, Sig4) is begin if Sel = "00" then Output1 <= Sig1; elsif Sel = "01" then Output1 <= Sig2; elsif Sel = "10" then Output1 <= Sig3; elsif Sel = "11" then Output1 <= Sig4; else Output1 <= (others => 'X'); end if; end process; -- Equivalent MUX using a case statement process(Sel, Sig1, Sig2, Sig3, Sig4) is begin case Sel is when "00" => Output2 <= Sig1; when "01" => Output2 <= Sig2; when "10" => Output2 <= Sig3; when "11" => Output2 <= Sig4; when others => Output2 <= (others => 'X'); end case; end process; end architecture;
在ModelSim运行仿真后,波形显示Output1和Output2行为完全相同。当选择器Sel取未定义值(如"UU")时,when others =>子句输出'X'指示未知状态。
控制台输出在50ns处包含以下警告,指示元值比较:
VSIM 2> run # ** Warning: NUMERIC_STD."=": metavalue detected, returning FALSE # Time: 50 ns Iteration: 1 Instance: /t14_casewhentb # ** Warning: NUMERIC_STD."=": metavalue detected, returning FALSE # Time: 50 ns Iteration: 1 Instance: /t14_casewhentb # ** Warning: NUMERIC_STD."=": metavalue detected, returning FALSE # Time: 50 ns Iteration: 1 Instance: /t14_casewhentb # ** Warning: NUMERIC_STD."=": metavalue detected, returning FALSE # Time: 50 ns Iteration: 1 Instance: /t14_casewhentb
关键要点
- 用
case语句替代长if-then-elsif链以提升可读性。 - 用
when others =>实现默认路径处理意外值。 - 多路选择器在VHDL中用
case构造表达最清晰。
进入下一教程学习更高级VHDL概念。
VHDL