Propeller Manual

Table Of Contents
WAITCNT – Spin Language Reference
Page 220 · Propeller Manual v1.1
Figure 2-3: Fixed Delay Timing
Figure 2-3 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
T
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.
T
CON
_clkfreq = xtal1 'Set for slow crystal
_xinfreq = 5_000_000 'Use 5 MHz accurate crystal
PUB Toggle | Time
Time := cnt 'Get current system counter value
repeat
waitcnt(Time += 50_000) 'Wait for 10 ms
!outa[0] 'Toggle pin 0
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