Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Synchronized delays are those that are all directly related to one specific point in time, a "base" time, and serve the purpose of "time-aligning" future events relative to that point. A synchronized delay, for example, may be used to output or input a signal at a specific interval, despite the unknown amounts of overhead associated with the code itself. To understand how this is different from the Fixed Delay example, let's look at that example's timing diagram.

_Ref133038029Fixed Delay Timing

Anchor
_Ref133038029


The figure above (Fixed Delay Timing) shows the output of our previous example, the fixed delay example. Notice how the I/O pin P0 toggles roughly every 10 milliseconds, but not exactly? In fact, there's a cumulative error that makes successive state changes further and further out-of-sync in relation to our start time, 0 ms. The delay is 10 ms in length, but the error occurs because that delay doesn't compensate for the length of the rest of the loop. The repeat, !outa[0] and WAITCNT statements each take a little time to execute, and all that extra time is in addition to the 10 ms delay that WAITCNT specified.
Using WAITCNT a slightly different way, for a synchronized delay, will eliminate this timing error. The following example assumes we're using a 5 MHz external crystal.

...

This code first retrieves the value of the System Counter, Time := cnt, then starts the repeat loop where it waits for the System Counter to reach Time + 50,000, toggles the state of I/O pin P0 and repeats the loop again. The statement Time += 50_000 is actually an assignment statement; it adds the value of Time to 50,000, stores that result back into Time and then executes the WAITCNT command using that result. Notice that we retrieved the System Counter's value only once, at the start of the example; that is our base time. Then we wait for the System Counter to equal that original base time plus 50,000 and perform the actions in the loop. Each successive iteration through the loop, we wait for the System Counter to equal another multiple of 50,000 from the base time. This method automatically compensates for the overhead time consumed by the loop statements: repeat, !outa[0] and waitcnt. The resulting output looks like the figure below (Synchronized Delay Timing).

_Ref133038155Synchronized Delay Timing

Anchor
_Ref133038155


Using the synchronized delay method, our output signal is always perfectly aligned to the time base plus a multiple of our interval. This will work as long as the time base (an external crystal) is accurate and the overhead in the loop does not exceed the time interval itself. Note that we waited, with WAITCNT, before the first toggle so that the time between the very first toggle and the second matches that of all the rest.

...