Electrical – How to measure time difference between 2 signal changes in verilog

system-verilogverificationverilog

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.

Best 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.