亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> VHDL

掌握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>可以是:

实战练习:构建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

关键要点

进入下一教程学习更高级VHDL概念。

VHDL

  1. 刀具磨床实战技法指南:从入门到精通
  2. 钼如何塑造现代工业:用途、优势与供应动态
  3. VHDL过程示例:标准逻辑向量自增
  4. VHDL 字符串列表创建:最佳实践与示例
  5. 优雅结束 VHDL 测试平台仿真
  6. VHDL 实现 PWM 控制器:设计、仿真与 FPGA 演示
  7. VHDL 生成随机数:从均匀分布到 OSVVM
  8. 利用进程内过程简化VHDL状态机设计
  9. 使用VHDL不纯函数提升FSM可读性与可维护性
  10. 掌握VHDL函数:高效设计实战指南
  11. 用VHDL设计有限状态机:红绿灯实战范例
  12. 在VHDL中使用过程:用可复用代码简化设计