Propeller Manual

Table Of Contents
2: Spin Language Reference – WAITCNT
Propeller Manual v1.1 · Page 219
This code toggles the state of I/O pin P0 and waits for 50,000 system clock cycles before
repeating the loop again. Remember, the Value parameter must be the desired 32-bit value to
match against the System Clock’s value. Since the System Clock is a global resource that
changes every clock cycle, to delay for a certain number of cycles from “now” we need a
value that is added to the current System Counter value. The
cnt in “50_000 + cnt” is the
System Counter Register variable; it returns the value of the System Counter at that moment
in time. So our code says to wait for 50,000 cycles plus the current value of the System
Counter; i.e.: wait 50,000 cycles from now. Assuming that an external 5 MHz crystal is
being used, 50,000 cycles is about 10 ms (1/100
th
second) of time.
IMPORTANT: Since
WAITCNT pauses the cog until the System Counter matches the given
value, care must be taken to ensure that the given value was not already surpassed by the
System Counter. If the System Counter already passed the given value before the wait
hardware activated then the cog will appear to have halted permanently when, in fact, it is
waiting for the counter to exceed 32 bits and wrap around to the given value. Even at 80
MHz, it takes over 53 seconds for the 32-bit System Counter to wrap around!
Related to this, when using
WAITCNT in Spin code as shown above, make sure to write the
Value expression the same way we did: in the form “
offset + cnt” as opposed to
cnt + offset.” This is because the Spin interpreter will evaluate this expression from left
to right, and each intermediate evaluation within an expression takes time to perform. If
cnt
were at the start of the expression, the System Counter would be read first then the rest of the
expression would be evaluated, taking an unknown amount of cycles and making our
cnt
value quite old by the time the final result is calculated. However, having
cnt as the last
value in the
WAITCNT expression ensures a fixed amount of overhead (cycles) between reading
the System Counter and activating the wait hardware. In fact, the interpreter takes 381 cycles
of final overhead when the command is written in the form
waitcnt(offset + cnt). This
means the value of
T
offset must always be at least 381 to avoid unexpectedly long delays.
Synchronized Delays
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.