Page 47 - Designing Autonomous Mobile Robots : Inside the Mindo f an Intellegent Machine
P. 47
Chapter 3
SR0EXIT:LD (SP0),SP
LD SP,(SPMAIN0)
POP IX
POP BC ;Restore registers
POP DE
POP HL
RETI ;Restore interrupts & exit.
;
;------------------------------------------
Figure 3.4. Simple multitasking serial input routine coded for the Z-180 family
Figure 3.3 demonstrates just how simple a context switching can really be. The
“looking glass” is the middle of the diagram. To the main program thread, the se-
quence on the left side of the figure looks like an ordinary serial interrupt. To the
communications program thread, the sequence on the right side of the diagram looks
like an ordinary subroutine. The communications thread will look like any ordinary
program which calls the Get Character routine whenever it needs input. This is the
magic routine referenced in Figure 3.2! In addition to making programs easy to code,
not a single cycle of the CPU is wasted waiting for the serial character to come in!
The example of Figure 3.3 is shown coded in humble Z-80/Z-180 code in Figure 3.4.
Unlike a conventional serial interrupt routine, the communications thread that calls
Get Character maintains its context. That is to say that it can ask for a character until
it sees the beginning of an incoming message, and then repeatedly ask for characters
it expects to see if the message is valid as shown in Figure 3.2. If a complete message
is received, or if invalid characters are received, it will loop back to looking for the
beginning of the next incoming message. It looks like an ordinary single threaded
program, but it only runs when new data arrives and releases the processor when it
has processed that data and needs more.
Now if you have digested this bit of trickery, consider that the left half of the dia-
gram does not necessarily represent an interrupt that occurs when the main thread is
executing. The fact is it doesn’t matter whether the main thread is executing, or
another interrupt, or another independent thread. Context switching is entirely
stack-based and therefore indifferent to sequence. Note, however, that the stack-
pointers must be kept in dedicated memory storage that is reserved for this single
event so that they may be restored during a context switch.
Note also that the stack pointers for all threads must be initialized to point at the
top of their respective stacks before interrupts are enabled. Also note the initializa-
tion program must push the starting address for each thread onto its respective stack
30

