Verilog 3-8译码器Testbench信号未更新问题排查(含for循环)
3-8译码器Testbench仿真信号不更新问题排查
我是Verilog新手,编写了一个3-8译码器及其Testbench,用ModelSim 10.5仿真时发现信号完全不更新,想知道问题是不是出在for循环上。
译码器代码
module decoder_38(input [2:0] in, output reg [7:0] out); always @* begin case (in) //Switch based on concatenation of control signals 3'b000 : out = 8'b00000001; 3'b001 : out = 8'b00000010; 3'b010 : out = 8'b00000100; 3'b011 : out = 8'b00001000; 3'b100 : out = 8'b00010000; 3'b101 : out = 8'b00100000; 3'b110 : out = 8'b01000000; 3'b111 : out = 8'b10000000; endcase end endmodule
Testbench代码
`timescale 1ns / 1ns module tb_decoder_38; // decoder_38 Parameters parameter PERIOD = 20; // decoder_38 Inputs reg [2:0] in ; // decoder_38 Outputs wire [7:0] out ; reg clk; integer i; initial begin clk = 0; forever #(PERIOD/2) clk=~clk; end decoder_38 u_decoder_38 ( .in ( in [2:0] ), .out ( out [7:0] ) ); initial begin in = 0; #(PERIOD*2); for (i = 3'd0; i < 3'd8; i=i+1) begin in = i; #PERIOD; end end endmodule
问题根源
Testbench的for循环条件存在错误:你使用3'd8作为循环终止的比较值,但3位二进制数的有效范围是0~7,3'd8会被Verilog截断为3位二进制数3'b000(对应十进制0)。由于i是integer类型(32位有符号数),比较时3'd8会被符号扩展为32位的0,此时循环条件i < 3'd8等价于i < 0。而i初始值是0,这个条件永远不成立,导致循环体一次都不会执行。
因此in在#(PERIOD*2)之后始终保持初始值0,译码器输出out也固定为8'b00000001,看起来所有信号都没有更新。
修复方案
把循环条件中的3'd8改为十进制的8,修改后的for循环代码如下:
for (i = 0; i < 8; i=i+1) begin in = i; #PERIOD; end
或者也可以用i <= 3'd7作为循环条件,同样能覆盖0~7的所有输入情况。
这样修改后,循环会正常遍历3位输入的所有可能值,in和out信号就能按预期更新了。
内容的提问来源于stack exchange,提问作者Tokubara
相关产品推荐
相关产品推荐

