I am trying to use a testbench to test some features of a 4X1 Mux [a,b,c,d are the inputs , z is the output and s is the select line]. Here is my code:

module testbench_MUX(); reg a,b,c,d; reg [1:0] s; wire z ; MUX4_1 mux(.a(a) ,.b(b),.c(c),.d(d), .s(s),.z(z)); initial begin $dumpfile("dump.vcd"); $dumpvars; end initial begin // { a='b0;b='b1 ;c='b0 ;d='b1 ;s='d0;#15 if(z==0) $display("time : %0t Test # 1 : passed",$time); a='b0;b='b1 ;c='b0 ;d='b1 ;s='d1;#15 if(z==1) $display("Test # 2 : passed"); a='b0;b='b0 ;c='b1 ;d='b1 ;s='d1; #15 if(z==0) $display("Test # 3 : passed"); a='b1;b='b0 ;c='b0 ;d='b0 ;s='d1; #15 if(z==0) $display("Test # 4 : passed"); $finish; end // } 

Here is the waveform:

enter image description here

The kernel displays that test 1 has passed, meaning that z=0:

# KERNEL: time : 15Test # 1 : passed 

But, as you can see from the waveform at time 15ns (the simulation timescale is 1ns/1ns), z=1. Why does the if statement execute?

MUX designcode :

module MUX4_1( input a,b,c,d, input [1:0] s, output reg z ); always @ (*) begin if ( s==0) z=a; else if ( s==1) z=b; else if ( s==2) z=c; else if (s==3) z=d; else z=a; end endmodule: MUX4_1 
0

1 Answer

You have a race condition. At time 15, you change the s input, which causes a change on the z output from 0 to 1. At the same time you sample the z output (if(z=0)). The simulator sees z at 0.

You should delay the time at which you change the input, so that you sample the output when you know it will be stable. For example:

initial begin a='b0; b='b1 ; c='b0 ; d='b1 ;s='d0; #15 if(z==0) $display("time : %0t Test # 1 : passed",$time); #1; a='b0;b='b1 ;c='b0 ;d='b1 ;s='d1; 

In this case, z will be checked at time 15, and then s will change at time 16.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.