Why do we have to add a "clr" (clean input wire) while forming a T flip-flop in Verilog with Vivado?

I am trying to form a T flip-flop in Verilog. I am studying verilog from "Digital System Design with FPGA: Implementation using verilog and vhdl" and the code for T flip-flop is here below:

module t_flip_flop(t,clk,clr,q,qn);

input t,clk,clr;
output reg q,qn;

always @(posedge clk or negedge clr)
begin
if(clr==0)
q<=0;qn<=1;
else
q<=q^t;
qn<=~(q^t);
end

I understand the xor part that we use this because of the toggle operation. I tried to form it without using "clr", but it didn't work. (I am using "clr" as clear input which is for resetting the flip-flop). Can't I do it without using "clr"?

I tried to change code like this below:

module t_flip_flop(t,clk,q,qn);

input t,clk;
output reg q,qn;

always @(posedge clk)
if(t)
begin
q<=q^t;
qn<=~(q^t);
end

But in the simulation, I get "x" for both q and qn in Vivado. I was expecting to get the same results as the code with "clr".

Upvotes: 2

Views: 205

Answers (1)

toolic
toolic

Reputation: 61977

The clr signal is used to properly initialize q and qn.

You declared q as a reg type. In Verilog simulations, reg is initialized to x (the "unknown" value).

Consider your code without clr. At time 0, q=x. Let's say the posedge of clk is at 10ns and t=1 at that time. The assignment:

q<=q^t;

is evaluated like:

q <= x ^ 1;

Verilog evaluates x ^ 1 as x. Since x could be 0 or 1, we don't know if the expression is 1^1 or 0^1, which means that we don't know what the result of the expression should be. This means that q will remain x for the rest of the simulation. There will be no way to change its value.

Using the clr signal fixes that problem. Typically, at the start of simulation (time=0), you would set clr=0 so that q is assigned a known value (0). That prevents the x.

Even if you didn't start with clr=0, as soon as you do set clr=0 at a later time, that will resolve the x.

All of this applies to the qn signal as well.


Note: The 1st code example in the question has syntax errors. I assume the q and qn assignments should have been inside begin/end blocks.

Upvotes: 2

Related Questions