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

8.7k views Asked by At

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
2

There are 2 answers

0
Serge On BEST ANSWER

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.

0
toolic On

In decoder2x4Beh, change:

initial begin

to:

always @* begin

The intital block only executes once at time 0, but you want the block to be executed whenever there is a change on any of its input signals.

This is the output I get, showing q changing:

               0 enable 0 input code = 00   output q3 0 q2 0 q1 0 q0 0
              20 enable 0 input code = 01   output q3 0 q2 0 q1 0 q0 0
              30 enable 0 input code = 10   output q3 0 q2 0 q1 0 q0 0
              40 enable 0 input code = 11   output q3 0 q2 0 q1 0 q0 0
              50 enable 1 input code = 00   output q3 1 q2 0 q1 0 q0 1
              60 enable 1 input code = 01   output q3 1 q2 0 q1 1 q0 1
              70 enable 1 input code = 10   output q3 1 q2 1 q1 1 q0 1
              80 enable 1 input code = 11   output q3 1 q2 1 q1 1 q0 1
              90 enable 0 input code = 00   output q3 0 q2 0 q1 0 q0 0
             100 enable 0 input code = 01   output q3 0 q2 0 q1 0 q0 0
             110 enable 0 input code = 10   output q3 0 q2 0 q1 0 q0 0