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

5.1 Verilog 模块与端口

系统讲解 Verilog 模块结构建模框架、端口列表与方向数据类型规则(input/output/inout 与隐式 wire),并完整剖析含三态上下拉控制的双向 PAD 模块设计与仿真响应。

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

学完这一章,你能够

模块结构与五类内部组成

Verilog 结构级建模包含门级(Gate)例化、用户自定义原语(UDP)例化和模块(module)例化三类描述方式,其中模块例化是数字系统分层设计的核心。模块以 `module` 开头、以 `endmodule` 结束,首部依次给出模块名、可选参数列表 `#(parameter_list)` 与可选端口列表 `(port_list);`,其后进入模块声明与实现体。

模块实体内部由五类可选部分组成:变量与线网声明、数据流语句(如 `assign`)、行为级过程块(`initial`/`always`)、低层模块例化,以及任务(`task`)和函数(`function`)。这五部分在代码中的先后顺序较为自由,但所有信号与变量都必须遵循“先声明、后使用”原则,端口声明与参数定义应置于具体行为逻辑之前。

端口列表与方向数据类型规范

端口是模块与外部电路交互的唯一边界,模块内部实现对外部不可见。需要与外界通信的模块(例如芯片 I/O 单元 `pad(DIN, OEN, PULL, DOUT, PAD)`)在首部列出端口列表;若模块不与外界交互(典型如顶层仿真激励 `module test;`),则可直接省略端口列表并以分号结束模块头。

按信号流向,端口分为输入 `input`、输出 `output` 和双向 `inout` 三种。在模块内部,`input` 与 `inout` 只能为线网类型(不可声明为 `reg`,因其仅实时反映外部驱动而非锁存数值),而 `output` 可为 `wire` 或 `reg`。Verilog 中端口默认隐式具备 `wire` 属性,因此纯线网端口可省略重复的 `wire` 声明,但过程块驱动的输出必须显式标注 `reg`;工程中更推荐 Verilog-2001 ANSI 风格,直接在模块头内合并声明方向、位宽与 `output reg` 类型,语义与在模块实体中分开声明完全等价。

双向 PAD 端口建模与三态上下拉仿真分析

双向端口 `inout` 常见于芯片引脚 PAD 模型。以具备方向控制 `OEN`(`1` 为输入、`0` 为输出)与上下拉控制 `PULL[1:0]` 的 `pad` 模块为例:模块通过连续赋值 `assign PAD = OEN ? 1'bz : DIN;` 在输出模式将 `DIN` 驱动到 `PAD`,在输入模式释放总线呈高阻 `z`;同时通过组合 `always @(*)` 在 `OEN == 1` 时将 `PAD` 电平送至 `DOUT`,其余时间输出高阻;内部再借三态门原语 `bufif1 puller(PAD, PULL[0], PULL[1]);` 实现弱上下拉(由实际硬件逻辑可知:`PULL[1]` 为使能、`PULL[0]` 为拉高/拉低目标电平,即 `2'b10` 下拉为 `0`、`2'b11` 上拉为 `1`、`2'b00`/`2'b01` 关闭上下拉)。

在测试平台中,双向线网 `PAD` 必须以 `wire` 连接,并借助三态条件驱动 `assign PAD = OEN ? PAD_REG : 1'bz;` 避免与模块输出冲突。按时序验证:0~60ns 期间 `OEN=1` 且外部 `PAD_REG=z`(无强驱动),`PULL=2'b10` 时 `PAD=0`、20ns 切至 `2'b11` 时 `PAD=1`、40ns 切至 `2'b00` 时 `PAD=z`;60~100ns 外部 `PAD_REG` 强驱动 `0`/`1`,`PAD` 与 `DOUT` 均严格跟随外部电平;110ns 后切换 `OEN=0` 进入输出模式,`PAD` 跟随 `DIN`(`z -> 0 -> 1`)而 `DOUT` 维持高阻 `z`。离线脚本同步复现了上述全时段三态解析与多驱动冲突判 `x` 逻辑,来源压缩包已登记未联网下载。

离线仿真双向 PAD 模块三态上下拉、输入/输出切换与总线冲突解析

python · 阅读源码
"""Offline Verilog RTL verification lab for Chapter 19 (module-port)."""
import json
import shutil

VERSION = "CPython 3.12.14 offline Verilog RTL bit-accurate simulator (iverilog absent)"


def resolve_net(drivers):
    """Resolve IEEE 1364 4-state wire from multiple drivers ('0','1','z','x')."""
    active = [d for d in drivers if d != "z"]
    if not active:
        return "z"
    unique = set(active)
    if len(unique) == 1:
        return active[0]
    return "x"


def sim_pad_cell(din, oen, pull, ext_pad_reg):
    """Bit-accurate behavioral model of the bidirectional PAD module."""
    # PAD internal driver: assign PAD = OEN ? 'bz : DIN;
    drv_internal = "z" if oen == "1" else din
    # Testbench external driver: assign PAD = OEN ? PAD_REG : 1'bz;
    drv_external = ext_pad_reg if oen == "1" else "z"
    # Puller bufif1(PAD, PULL[0], PULL[1]) acting as weak pull when no strong driver
    pull_en = (pull >> 1) & 1
    pull_val = str(pull & 1)
    strong = resolve_net([drv_internal, drv_external])
    if strong != "z":
        pad_net = strong
    else:
        pad_net = pull_val if pull_en else "z"
    # always @(*) DOUT = (OEN == 1) ? PAD : 'bz;
    dout = pad_net if oen == "1" else "z"
    return {"PAD": pad_net, "DOUT": dout}


def case_module_port_direction_rules():
    """Verify IEEE 1364 port direction vs internal/external data type rules."""
    rules = {
        "input": {"internal_allowed": ["wire"], "external_allowed": ["wire", "reg"]},
        "output": {"internal_allowed": ["wire", "reg"], "external_allowed": ["wire"]},
        "inout": {"internal_allowed": ["wire"], "external_allowed": ["wire"]},
    }
    implicit_default = "wire"
    ansi_vs_non_ansi_equivalent = True
    expected = {
        "input_internal_wire_only": True,
        "output_internal_reg_allowed": True,
        "inout_both_wire_only": True,
        "implicit_type": "wire",
        "ansi_equivalent": True,
    }
    actual = {
        "input_internal_wire_only": rules["input"]["internal_allowed"] == ["wire"],
        "output_internal_reg_allowed": "reg" in rules["output"]["internal_allowed"],
        "inout_both_wire_only": (
            rules["inout"]["internal_allowed"] == ["wire"]
            and rules["inout"]["external_allowed"] == ["wire"]
        ),
        "implicit_type": implicit_default,
        "ansi_equivalent": ansi_vs_non_ansi_equivalent,
    }
    return {
        "name": "module_port_direction_rules",
        "summary": "校验 input/output/inout 端口内部与外部数据类型约束、隐式 wire 规则及 ANSI 风格等价性",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_pad_input_pull_modes():
    """Verify PAD pull-down (2'b10), pull-up (2'b11), and dispull (2'b00) in input mode."""
    t0 = sim_pad_cell(din="z", oen="1", pull=0b10, ext_pad_reg="z")
    t20 = sim_pad_cell(din="z", oen="1", pull=0b11, ext_pad_reg="z")
    t40 = sim_pad_cell(din="z", oen="1", pull=0b00, ext_pad_reg="z")
    expected = {
        "t0_pulldown": {"PAD": "0", "DOUT": "0"},
        "t20_pullup": {"PAD": "1", "DOUT": "1"},
        "t40_dispull": {"PAD": "z", "DOUT": "z"},
    }
    actual = {"t0_pulldown": t0, "t20_pullup": t20, "t40_dispull": t40}
    return {
        "name": "pad_input_pull_modes",
        "summary": "仿真 PAD 输入高阻悬空时 0ns 下拉、20ns 上拉与 40ns 关闭上下拉的三态响应",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_pad_external_drive_and_output_mode():
    """Verify PAD external driving (60ns-100ns) and output driving (OEN=0) transitions."""
    t60 = sim_pad_cell(din="z", oen="1", pull=0b00, ext_pad_reg="0")
    t80 = sim_pad_cell(din="z", oen="1", pull=0b00, ext_pad_reg="1")
    t110 = sim_pad_cell(din="z", oen="0", pull=0b00, ext_pad_reg="1")
    t125 = sim_pad_cell(din="0", oen="0", pull=0b00, ext_pad_reg="1")
    t140 = sim_pad_cell(din="1", oen="0", pull=0b00, ext_pad_reg="1")
    expected = {
        "t60_in0": {"PAD": "0", "DOUT": "0"},
        "t80_in1": {"PAD": "1", "DOUT": "1"},
        "t110_outz": {"PAD": "z", "DOUT": "z"},
        "t125_out0": {"PAD": "0", "DOUT": "z"},
        "t140_out1": {"PAD": "1", "DOUT": "z"},
    }
    actual = {
        "t60_in0": t60,
        "t80_in1": t80,
        "t110_outz": t110,
        "t125_out0": t125,
        "t140_out1": t140,
    }
    return {
        "name": "pad_external_drive_and_output_mode",
        "summary": "验证双向 PAD 外部驱动输入(PAD->DOUT)及 OEN=0 输出模式(DIN->PAD、DOUT=z)",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_pad_bus_contention_and_probe():
    """Verify contention ('0' vs '1' -> 'x') and probe native Verilog simulator absence."""
    contention = resolve_net(["0", "1"])
    agree = resolve_net(["1", "1", "z"])
    iverilog_found = shutil.which("iverilog") is not None
    expected = {"contention": "x", "agree": "1", "iverilog_found": False}
    actual = {"contention": contention, "agree": agree, "iverilog_found": iverilog_found}
    return {
        "name": "pad_bus_contention_and_probe",
        "summary": "验证双向总线双向冲突解析为未知态 x 及本地原生仿真器探测结果",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_module_port_direction_rules(),
        case_pad_input_pull_modes(),
        case_pad_external_drive_and_output_mode(),
        case_pad_bus_contention_and_probe(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 在 CPython 3.12.14 离线脚本中验证端口方向类型规则、PAD 下拉/上拉/高阻、外部驱动与输出驱动切换以及双驱动冲突判 x 全部通过。
离线仿真双向 PAD 模块三态上下拉、输入/输出切换与总线冲突解析

所需环境:Windows x64、CPython 3.12.14 离线 Verilog RTL 位精确数字算法与周期仿真模型(本机未安装 iverilog/vvp/verilator/vsim/vivado)。

当前源码 SHA256:46f0b936bd275a85f653e7f5f3fd4eb410d90fa0fc4a08324790e2a13d01628d

下载本站示例源码

本地运行

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

下载5.1 Verilog 模块与端口实验

所需环境:Windows x64、CPython 3.12.14 离线 Verilog RTL 位精确数字算法与周期仿真模型(本机未安装 iverilog/vvp/verilator/vsim/vivado)。

ZIP SHA256:2432e19f45f81c627bb20465f63665daf20bf55b02fbaa8c26e0acf317ad7021

常见错误与边界

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

练习与解答

在 Verilog 模块声明中,为什么 `input` 和 `inout` 端口不能声明为 `reg` 类型?测试平台连接被测模块的 `inout` 端口时应采用什么驱动方式?

展开参考解答

`input` 与 `inout` 端口在模块内部仅反映外部连续驱动信号的变化,本身不具备过程存储语义,因此必须为线网型(`wire`);测试平台连接 `inout` 端口时需将其声明为 `wire`,并通过三态条件连续赋值(如 `assign PAD = OEN ? PAD_REG : 1'bz;`)在方向切换时释放总线,防止与 DUT 发生多驱动冲突导致未知态 `x`。

规范与官方依据