显示与监视
本课属于 Coddy Verilog 学习旅程的“基础知识”单元。第 75 课,共 90 课。
$display 和 $monitor 是用于打印仿真信息的系统任务。它们可以帮助你查看设计内部发生的情况。
$display
$display 会在执行时一次性打印一条消息。
语法:
$display("message", variables);示例:
initial begin
$display("Simulation started");
#10;
$display("Time 10");
#10;
$display("Time 20");
end输出:
Simulation started
Time 10
Time 20$monitor
$monitor 会在其中任意变量发生变化时自动打印消息。
语法:
$monitor("message", variables);示例:
initial begin
a = 0; b = 0;
$monitor("Time %0t: a=%b, b=%b", $time, a, b);
#10 a = 1;
#10 b = 1;
#10 a = 0;
end输出:
Time 0: a=0, b=0
Time 10: a=1, b=0
Time 20: a=1, b=1
Time 30: a=0, b=1$display 与 $monitor
| $display | $monitor | |
|---|---|---|
| 打印时机 | 执行时打印一次 | 每次变量变化时打印 |
| 打印次数 | 调用几次就打印几次 | 持续打印(直到变量变化) |
| 用途 | 标题、测试消息 | 跟踪变化的信号 |
常见格式说明符
| 说明符 | 含义 | 示例 |
|---|---|---|
%b | 二进制 | $display("%b", a); |
%d | 十进制 | $display("%d", count); |
%h | 十六进制 | $display("%h", data); |
%t | 时间 | $display("%t", $time); |
%0t | 时间(不留空格) | $display("%0t", $time); |
%s | 字符串 | $display("%s", "Hello"); |
重要规则
| 规则 | 说明 |
|---|---|
$display只打印一次 | 适合打印标题和最终结果 |
$monitor在变化时打印 | 适合监视信号 |
只能有一个$monitor处于活动状态 | 最后一个会覆盖之前的 |
使用$finish停止 | 否则仿真可能会一直运行 |
挑战
在这个 testbench 中添加缺失的 $display 和 $monitor 语句。
操作步骤:
- 添加
$display,打印标题:"Testing OR Gate" - 添加
$monitor,在任何信号发生变化时打印时间、x、y 和 z。格式:"Time %0t: x=%b, y=%b, z=%b" - 在末尾添加
$display,打印 "Test complete"
亲手试试
module or_gate (
input x,
input y,
output z
);
assign z = x | y;
endmodule
module testbench;
reg x, y;
wire z;
or_gate dut (
.x(x),
.y(y),
.z(z)
);
initial begin
// TODO:添加 $display 标题 "Testing OR Gate"
// TODO:添加 $monitor,跟踪时间、x、y、z
// 格式:"Time %0t: x=%b, y=%b, z=%b"
// 施加激励信号
x = 0; y = 0; #10;
x = 0; y = 1; #10;
x = 1; y = 0; #10;
x = 1; y = 1; #10;
// TODO:添加 $display "Test complete"
$finish;
end
endmodule这节课包含一个小测验。开始学习即可作答,并记录你的进度。
基础知识中的所有课
自己练习: Verilog 在线编译器