verilog中的case语句

您所在的位置:网站首页 case语句的用法 verilog中的case语句

verilog中的case语句

2023-04-03 12:34| 来源: 网络整理| 查看: 265

case语句检查给定的表达式是否与列表中的其他表达式之一匹配,并相应地进行分支。它通常用于实现多路复用器。如果有许多条件需要检查,则if-else构造可能不合适,并且多分支的if-else会被综合成为优先级编码器而不是多路复用器。

语法

Verilog case语句以case关键字开始,以endcase关键字结束。匹配表达式将被精确地计算一次,并按照它们的编写顺序与备选方案列表进行比较,以及执行备选方案与给定表达式匹配的语句。一个由多个语句组成的块必须分组,并且位于begin和end之间。

// Here 'expression' should match one of the items (item 1,2,3,or 4) case() case_item1: case_item2: case_item3: case_item4: begin end default: endcase

如果没有一个case项与给定的表达式匹配,则default项中的语句被执行,default语句为可选的,并且一个case语句中只能有一个default语句。case语句是可以嵌套的。

如果没有任何项与表达式匹配并且没有给定default语句,则执行将退出case块而不执行任何操作。

例子

下面显示的设计模块有一个2位选择信号,用于将其他三个3位输入信号中的一个路由到称为out的输出信号上。case语句用于根据值sel将正确的输入分配给输出。由于是sel是2位信号,因此它可以具有0到3的组合。default语句有助于将输出设置为0如果sel是 3的话。

module my_mux (input [2:0] a, b, c, // Three 3-bit inputs input [1:0] sel, // 2-bit select signal to choose from a,b,c output reg [2:0] out); // output 3-bit signal // This always block is executed whenever a,b,c or sel changes in value always @(a,b,c,sel) begin case (sel) 2'b00: out = a; // If sel = 0, output is a; 2'b01: out = b; // If sel = 0, output is b; 2'b10: out = c; // If sel = 0, output is c; default: out = 0; // If sel is anything else, output is 0; endcase end endmodule

硬件电路图

对rtl代码进行综合以获得表示4对1多路复用器的硬件示意图

请注意,当sel为3时,输出为零,并且与其他值的指定输入相对应。

仿真结果

[0] a=0x1 b=0x2 c=0x3 sel=0x3 out=0x0 [10] a=0x2 b=0x4 c=0x5 sel=0x2 out=0x5 [20] a=0x1 b=0x2 c=0x3 sel=0x1 out=0x2 [30] a=0x1 b=0x2 c=0x3 sel=0x0 out=0x1 [40] a=0x5 b=0x2 c=0x0 sel=0x3 out=0x0

在case语句中,只有当表达式的每个位与包括、1和在内的备选项之一匹配时,比较才会成功。在上面显示的例子中,如果sel中的任何一个位是x或z,则将执行default语句,因为其他选项都不匹配。在这种情况下,输出将全部为零。

仿真结果

[0] a=0x1 b=0x2 c=0x3 sel=0xx out=0x0 [10] a=0x2 b=0x4 c=0x5 sel=0zx out=0x0 [20] a=0x1 b=0x2 c=0x3 sel=0xx out=0x0 [30] a=0x1 b=0x2 c=0x3 sel=0zx out=0x0 [40] a=0x5 b=0x2 c=0x3 sel=0xz out=0x0

如果设计中的case语句在设计的case 项中有x和z,结果会大不相同

module my_mux (input [2:0] a, b, c, // Three 3-bit inputs input [1:0] sel, // 2-bit select signal to choose from a,b,c output reg [2:0] out); // output 3-bit signal // This always block is executed whenever a,b,c or sel changes in value always @(a,b,c,sel) begin case (sel) 2'bxz: out = a; // If sel = 0, output is a; 2'bzx: out = b; // If sel = 0, output is b; 2'bxx: out = c; // If sel = 0, output is c; default: out = 0; // If sel is anything else, output is 0; endcase end endmodule

仿真结果

[0] a=0x1 b=0x2 c=0x3 sel=0xx out=0x3 [10] a=0x2 b=0x4 c=0x5 sel=0zx out=0x4 [20] a=0x1 b=0x2 c=0x3 sel=0xx out=0x3 [30] a=0x1 b=0x2 c=0x3 sel=0zx out=0x2 [40] a=0x5 b=0x2 c=0x3 sel=0xz out=0x5

case语句和if-else有两点不同:

if-else中的条件表达式更为通用,匹配的范围更广,然而在case块中,单条语句要匹配多项case。更为精准。当表达式中有X和Z值时,case语句将提供决定性的结果。


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3