0

I am writing a ripple counter using D-Flip Flops. However the following code is giving me Illegal reference error inside initial block for q2,q3,q4variables. Why is that?

module RCounter;

reg d,d2,d3,d4,clk;
wire q,q2,q3,q4;


DFlipFlop a(d,q,clk);
DFlipFlop a1(d2,q2,q);
DFlipFlop a2(d3,q3,q2);
DFlipFlop a3(d4,q4,q3);

initial

begin

clk =1;


d=0;d2=0;d3=0;d4=0;q2=0;q3=0;q4=0;

#2 d=1;d2=~q2; d3=~q3; d4=~q4;
#2 d=0;d2=~q2; d3=~q3; d4=~q4;
#2 d=1;d2=~q2; d3=~q3; d4=~q4;
#2 d=0;d2=~q2; d3=~q3; d4=~q4;
#2 d=1;d2=~q2; d3=~q3; d4=~q4;
#2 d=0;d2=~q2; d3=~q3; d4=~q4;
#2 d=1;d2=~q2; d3=~q3; d4=~q4;

end

always 
begin

#2 assign clk = ~ clk;

end

endmodule

D FlipFlop module:

module DFlipFlop(d,q,clk);

input d,clk;
output q;

assign q = clk?( (d==1)? 1:0) : q;

endmodule

How can I solve this problem?

Regards

rene
  • 41,474
  • 78
  • 114
  • 152
James Aflred
  • 87
  • 2
  • 5
  • 12

2 Answers2

2

As Vlad Lazarenko has pointed out you can not assign values to wires inside initial or always@ blocks.

The fix for this is to simply to change the type from wire to reg.

Or declare everything (except tristate buses) as logic if you are using SystemVerilog.

The definition of reg or wire only applies to that level of hierarchy. A reg can drive a port which is treated as wire inside that module.

Reg does not imply a flip-flop or register it is a simulator optimisation.

It is also worth noting that a flip-flop is normally instantiated via:

reg x;
always @(posedge clk or negedge rst_n) begin
  if(~rst_n) begin
    //reset condition
    x <= 1'b0;
  end
  else begin
    x <= next_value;
  end
end
Morgan
  • 19,934
  • 8
  • 58
  • 84
0

You are trying to assign initial values to wires, here:

q2=0;q3=0;q4=0;

That is illegal.

  • 2
    @JamesAflred: Do not do it? It seems like you desperately need to learn Verilog before writing any hardware descriptions using it. –  Feb 20 '13 at 15:13
  • well I am learning it through making programs like this. So how can I solve this issue? I am posting the full code now. – James Aflred Feb 20 '13 at 15:17
  • @JamesAflred: Oh, well... You don't write programs with verilog :) You describe the hardware with it. Try learning it by reading the book first, then proceed to writing code. At least read what the wire is. Basically, it connects something to something else and do not store any information. Now, you are trying to store `0` in it. How do you do it? There is no way of doing this, it doesn't make any sense whatsoever. So do not do it. –  Feb 20 '13 at 15:42