Question

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

Was it helpful?

Solution

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

OTHER TIPS

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

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

That is illegal.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top