I am going to use the term "yielding" to describe a subroutine that is made in such a way that it "yields" control of the processor, i.e. frees up SPLatty, as soon as it has nothing useful to do. In our multitasking scheme, every subroutine must be yielding. Let's illustrate this with a very simple lamp flasher.
First, here is a program that will flash an output "FlashLight" 500mS on, 500mS off forever, without yielding
FlashTheLight
Test 0 ;Test the timer
GoIfT FlashTheLight ;go if still timing
SetTimer 0,5 ;Restart the timer
InputO FlashLight ;Read back the output
Not ;Reverse the value
Output FlashLight ;Update the output
GoTo FlashTheLight ;Repeat forever
The program uses timer 0. It starts by testing the timer. If it is still timing, it just jumps back and tests again. Once it discovers the timer has timed out, it reads back the output, inverts it (NOT) and sends the inverted value back to the output (hence toggling the output). It then jumps back to the start and repeats the whole process.
I've deliberately not used a Pause instruction, because Pause is verboten in our simple multitasking scheme, and that's where we are heading.
The above program will make a fine light flasher but that's it, that's all you will get. What a shame, using up 100% of SPLatty's capability on something that really should only use up maybe 0.1%!
The following code is a subroutine that will toggle the state of FlashLight every 500mS, but yields as quickly as it can each time it is called.
FlashTheLight
Test 0 ;Test the timer
RetIfT ;Return (yield) if still timing
SetTimer 0,5 ;Restart the timer
InputO FlashLight ;Read back the output
Not ;Reverse the value
Output FlashLight ;Update the output
Return ;Yield
You will notice all I've done is replace the GoTo's with Returns (it's not always that simple, but it's also not much more complicated!). Providing this subroutine is called frequently from a main loop, it will merrily flash the light while taking up very little of SPLatty's time.
I suggest you stop here and make an actual program, complete with a main loop, that flashes a light using this technique. You can get the main loop from the previous section. Run it in SPLat/PC and make yourself quite comfortable with how it works.
In the next section I will introduce some nifty instructions that let SPLatty "bookmark" where he is in a program, so he can go off and do other things and still get back to where he left off.
Special note: This tutorial and the multitasking mechanism it covers have largely been superseded by the newer MultiTrack mechanism. MultiTrack achieves everything and more, with considerably less programming effort. The only time you would use this older multitasking mechanism would be if the controller you are using is unable to handle as many tasks as you need using MultiTrack.