📜  Verilog控制块

📅  最后修改于: 2021-01-11 14:48:40             🧑  作者: Mango

Verilog控制块

没有条件语句和其他控制逻辑流的方法,就无法实现硬件行为。 Verilog具有一组机制和控制流模块。

如果-否则-如果

此条件语句用于决定是否执行某些语句。它与C语言中的if-else-if语句非常相似。如果表达式的计算结果为true,则将执行第一条语句。

如果表达式的计算结果为false,并且其他部分存在,则将执行else部分。

句法

以下是if-else-if条件语句的最简化语法:

// if statement without else part
if (expression)
    [statement]

// if statement with an else part
if (expression)
    [statement]
else
    [statement]

// if else for multiple statements should be
// enclosed within "begin" and "end"

if (expression) begin
    [multiple statements]
end else begin
    [multiple statements]
end

// if-else-if statement
if (expression)
    [statement]
else if (expression)
    [statement]
 
else
    [statement]

if-else的else部分是可选的,并且可能引起混淆。为避免这种混淆,如果缺少其他元素,则始终将其他元素与上一个元素关联起来会更容易。另一种方法是将语句括在begin-end块内。最后的其他部分处理其他条件都不满足的上述或默认情况。

循环提供了一种在块中执行一次或多次的单个或多个语句的方法。在Verilog中,有四种不同类型的循环语句。

1.永远循环

该循环将连续执行块中的语句。

句法

Forever
      [statement]
forever begin
      [multiple statements]
end

module my_block;
initial begin
    forever begin
        $display ("This will be printed forever, simulation can hang ...");
    end
end
endmodule

执行完上面的示例后,它将产生以下数据。

ncsim> run
This will be printed forever, simulation can hang
This will be printed forever, simulation can hang
...
...
This will be printed forever, simulation can hang
This will be printed forever, simulation can hang 
This will be printed forever, simulation can hang 
This will be printed forever, simulation can hang 
…
…
Result reached a maximum of 5000 lines.
Killing process.

2.重复循环

这将执行固定次数的语句。如果表达式的计算结果为X或Z,它将被视为零且不执行。

句法

repeat ([num_of_times]) begin
    [statements]
end
repeat ([num_of_times]) @ ([some_event]) begin
    [statements]
end

module my_block;
    initial begin
        repeat(5) begin
            $display("This is a new iteration ...");
        end
    end
endmodule

上面的代码生成以下结果。

ncsim> run
This is a new iteration
This is a new iteration 
This is a new iteration 
This is a new iteration 
This is a new iteration 

ncsim: *W,RNQUIE: Simulation is complete.

3. ile循环

只要表达式为真,这将执行语句,一旦条件为假,将退出。如果从一开始条件为假,则将根本不执行语句。

句法

while (expression) begin
    [statements]
end

module my_block;
      integer i = 5;
    initial begin
      while (i > 0) begin
        $display ("Iteration#%0d", i);
        i = i - 1;
      end
    end
endmodule

运行上面的代码,我们将获得以下输出。

ncsim> run
Iteration#5
Iteration#4
Iteration#3
Iteration#2
Iteration#1
ncsim: *W,RNQUIE: Simulation is complete.

4.循环

For循环使用三步过程控制语句:

  • 初始化循环计数器变量。
  • 计算表达式,通常涉及循环计数器变量。
  • 递增循环计数器变量,以使表达式在以后的时间变为假,并退出循环。

句法

for ( initial_assignment; condition; increment_variable) begin
    [statements]
end

module my_block;
      integer i = 5;
    initial begin
      for (i = 0; i < 5; i = i + 1) begin
        $display ("Loop #%0d", i);
      end
    end
endmodule

执行for循环代码后,输出看起来像

ncsim> run
Loop #0
Loop #1
Loop #2
Loop #3
Loop #4
ncsim: *W,RNQUIE: Simulation is complete.