SystemVerilog教程之Verilog Basics Part-II

Control Statements

Verilog中的if, else, repeat, while, for, case看起来完全像C语言!

但是Verilog是HDL,我们需要用这些关键字来描述硬件,这意味着如果不小心对待这些控制语句,我们的硬件可能会出现问题。

If-else

if-else语句根据不同的条件来决定是否执行哪一部分代码。

// begin and end act like curly braces in C/C++.
if (enable == 1'b1) begin
  data = 10; // Decimal assigned
  address = 16'hDEAD; // Hexadecimal
  wr_enable = 1'b1; // Binary
end 
else begin
  data = 32'b0;
  wr_enable = 1'b0;
  address = address + 1;
end

和C语言一样,我们可以在Verilog条件语句中使用任何运算符,甚至嵌套if else语句。

但是在对组合逻辑进行Verilog HDL建模时,我们需要防止生成Latch。

Case

当需要检查多个值的变量的情况下使用Case语句,而不是使用多个嵌套的if-else语句。

case(address)
0 : $display ("It is 11:40PM");
1 : $display ("I am feeling sleepy");
2 : $display ("Let me skip this tutorial");
default : $display ("Need to complete");
endcase

case语句以关键字case开头,以关键字endcase结尾。

在这两个关键字中列出了这些case条件和相应的希望执行的语句。

和if-else一样,建议在case语句中添加default case语句,因为如果组合逻辑Verilog HDL建模时,if-else和case-endcase语句中没有涵盖所有的情况(在If中没有’else’或者在Case中没有’default’),那么综合工具可能会推断出Latch。

While

如果判断的条件返回true,则while语句将重复执行语句块中的代码。While循环通常不用于实际的硬件建模,但是它们用于测试平台(验证)。与其他语句块一样,它们由begin和end分隔。

while (free_time) begin
$display ("Continue with webpage development");
end

只要设置free_time变量为true,就会一直执行begin和end中的代码。即打印“Continue with webpage development”。

module counter (clk,rst,enable,count);
input clk, rst, enable;
output [3:0] count;
reg [3:0] count;
         
always @ (posedge clk or posedge rst)
if (rst) begin
count <= 0;
end else begin : COUNT
while (enable) begin
count <= count + 1;
disable COUNT;
end
end
endmodule

上面的例子使用了Verilog的大多数结构。我们可以注意到其中有一个名为always的语句,这也说明了Verilog的一个关键特性:

大多数软件语言都是按顺序执行的,而Verilog程序通常会并行执行许多语句块。

在上面的示例中,当rst或clk达到上升沿时,always语句块将会一直运行。在同一个verilog模块中,可以同时执行多个always语句块。

For loop

Verilog中的For循环与C或C ++中的循环几乎相同。唯一的区别是Verilog不支持++和 – 运算符,我们必须写出完整的i = i + 1。

for (i = 0; i < 16; i = i +1) begin
$display ("Current value of i is %d", i);
end

上述代码将按顺序打印0到15之间的数字。

使用for循环进行寄存器传输级(RTL)建模时,我们需要确保我们的代码在硬件上可以实现,既保证我们的循环次数是有限且确定的。

Repeat

Repeat和上面的for循环类似。我们在Repeat中直接明确运行了多少次。

repeat (16) begin
$display ("Current value of i is %d", i);
i = i + 1;
end

Variable Assignment

在数字IC中,有两种类型的元素,组合元素和时序元素。

我们如何用Verilog建模这两 中元素呢?Verilog提供了两种方法来建模组合逻辑,提供了一种方法来建模时序逻辑。

使用assign和always语句对组合逻辑建模。

使用always语句对时序逻辑进行建模。

另外,在测试平台中还可以使用 Initial 语句对变量进行赋值。

Initial Blocks

顾名思义,Initial语句块仅在仿真开始时执行一次,用于初始化变量。

initial begin
clk = 0;
reset = 0;
req_0 = 0;
req_1 = 0;
end

在上面的例子中,在仿真开始时(即当t= 0时),begin和end块内的所有变量都被初始化为零。

发布了32 篇原创文章 · 获赞 2 · 访问量 1511

猜你喜欢

转载自blog.csdn.net/qq_36248682/article/details/105350645