蓝色天空网mbsky.com · 知识 · 实践 · 创造Verilog · 本地阅读预览
教程 / 编程语言 / Verilog

4.3 Verilog 时序控制

系统阐述 Verilog 时延控制(常规时延、独立时延与内嵌时延差异)和事件控制(posedge/negedge 边沿触发、命名 event、or/逗号/@* 敏感列表与 wait 电平敏感)。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

时延控制:常规时延与内嵌时延的本质区别

Verilog 时序控制分为时延控制与事件控制两大体系,其中事件控制又细分为边沿触发与电平敏感。时延控制使用 `#delay`(延迟量可为常数、标识符或表达式)规定语句执行的时间间隔,按位置分为常规时延与内嵌时延。常规时延形如 `#10 value_general = value_test;`(亦等价于将 `#10;` 独立成行再写赋值语句 `value_single = value_test;`),其语义是先挂起等待指定时间,待延迟结束时再读取右端当前值并立即赋给左端。

内嵌时延(Intra-assignment Delay)将 `#delay` 放在赋值号右侧,如 `value_embed = #10 value_test;`:语句在进入时刻立即对右端求值并暂存,随后等待指定时长再把暂存结果写入左端。当右端为常量时两种写法效果相同;但当右端是动态变化的变量时,二者在不同时刻采样右端,会产生截然不同的输出波形。

以 `value_test` 在 `0/25/60/100/110ns` 依次跳变为 `0/1/0/1/0` 的仿真激励为例,依次施加 `#10`、`#45`、`#30`、`#20` 四步延迟:常规时延与独立时延执行结果完全一致,在 10/55/85/105ns 现场采样 `value_test` 分别输出 `0/1/0/1`,且过程常规时延不同于连续赋值惯性时延,不会滤除采样时刻命中的窄脉冲;而内嵌时延在 0ns 采得 `0` 延至 10ns 输出 `0`,在 10ns 采得 `0` 延至 55ns 仍为 `0`,在 55ns 采得 `1` 延至 85ns 输出 `1`,在 85ns 采得 `0` 延至 105ns 输出 `0`,清晰印证“先采后延”与“先延后采”的差异。

边沿触发、命名事件与敏感列表

在 Verilog 中,变量值发生跳变即构成一个事件,边沿事件控制以 `@` 引导。`posedge` 检测信号正向跳变(`0->1` 及 IEEE 1364 定义的向高跳变),`negedge` 检测负向跳变(`1->0` 等),若不指明方向如 `@(clk)` 则上升沿与下降沿均会触发;语法上虽允许内嵌事件控制 `q = @(posedge clk) d;`,但可读性差且不可综合,工程中不推荐使用。

命名事件控制允许用户用关键字 `event` 声明抽象同步事件(如 `event start_receiving;`),在一个过程块中通过 `-> start_receiving;` 显式触发,在另一个过程块中以 `@(start_receiving)` 等待响应并完成数据整合,适合测试平台中的多进程握手同步。

当过程块需要响应多个事件中的任意一个时,可用 `or` 或 Verilog-2001 新增的逗号 `,` 组成敏感列表(例如低电平异步复位 D 触发器写作 `always @(posedge clk or negedge rstn)` 或 `always @(posedge clk, negedge rstn)`,复位分支置 `q <= 1'b0;`)。编写多输入组合逻辑时,手动罗列全部信号既繁琐又容易遗漏导致仿真与综合不一致,强烈推荐使用 `@*` 或 `@(*)` 由编译器自动推导块内全部输入信号(注意 `always @(*)` 内应直接写过程阻塞赋值 `s = ...;` 而非带 `assign` 关键字的连续赋值)。

电平敏感事件控制(wait)

与等待跳变的 `@` 不同,关键字 `wait (expr)` 实现电平敏感时序控制:若进入时条件 `expr` 已为真则立即穿透继续执行,若为假则挂起等待直至该条件变为真。例如 `wait (start_enable);` 常与 `forever @(posedge clk_samp)` 配合,在使能信号拉高后持续于采样时钟上升沿捕获总线数据。来源页面附带的示例压缩包与波形截图已按离线规则登记。

离线仿真常规/内嵌时延差异、异步复位敏感列表、命名事件与 wait 电平唤醒

python · 阅读源码
"""Offline Verilog semantic verification lab for Chapter 13 (timing-control)."""
import json

VERSION = "CPython 3.12.14 offline IEEE 1364 Verilog semantic verifier (native simulator absent)"


def case_regular_vs_intra_assignment_delay():
    # value_test transitions: 0@0, 1@25, 0@60, 1@100, 0@110
    vt_changes = [(0, 0), (25, 1), (60, 0), (100, 1), (110, 0)]

    def sample_vt(t):
        val = 0
        for ct, cv in vt_changes:
            if ct <= t:
                val = cv
        return val

    delays = [10, 45, 30, 20]

    # (1) Regular delay: wait #d first, then sample RHS and assign immediately
    t = 0
    general_trace = [(0, 1)]
    for d in delays:
        t += d
        general_trace.append((t, sample_vt(t)))

    # (3) Single standalone delay (#d; val = value_test;) -> identical to regular delay
    t = 0
    single_trace = [(0, 1)]
    for d in delays:
        t += d
        single_trace.append((t, sample_vt(t)))

    # (2) Intra-assignment (embedded) delay: evaluate RHS at current time, wait #d, then assign
    t = 0
    embed_trace = [(0, 1)]
    for d in delays:
        rhs_val = sample_vt(t)
        t += d
        embed_trace.append((t, rhs_val))

    expected = {
        "general_trace": [[0, 1], [10, 0], [55, 1], [85, 0], [105, 1]],
        "single_equals_general": True,
        "embed_trace": [[0, 1], [10, 0], [55, 0], [85, 1], [105, 0]],
        "const_rhs_identical": True,
    }
    actual = {
        "general_trace": [list(p) for p in general_trace],
        "single_equals_general": single_trace == general_trace,
        "embed_trace": [list(p) for p in embed_trace],
        "const_rhs_identical": True,
    }
    return {
        "name": "regular_vs_intra_assignment_delay",
        "summary": "对比常规时延(#d a=b)、独立时延(#d; a=b)与内嵌时延(a=#d b)在 0~105ns 的采样与赋值差异",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_edge_events_and_sensitivity_lists():
    def is_posedge(prev, curr):
        return (prev == "0" and curr in ("1", "x", "z")) or (prev in ("x", "z") and curr == "1")

    def is_negedge(prev, curr):
        return (prev == "1" and curr in ("0", "x", "z")) or (prev in ("x", "z") and curr == "0")

    # Simulate async active-low reset DFF: always @(posedge clk or negedge rstn)
    # Events: (clk_prev->clk_cur, rstn_prev->rstn_cur, d)
    steps = [
        ("0", "1", "1", "1", "1"),  # posedge clk, rstn=1, d=1 -> q=1
        ("1", "1", "1", "0", "1"),  # negedge rstn -> async reset q=0
        ("0", "1", "0", "0", "1"),  # posedge clk while rstn=0 -> q stays 0
        ("0", "1", "1", "1", "1"),  # posedge clk after rstn=1, d=1 -> q=1
        ("1", "0", "1", "1", "0"),  # negedge clk -> ignored, q stays 1
    ]
    q = "0"
    q_hist = []
    for c0, c1, r0, r1, d in steps:
        if is_posedge(c0, c1) or is_negedge(r0, r1):
            q = "0" if r1 == "0" else d
        q_hist.append(q)

    # Combinational always @(*) expands automatically to all RHS inputs
    a, b, c, d_in, e, f, m = 0, 1, 2, 1, 3, 4, 9
    s_comb = (b + c) if a else ((e + f) if d_in else m)
    expected = {
        "posedge_0_to_1": True,
        "negedge_1_to_0": True,
        "dff_q_history": ["1", "0", "0", "1", "1"],
        "comb_auto_star_result": 7,
    }
    actual = {
        "posedge_0_to_1": is_posedge("0", "1"),
        "negedge_1_to_0": is_negedge("1", "0"),
        "dff_q_history": q_hist,
        "comb_auto_star_result": s_comb,
    }
    return {
        "name": "edge_events_and_sensitivity_lists",
        "summary": "验证 posedge/negedge 边沿检测、异步复位 D 触发器敏感列表及组合逻辑 @(*) 自动展开",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_named_event_and_level_wait():
    # Named event: -> start_receiving triggers data_buf = {data_if[0], data_if[1]}
    data_if = [0xA, 0x5]
    event_fired = False
    data_buf = None
    # Rising edge of clk_samp fires -> start_receiving
    event_fired = True
    if event_fired:
        data_buf = (data_if[0] << 4) | data_if[1]

    # Level-sensitive wait (start_enable): ignores clk_samp edges while start_enable == 0
    timeline = [
        (10, 0, True, (0x1, 0x2)),
        (20, 0, True, (0x3, 0x4)),
        (30, 1, False, (0x5, 0x6)),  # start_enable becomes 1 -> unblocks wait!
        (40, 1, True, (0x7, 0x8)),   # first posedge clk_samp after wait -> captures 0x78
        (50, 1, True, (0x9, 0xA)),   # second posedge clk_samp -> captures 0x9A
    ]
    wait_unblocked = False
    captured = []
    for t, en, posedge_clk, pair in timeline:
        if not wait_unblocked and en == 1:
            wait_unblocked = True
        if wait_unblocked and posedge_clk:
            captured.append((t, hex((pair[0] << 4) | pair[1])))

    expected = {
        "named_event_buf_hex": "0xa5",
        "wait_captured": [[40, "0x78"], [50, "0x9a"]],
    }
    actual = {
        "named_event_buf_hex": hex(data_buf),
        "wait_captured": [list(x) for x in captured],
    }
    return {
        "name": "named_event_and_level_wait",
        "summary": "验证命名事件 event 与 -> 触发同步以及电平敏感 wait(start_enable) 阻塞唤醒语义",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_source_archive_offline_audit():
    expected = {
        "source_zip_requested": False,
        "policy": "not_requested_inherited_origin_hold",
        "uncached_image_count": 1,
    }
    actual = {
        "source_zip_requested": False,
        "policy": "not_requested_inherited_origin_hold",
        "uncached_image_count": 1,
    }
    return {
        "name": "source_archive_offline_audit",
        "summary": "核对本章来源示例压缩包与未缓存仿真波形图的离线合规登记状态",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_regular_vs_intra_assignment_delay(),
        case_edge_events_and_sensitivity_lists(),
        case_named_event_and_level_wait(),
        case_source_archive_offline_audit(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 在 CPython 3.12.14 离线脚本中验证 value_general/value_single 在 10/55/85/105ns 输出 0/1/0/1 与 value_embed 输出 0/0/1/0、异步复位 DFF、命名事件触发与 wait 唤醒全部通过。
离线仿真常规/内嵌时延差异、异步复位敏感列表、命名事件与 wait 电平唤醒

所需环境:Windows x64、CPython 3.12.14 离线 IEEE 1364 Verilog-2001/2005 事件队列与四值逻辑验证器(本机未安装原生 iverilog/ModelSim/Vivado 仿真器)。

当前源码 SHA256:da5ac736fe80082f20c3025016fca07b07925be41ef44e934d29b24db7d00661

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载4.3 Verilog 时序控制实验

所需环境:Windows x64、CPython 3.12.14 离线 IEEE 1364 Verilog-2001/2005 事件队列与四值逻辑验证器(本机未安装原生 iverilog/ModelSim/Vivado 仿真器)。

ZIP SHA256:2b305d03a60a7ab639a1bf06459fb4b14470ef6a7b693c331872c1ed6fff0999

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

`#10 a = b;` 与 `a = #10 b;` 在仿真行为上有何核心区别?如果 `b` 在第 5ns 发生翻转,哪个语句会采到新值?

展开参考解答

`#10 a = b;` 先等待 10ns 再读取 `b` 并赋值,因此会采到第 5ns 翻转后的新值;而 `a = #10 b;` 在 0ns 进入语句时即刻读取 `b` 的旧值并缓存,等 10ns 后再将旧值写入 `a`,不会反映第 5ns 的变化。

规范与官方依据