Verilog 控制块
如果没有条件语句和其他控制逻辑流的方法,就无法实现硬件行为。 Verilog 有一套控制流块和机制来实现这一点。
如果-否则-如果
这个条件语句 用于决定是否应该执行某些语句。这与 if-else-if
非常相似 C 中的语句。如果表达式的计算结果为真,则将执行第一条语句。如果表达式计算结果为 false 并且如果 else
部分存在,else
部分将被执行。
// if statement without else part
if (expression)
[statement]
// if statment 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]
else
if-else 的一部分是可选的,如果 else
在嵌套的 if 序列中被省略。为了避免这种混淆,如果缺少 else,总是将 else 与前一个关联起来会更容易。另一种方法是将语句包含在 begin-end
中 堵塞。最后一个else
部分处理不满足上述条件的非上述情况或默认情况。
点击这里阅读更多关于 if-else-if 的内容
循环提供了一种在块内多次执行单个或多个语句的方法。 Verilog中有四种不同类型的循环语句。
永远循环
这将连续执行块内的语句。
forever
[statement]
forever begin
[multiple statements]
end
示例
module my_design;
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 the maximum of 5000 lines. Killing process.
重复循环
这将执行语句固定次数。如果表达式的计算结果为 X 或 Z,那么它将被视为零并且根本不会执行。
repeat ([num_of_times]) begin
[statements]
end
repeat ([num_of_times]) @ ([some_event]) begin
[statements]
end
示例
module my_design;
initial begin
repeat(4) 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 ... ncsim: *W,RNQUIE: Simulation is complete.
while 循环
只要表达式为真,这将执行语句,并在条件变为假时退出。如果条件一开始就为假,则根本不会执行语句。
while (expression) begin
[statements]
end
示例
module my_design;
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.
for 循环
for ( initial_assignment; condition; increment_variable) begin
[statements]
end
这将使用三步过程控制语句:
- 初始化循环计数器变量
- 计算表达式,通常涉及循环计数器变量
- 增加循环计数器变量,以便稍后表达式变为假并退出循环。
示例
module my_design;
integer i = 5;
initial begin
for (i = 0; i < 5; i = i + 1) begin
$display ("Loop #%0d", i);
end
end
endmodule
模拟日志ncsim> run Loop #0 Loop #1 Loop #2 Loop #3 Loop #4 ncsim: *W,RNQUIE: Simulation is complete.
点击这里阅读更多关于 for 循环的内容。
Verilog