T-flip flop in Verilog

Carmen González picture Carmen González · Mar 26, 2017 · Viewed 7.4k times · Source

I want to build a T-flip flop in Verilog. So far I have written the following code, but I wish they could see if it is correct please. The machine I was using to make the code is in the image.

module flopJK(q,j,k,c);
 input j,k,c;
 output q;
 reg q;
 always @(posedge c)
 begin
  case ({j,k})
   {1'b0,1'b0}:begin q=q; end
   {1'b0,1'b1}:begin q=1'b0; end
   {1'b1, 1'b0}:begin q=1'b1; end
   {1'b1, 1'b1}:begin q=~q; end
  endcase
 end
endmodule

T-flip flop in Verilog: enter image description here

Answer

Karan Shah picture Karan Shah · Mar 26, 2017

There are several scope of improvements I think.

  • reset signal is not there, which is required to initialise your FF.
  • Always use non-blocking assignment for sequential logic and blocking for combinational logic.

Here is your code.

module flopJK (q,j,k,c, r);
 input j,k,c, r;
 output q;
 reg q;

 always @(posedge c, negedge r)
 begin
  if (r != 1) 
     q <= 1'b0;
  else
  begin
    case ({j,k})
     {1'b0,1'b0}:begin q <= q; end
     {1'b0,1'b1}:begin q <= 1'b0; end
     {1'b1, 1'b0}:begin q <= 1'b1; end
     {1'b1, 1'b1}:begin q <= ~q; end
    endcase
  end
 end
endmodule