Search code examples
veriloghdltest-bench

How to write a behavioral level code for 2to4 decoder in verilog?


I want to write a behavioral level code for 2 to 4 decoder using for loop in Verilog. This is what I tried, but I always seem to get the output as 0:

module decoder2x4Beh(a,e,q);
input e;
input [1:0]a;
output reg [3:0]q;
integer int_a,i;
always @(a) int_a = a;
initial begin
if(e) begin
 for(i=0;i<4;i=i+1) begin
  if(int_a==i)begin
  q[i] = 1'b1;
  end
 end
end
else q=4'b0;
end
endmodule

This is my testbench:

module testDecoder2x4();
reg e;
reg [1:0]a;
wire [3:0]q;
//decoder3x8 dec1(.d(d),.y(y));
//decoder2x4_df dec2(.a(a),.e(e),.q(q));
decoder2x4Beh dec3(.a(a),.e(e),.q(q));
integer k;
initial
begin
{e,a} = 3'b0;
$monitor($time," enable %b input code = %b   output q3 %b q2 %b q1 %b q0 %b",e,a,q[3],q[2],q[1],q[0]);
for(k=0;k<16;k=k+1)
begin
#10 {e,a} = k;
end
end
initial
#120 $stop;
endmodule

Solution

  • You have a few issues:

    1. your action code in decoder2x4Beh is executed only once at time 0 because you put in in the initial block. Instead it should be a part of an always block. For example
    always @* begin
       if(e) begin
          for(i=0;i<4;i=i+1) begin
             if(int_a==i)begin
                q[i] = 1'b1;
             end
          end
       end
       else 
         q=4'b0;
    end
    
    1. {e,a} = k, will only set enable for some of the sequences. I think that you should provide a reset at the beginning of the tb and then have 'e' asserted through the simulation process.

    2. You'd better use always @* to avoid issues with incomplete sensitivity lists.

    3. You should started using clocks in your design.

    4. Good indentation would help reading your program.