You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Verilog 8位或门模块输出异常求助:输出值为0或X

问题分析与解决方案

核心错误点

  1. 测试模块的驱动冲突
    测试模块中wire out = 0;是错误写法:wire类型不能直接这样赋值,这会给out额外添加一个恒定为0的驱动源,和Or8Way模块的输出驱动产生冲突。当模块输出为1时,两个驱动值(1和0)矛盾,导致最终输出为X;当模块输出为0时,两个驱动值一致,输出为0——这完全匹配你看到的测试结果。

  2. Or8Way模块未实现完整8位或运算
    你的Or8Way只对in_a[0]和一个固定0做了或运算,完全没处理其他7位。这导致只有当输入的第0位为1时模块才会输出1(还被测试模块的冲突掩盖成X),其他位为1时模块输出0,而非正确的1。

修正后的代码

首先修正测试模块

module OR8;
    reg  [7:0] in_a;
    wire out;  // 去掉错误的赋值,仅声明wire
    
    Or8Way or8_gate(in_a,out);

    initial begin       
        $display("Inputs: in_a = 1");
        in_a = 1;
        #20 $display("Output: out = %b", out);
        $display("Inputs: in_a = 0");
        in_a = 0;
        #20 $display("Output: out = %b", out);
        $display("Inputs: in_a = 25");
        in_a = 25;
        #20 $display("Output: out = %b", out);
        $display("Inputs: in_a = 32");
        in_a = 32;
        #20 $display("Output: out = %b", out);
        $display("Inputs: in_a = 4180");
        in_a = 4180[7:0];  // 取4180的低8位(原数超过8位)
        #20 $display("Output: out = %b", out);
        $display("Inputs: in_a = 0");
        in_a = 0;
        #20 $display("Output: out = %b", out);
    end
endmodule

然后实现正确的Or8Way模块

方式一:门级原语级联(贴合手动搭门的思路)
module Or8Way( input [7:0] in_a, output out);
    wire tmp1, tmp2, tmp3, tmp4, tmp5, tmp6;
    // 逐级或运算,覆盖所有8位
    or(tmp1, in_a[0], in_a[1]);
    or(tmp2, tmp1, in_a[2]);
    or(tmp3, tmp2, in_a[3]);
    or(tmp4, tmp3, in_a[4]);
    or(tmp5, tmp4, in_a[5]);
    or(tmp6, tmp5, in_a[6]);
    or(out, tmp6, in_a[7]);
endmodule
方式二:归约运算符实现(简洁写法)
module Or8Way( input [7:0] in_a, output out);
    assign out = |in_a;  // |是归约或,自动对所有8位执行或运算
endmodule
方式三:基于NAND门实现(延续你之前用NAND搭逻辑的需求)

利用逻辑转换规则:A OR B = ~(NAND(~A, ~B)),用NAND门构造OR后逐级级联:

module Or8Way( input [7:0] in_a, output out);
    wire n0, n1, n2, n3, n4, n5, n6, n7;
    wire or01, or23, or45, or67;
    wire or03, or47;
    
    // NAND单变量得到该变量的非:NAND(A,A) = ~A
    nand(n0, in_a[0], in_a[0]);
    nand(n1, in_a[1], in_a[1]);
    nand(n2, in_a[2], in_a[2]);
    nand(n3, in_a[3], in_a[3]);
    nand(n4, in_a[4], in_a[4]);
    nand(n5, in_a[5], in_a[5]);
    nand(n6, in_a[6], in_a[6]);
    nand(n7, in_a[7], in_a[7]);
    
    // NAND两个非值得到OR:~(NAND(~A, ~B)) = A OR B
    nand(or01, n0, n1);
    nand(or23, n2, n3);
    nand(or45, n4, n5);
    nand(or67, n6, n7);
    
    nand(or03, or01, or23);
    nand(or47, or45, or67);
    
    nand(out, or03, or47);
endmodule

修正后测试结果说明

  • 输入1(00000001):输出1
  • 输入0:输出0
  • 输入25(00011001):输出1
  • 输入32(00100000):输出1
  • 输入4180的低8位(01010100):输出1

内容的提问来源于stack exchange,提问作者Ice-T

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 00:27:08