Atinesh
Atinesh

Reputation: 1910

Implementing JK Flipflop in Verilog

I'm trying to implement simple JK Flipflop in Verilog (Modelsim). But I'm getting the following error

The generate if condition must be a constant expression.

Here is the code which I'm using

module jkfflop(J,K,clk,Q);
input J,K,clk;
output Q;
 if(J==0 & K==1)
  begin
   assign Q = 0;
  end
 else if(J==1 & K==0)
  begin
   assign Q = 1;
  end
 else if(J==1 & K==1)
  begin
   assign Q = ~Q;
  end
endmodule

Can someone help me

Upvotes: 0

Views: 23446

Answers (1)

Morgan
Morgan

Reputation: 20514

In Verilog RTL there is a formula or patten used to imply a flip-flop. for a Positive edge triggered flip-flop it is always @(posedge clock) for negative edge triggered flip-flops it would be always @(negedge clock).

An Example of positive edge triggered block.

 reg [7:0] a;
 always @(posedge clock) begin
   a <= b;
 end

Normally you want a reset as well, a Synchronous reset would be:

 reg [7:0] a;
 always @(posedge clock) begin
   if ( reset == 1'b1 ) begin
     a <= 'b0; 
   end
   else begin
     a <= b;
   end
 end

It is more common is ASIC design to require an active low Asynchronous :

 reg [7:0] a;
 always @(posedge clock, negedge reset_n) begin
   if ( reset_n == 1'b0 ) begin
     a <= 'b0; 
   end
   else begin
     a <= b;
   end
 end

Note that the asynchronous reset has reset in the sensitivity list this makes the block respond to changes in the signal.

The way you have used (reused) assign is incorrect.

Using the above info your module would become:

module jkfflop(
  input  J,
  input  K,
  input  clk,
  output Q );
  always @(posedge clk) begin
    if(J==1'b0 && K==1'b1) begin
      Q <= 'b0;
    end
    else if(J==1'b1 && K==1'b0) begin
      Q <= 1'b1;
    end
    else if(J==1'b1 & K==1'b1) begin
      Q <= ~Q;
    end
  end
endmodule

But could be written with a case statement:

  always @(posedge clk) begin
    case({J,K})
      2'b0_0 : Q <= Q   ;
      2'b0_1 : Q <= 1'b0;
      2'b1_0 : Q <= 1'b1;
      2'b1_1 : Q <= ~Q  ;
    endcase
  end

Upvotes: 2

Related Questions