# How to measure time difference between 2 signal changes in verilog?

There are two signals sig, enable - and I wanted to find the time difference after which enable toggles after sig falls. ( >Sig Low to Enable toggle< time)

I understand that always@() block can't be nested inside another, so I tried the following approach:

  realtime toggletime ;
realtime sig_low;

always@(negedge sig) begin
sig_low = $time ; @(enable)begin toggletime=$time - sig_low ;
end
end


My idea was to trace sig, and whenever it goes low, note the time (in sig_low) and from that point, trace enable and whenever it changes note the difference between that point and the earlier sig_low value. But this isn't giving me the required result. Is there some other way of doing this?

*The sig signal is a periodic pulse that goes low say, every 500us. enable is a signal that toggles at sporadic intervals. I am trying to measure the time elapsed after the latest sig low after which enable toggles.

*Both are synchronous to the same clock. They don't trigger at the same time. If there are multiple neg edges, only the last edge is of interest.

• The @(enable) needs to be in a separate @always block -- one that isn't already qualified by @(negedge sig). – Dave Tweed Jan 17 '17 at 13:15
• You have the verification tag, so can I assume this does not need to be synthesize? What is toggletime used for? Are these signals synchronous to the same clock? Can sig and enable be triggered at the same time? What should happen if there are multiple negedge sig before the first enable toggle? – Greg Jan 17 '17 at 21:40
• It would help if you gave an example that shows what your required result should be, versus the result you are getting. – dave_59 Jan 18 '17 at 1:01
• @dave_59 Required would be say 200 (if sig low is at 500ns ans enable toggles at 700ns) but toggletime variable is not getting any value as of now – Ambareesh Sr Ja Jan 18 '17 at 5:33

## 1 Answer

The code you wrote should work. The only possible problem is that you should use $realtime instead of $time if the current timescale is greater than 1ms. That prevents time from being rounded to an integer.

I can rearrange the begin/end blocks to better explain how it executes.

   always begin
@(negedge sig) // wait for sig to goto 0
sig_low = $realtime ; @(enable) // wait for enable to change its value toggletime=$realtime - sig_low ;
end


This is functionally equivalent to what you wrote.

• timescale is 1ns – Ambareesh Sr Ja Jan 18 '17 at 6:59
• I used $display(sig_low,"difference in toggle is",toggletime) ; and tried to print the value, but it isn't printing any value. Hence I assumed that the approach is wrong. – Ambareesh Sr Ja Jan 18 '17 at 7:05 • Did you mean to write $display("difference in toggle is %g",toggletime); – dave_59 Jan 18 '17 at 8:31
• No. But I tried that too. No avail. Rest of the always block \$displays are working except for this one. line 110 : edaplayground.com/x/37nH – Ambareesh Sr Ja Jan 18 '17 at 9:58