64 of 172
ZBasic Language Reference 57 ZX Microcontroller Family your application might benefit from being divided into tasks, it is simple to define them. Each task has two core elements: a task main routine and a task stack. The task main routine is the (usually parameterless) subroutine with which the task begins execution. The task stack is a portion of RAM set aside exclusively for the task. The example below shows how to define a task stack and how to activate a second task. Dim taskStack(1 to 80) as Byte Sub Main() CallTask "MyTask", taskStack Do Debug.Print "Hello from Main" Call Delay(1.0) Loop End Sub Sub MyTask() Do Debug.Print "Hello from MyTask" Call Delay(2.0) Loop End Sub This simple program has two tasks: Main and MyTask. The Main task is created automatically for you and its task stack is automatically allocated all of the remaining User RAM after explicitly defined variables are allocated. In contrast, additional tasks such as MyTask have to be explicitly invoked using the CallTask statement and each task’s stack must also be explicitly allocated, for example by defining a Byte array as shown above. A task is said to be “active” if it has been invoked by CallTask and has not yet terminated. Both of the tasks above never terminate so they are always active. The example below shows a situation where a task terminates. Dim taskStack(1 to 50) as Byte Sub Main() CallTask "MyTask", taskStack Do Debug.Print "Hello from Main" Call Delay(1.0) Loop End Sub Sub MyTask() Dim i as Integer For i = 1 to 5 Debug.Print "Hello from MyTask" Call Delay(2.0) Next i End Sub In this example, the task MyTask will output the message 5 times and then terminate. After the task terminates, its task stack could be used for another task. It is important to note that tasks cannot use the same task stack if they will be active at the same time. The examples above were chosen because they clearly illustrate, when executed, that the separate tasks experience interleaved execution. A more realistic example is shown (necessarily incompletely) below. Dim taskStack(1 to 50) as Byte Sub Main() CallTask "MyTask", taskStack Do <other-important-stuff>