Search code examples
verilogflip-flop

Register type variable gives error : unknown type


I'm making a 1 bit positive edge Dflipflop. All outputs should be assigned only when there is a positive edge of the clock signal. Q is same as D, Qbar is the negation of D.

It somehow works when I try this with Qbar as a wire.

assign Qbar = ~Q;

outside of the always block. But the original code as below gives an error that "Syntax error near =" and "Qbar is an unknown type"

I've tried to make Qbar assignment a non blocking type, but it has no effect.

module DFlipFlop(
    input D,
    input clk,
    output reg Qbar,
    output reg Q
    );
//assign Qbar = ~D;
always @(posedge clk)
     Q = D;
     Qbar = ~D; 
endmodule

What am I missing here? I'm new to verilog.


Solution

  • Your error message is caused by the fact that in Verilog if you have more than one statement in an always block (and in other places too) it must be enclosed within a begin - end construct. So, you needed this:

    module DFlipFlop(
        input D,
        input clk,
        output reg Qbar,
        output reg Q
        );
    
      always @(posedge clk) begin
         Q = D;
         Qbar = ~D; 
      end
    endmodule
    

    However, that isn't a good solution, because

    i) (unless you know what you're doing) always use non-blocking assignments for variables that are to become flip-flops after synthesis and

    ii) using a wire and assign statement is probably a better solution anyway, because (initially at least) if you assign to two separate variables within a clocked always block, your synthesiser with output two flip-flops - one for Q and one for Qbar.

    This is a better solution:

    module DFlipFlop(
        input D,
        input clk,
        output Qbar,
        output reg Q
        );
    
      always @(posedge clk)
         Q <= D;
    
      assign Qbar = ~Q;
    
    endmodule