*'''Note: The following has been copied from various posts from the following thread: http://www.vexforum.com/showthread.php?t=53551'''

+

<br />

RobotC’s ability to run more than one task is IMHO it’s greatest strength, there has been lot’s written describing multi-tasking in it’s different forms but when dealing with RobotC I like to think of it as the ability to run more than one independent program at a time even though these programs are contained within one executable and downloaded together. For some background reading on multi-tasking, wikipedia is not a bad place to start. http://en.wikipedia.org/wiki/Computer_multitasking.

RobotC’s ability to run more than one task is IMHO it’s greatest strength, there has been lot’s written describing multi-tasking in it’s different forms but when dealing with RobotC I like to think of it as the ability to run more than one independent program at a time even though these programs are contained within one executable and downloaded together. For some background reading on multi-tasking, wikipedia is not a bad place to start. http://en.wikipedia.org/wiki/Computer_multitasking.

The difficulty in creating a simple multi-tasking example is that almost everything proposed can be done without using multi-tasking, however, just to illustrate the principles involved we will create a very simple piece of code to flash two leds on and off connected to different output ports.

The difficulty in creating a simple multi-tasking example is that almost everything proposed can be done without using multi-tasking, however, just to illustrate the principles involved we will create a very simple piece of code to flash two leds on and off connected to different output ports.

Line 155:

Line 162:

|}

|}

<br />

<br />

−

== Part 2 ==

== Part 2 ==

−

OK, part 2 then I need to do some real work today. This may be a little complex for some here but please don't feel intimidated, it's good to see a more fully developed example once in a while.

+

{{tip-from-author

+

|name=jpearman

+

|link=http://www.vexforum.com/showpost.php?p=225727&postcount=25

+

}}

+

<br />

The previous post contained a very simple example demonstrating RobotC multi-tasking that would flash two LEDs at different speeds, not very exciting but actually useful in some cases. The task, flashLed_1, will keep executing no matter what other code you are running. Perhaps the robot is under driver control, LED_1 keeps flashing, perhaps following a line in autonomous mode, LED_1 keeps flashing. Why it’s flashing I have no idea, perhaps bad battery, that’s up to the programmer.

The previous post contained a very simple example demonstrating RobotC multi-tasking that would flash two LEDs at different speeds, not very exciting but actually useful in some cases. The task, flashLed_1, will keep executing no matter what other code you are running. Perhaps the robot is under driver control, LED_1 keeps flashing, perhaps following a line in autonomous mode, LED_1 keeps flashing. Why it’s flashing I have no idea, perhaps bad battery, that’s up to the programmer.

Line 378:

Line 388:

This is the main task and entry point for the program. The “MotorSlewRateTask” is started, the “ArcadeDrive” is started and then it enters a loop that does nothing. All control is handled by the other two tasks. Implementing main in this fashion allows the code to be moved into the competition template easily, to enter driver control simply start the two other tasks.

This is the main task and entry point for the program. The “MotorSlewRateTask” is started, the “ArcadeDrive” is started and then it enters a loop that does nothing. All control is handled by the other two tasks. Implementing main in this fashion allows the code to be moved into the competition template easily, to enter driver control simply start the two other tasks.

+

== Part 3 ==

+

{{tip-from-author

+

|name=jpearman

+

|link=http://www.vexforum.com/showpost.php?p=226282&postcount=28

+

}}

+

<br />

+

Consider a group of students sitting around a table having a discussion with their teacher. If a student wants to speak then they have to raise their hand and wait for the teacher to give them permission. If several students have their hands raised the teacher will choose each one in turn so everyone can be heard. Some students may want to speak often and keep raising their hands, others may be sleepy and not participate much at all. The teacher is also watching a clock, if a student speaks for too long then the teacher will interrupt them and give someone else a turn. At one point the school principle joins the debate, he also has to raise his hand to be able to speak but, as he is considered more important, the teacher always gives him priority.

+

+

This analogy describes quite well how the RobotC task scheduler works. The task scheduler (the teacher in my example) determines which task (student) can run. The principle represents a high priority task that has precedence over the others. When several tasks of the same priority want to run the scheduler chooses them in turn. If a task continues running too long then the scheduler stops it and gives time to others.

+

+

To show how this works in practice I’m going to use a modified version of the code presented a couple of posts back that flashes two LEDs. I’ve modified the code a little so that everything happens much faster and we can observe the signal going to the LEDs on an oscilloscope. An oscilloscope lets us look at the level of a signal (it’s voltage) over time and creates a graphical representation. More background on oscilloscopes is here http://en.wikipedia.org/wiki/Oscilloscope.

+

+

Here’s the test code we will use, very similar to before but the while loops only wait for 1mS and 2mS respectively.<br />

If we observe the digital outputs on the scope we see the following, the value of LED_1 is shown by the yellow trace, LED_2 the blue. LED_1 is changing state every 1mS, LED_2 is changing state every 2mS. This corresponds exactly to the wait1Msec delays we have in the two tasks, each task does it’s thing and then sleeps until woken again by the task scheduler.<br />

+

+

[[File:tips-multitask-1.jpg]]

+

+

+

For the next example we replace the wait1Msec(1) statement in the flashLed_1 task with a different command, AbortTimeSlice. This command hands control back to the task scheduler which then decides if any other tasks are waiting to execute (have their hands up), if none are waiting then control is given back to flashLed_1, lets see this on the scope.<br />

+

+

{|

+

|-

+

|<syntaxhighlight lang="ROBOTC">

+

// Flash the first LED

+

task flashLed_1()

+

{

+

while( true )

+

{

+

// toggle output

+

SensorValue[ LED_1 ] = 1 - SensorValue[ LED_1 ];

+

+

AbortTimeSlice();

+

}

+

}

+

</syntaxhighlight>

+

|}<br />

+

+

[[File:tips-multitask-2.jpg]]

+

+

+

You can observe that LED_1 is now flashing very fast as the only other task we have created is the main task which sleeps for 2mS before wanting to run. Both tasks still operate but the majority of the time is spent running the flashLed_1 task. If you are wondering what the large gap in the yellow trace is, well in the previous post I explained that RobotC already has other tasks running for debugging purposes, this gap occurred when the RobotC task, presumably a more important task, needed to run.

For the next experiment I’m going to delete the AbortTimeSlice command completely and see what the result is, here’s the modified code.<br />

+

+

{|

+

|-

+

|<syntaxhighlight lang="ROBOTC">

+

// Flash the first LED

+

task flashLed_1()

+

{

+

while( true )

+

{

+

// toggle output

+

SensorValue[ LED_1 ] = 1 - SensorValue[ LED_1 ];

+

}

+

}

+

</syntaxhighlight>

+

|}<br />

+

And the waveform showing what the two LEDs are doing.<br />

+

+

[[File:tips-multitask-3.jpg]]

+

+

+

So not much changed but it is different from before. flashLed_1 did not voluntarily give control back to the task scheduler, however, the task scheduler was watching the clock and after a while said enough is enough and let the main task run. LED_2 controlled by the main task is still changing but not as consistently as before.

+

+

One more example for today, lets now make flashLed_1 a more important task, the correct terminology is a higher priority task. We do this by providing a second parameter to the StartTask command in the following way.<br />

+

+

{|

+

|-

+

|<syntaxhighlight lang="ROBOTC">

+

StartTask( flashLed_1, 10 );

+

</syntaxhighlight>

+

|}<br />

+

+

Normal priority tasks are started with a priority of 7, if we provide a number which is higher then that task will have a higher priority (bigger number = more important).

+

+

Here’s the modified code.<br />

+

{|

+

|-

+

|<syntaxhighlight lang="ROBOTC">

+

// Main task - flash the second LED

+

task main()

+

{

+

// Start the other task

+

StartTask( flashLed_1, 10 );

+

+

// Do our own thing

+

while( true )

+

{

+

// toggle output

+

SensorValue[ LED_2 ] = 1 - SensorValue[ LED_2 ];

+

+

wait1Msec( 2 );

+

}

+

}

+

</syntaxhighlight>

+

|}<br />

+

+

And here’s the waveform.

+

+

[[File:tips-multitask-4.jpg]]

+

+

You will notice that the main task (blue waveform) never runs, this is because the higher priority task does not give up control and therefore the task scheduler does not let the less important task run.

+

<br />

+

+

== Part 5 ==

+

{{tip-from-author

+

|name=jpearman

+

|link=http://www.vexforum.com/showpost.php?p=227764&postcount=30

+

}}

+

<br />

+

+

I’m going to conclude this short tutorial on multi tasking with a discussion of the remaining useful RobotC commands relating to tasks.

+

+

We have already used StartTask to start tasks with the default task priority or a user defined priority.

+

+

{|

+

|-

+

|<syntaxhighlight lang="ROBOTC">

+

StartTask( taskName );

+

+

StartTask( taskName, priority );

+

</syntaxhighlight>

+

|}<br />

+

+

We looked at how abortTimeslice ( and EndTimeSlice ) affect the way tasks run. Although I did not specifically discuss wait1Msec, it’s importance in allowing the task scheduler to switch between tasks was demonstrated.

+

+

The following commands will be used less frequently.

+

+

{|

+

|-

+

|<syntaxhighlight lang="ROBOTC">

+

StopAllTasks();

+

</syntaxhighlight>

+

|}<br />

+

+

This does what it’s name implies, stop all tasks from running including the main task. Not sure what the use of this really is other to terminate the program.

+

+

{|

+

|-

+

|<syntaxhighlight lang="ROBOTC">

+

StopTask( taskName );

+

</syntaxhighlight>

+

|}<br />

+

+

A bit more useful, stop the named task.

+

+

{|

+

|-

+

|<syntaxhighlight lang="ROBOTC">

+

hogCPU();

+

releaseCPU();

+

</syntaxhighlight>

+

|}<br />

+

+

The hogCPU command tells the task scheduler that the current task requires exclusive use of the cpu until either a releaseCPU call is made or the task sleeps. I don’t see the need for this in “normal” competition software, it can be used to stop the task scheduler switching tasks in the middle of time critical processing but, as it does not stop the RobotC background tasks from running, even that use is marginal.

+

+

{|

+

|-

+

|<syntaxhighlight lang="ROBOTC">

+

getTaskPriority( taskName );

+

setTaskPriority( taskName, newPriority );

+

</syntaxhighlight>

+

|}<br />

+

+

Use these to get and set the task priority for a currently running task. As above, I’m not sure these have much use during “normal” competition programming.

+

+

Before concluding I wanted to discuss briefly how long tasks should sleep in their processing loop. The cortex is running a form of Real Time Operating System, (RTOS), however, real time operation of every task is an illusion as the cortex can in fact only do one thing at a time. The concept of real time is very flexible, when a button is pressed on the joystick to make an action happen, for example a motor running or stopping, how fast this has to happen and whether it is considered real time is purely from the perspective of the operator. For this type of action 0.1 seconds has been used as a rule of thumb in many situations and would imply that checking joystick buttons needs to happen no faster than perhaps twice this speed, say every 50mS. The point I’m trying to make is that most tasks do not need to run that often and can spend most of their time sleeping. Updating motors or checking sensors any more than 50 to 100 times a second is not necessary so an average task can have wait1Msec(20) at the end of the processing loop without any issues.

Contents

RobotC’s ability to run more than one task is IMHO it’s greatest strength, there has been lot’s written describing multi-tasking in it’s different forms but when dealing with RobotC I like to think of it as the ability to run more than one independent program at a time even though these programs are contained within one executable and downloaded together. For some background reading on multi-tasking, wikipedia is not a bad place to start. http://en.wikipedia.org/wiki/Computer_multitasking.

Some will argue that most programs written for the VEX robotics system do not need to use multi-tasking. This to a certain extent is true, back when micro processors were not so powerful much embedded software used a technique where the “tasks”, in this case simply meaning different subroutines, were called one after the other in a so called “main loop”. Each subroutine would determine if it had any actions to take, perform them if necessary and then return. System functions needing immediate attention would be setup to use interrupts but great care had to be taken to make these special interrupt routines fast and efficient. Having said this some of the most complex embedded systems of the 60’s did use a primitive form of multi-tasking, one of the most famous of all was the Apollo guidance computer (AGC), which enabled NASA to land on the moon.

RobotC is, in fact, always using multi-tasking even when you have not created additional tasks yourself. It’s ability to display global variables, sensor values and other parameters is achieved using tasks that are started behind the scenes. These tasks only consume a small amount of the microcontrollers resources, perhaps 5%. We are not going to be concerned with how RobotC switches between tasks for now, perhaps a future post.

Part 1

The difficulty in creating a simple multi-tasking example is that almost everything proposed can be done without using multi-tasking, however, just to illustrate the principles involved we will create a very simple piece of code to flash two leds on and off connected to different output ports.

RobotC always needs a main task, this is the entry point for the code, it’s the equivalent of the main function in any C program. From the main task we will start a second task using the StartTask command with a single parameter, the name of the task to start. The call to start the second task is:

StartTask( flashLed_1 );

Both the main and flashLed_1 tasks contain an infinite while loop, that is, a loop that never exits until the program is stopped. This loop prevents the tasks from running out of code to execute and therefore stopping. Sometimes allowing a task to finish can be useful but in general I would not recommend it, perhaps we will cover starting and stopping tasks dynamically in another post.

The contents of the while loop of each task is very similar, change the value on the output port and then wait for a preset amount of time, change the output port value back and then wait some more.

The code also includes another example of using the C preprocessor discussed in an earlier post.

#if(_TARGET == "Emulator")

This line is testing to see if the code is running on real hardware or on the PC emulator. The PC emulator can be very usefull but does not simulate real sensors, to overcome this in the example we substitute the real sensors for an array of integers by using a definition. If the code is compiled for a real cortex then

#define SENSOR SensorValue

will be used, otherwise if running on the PC Emulator a different definition is used and an array

If the tasks that you are running do not have ant wait time in them, i.e Wait1Msec(x), then the tasks might not execute properly. When you are not absolutely sure that a task will include wait time, then you must include this command somewhere in the while loop of your task so that it es executed on every iteration: endTimeSlice(); For example:

task flashLed1(){while(true){SensorValue[LED1] = 0;
wait1Msec(500);
SensorValue[LED1] = 0;
wait1Msec(500);
}}//There is no endTimeSlice() needed here because the task always waits//no matter whattask flashLed2(){while(true){if(SensorValue[button1]){SensorValue[LED1] = 0;
wait1Msec(500);
SensorValue[LED1] = 0;
wait1Msec(500);
}
endTimeSlice();
}}//This task needs a endTimeSlice() because if the button is not pressed,//then there will be no wait time in the tasktaskmain(){StartTask(flashLed1);
StartTask(flashLed2);
while(true){motor[port3] = vexRT[Ch3];
endTimeslice();
}}//The command is also needed in the main task here because the//main task does not wait in the while loop.

Part 2

The previous post contained a very simple example demonstrating RobotC multi-tasking that would flash two LEDs at different speeds, not very exciting but actually useful in some cases. The task, flashLed_1, will keep executing no matter what other code you are running. Perhaps the robot is under driver control, LED_1 keeps flashing, perhaps following a line in autonomous mode, LED_1 keeps flashing. Why it’s flashing I have no idea, perhaps bad battery, that’s up to the programmer.

(one caveat here, when using the competition template, RobotC will stop all tasks started in Autonomous mode before entering driver control mode. You need to restart tasks you may want in both phases).

Now for a more complex example, hopefully not too complex but programmers of all abilities are presumably reading the forums.

One thing that I see that always worries me when students are doing motor control is that motors are being switched from full speed forwards to full speed backwards instantaneously. I’ve never seen any damage resulting from this, and I’m sure VEX has designed the motors to handle this stress, but it worries me all the same. To circumvent this situation we are going to use multi-tasking to implement a controlled acceleration and deceleration of the motors, I call this slew rate control, but it goes by other names as well.

To achieve this we will use an intermediate variable to hold the requested speed of the motor and a task to gradually change the current speed of the motor until it reaches the requested speed. As there can be up to 10 motors connected to the cortex microcontroller we need to track this for all 10 motors. We may not want the same acceleration and deceleration for all motors so we will also have a variable for each motor that determines how fast each one can change.

A bunch of definitions used by the task controlling acceleration and deceleration. An array, motorReq, to hold the requested speed for each motor. An array, motorSlew, to hold the change in speed for each motor each time we check it:

This is the task that sends new speeds to each motor. The code before the while statement initializes the variables to a known state. Within the while loop there is a for loop that iterates through each motor. The current motor speed is compared to the requested speed and incremented or decremented as necessary. The motor speed is limited to the exact speed requested and then sent to the motor. The task having checked each motor then goes to sleep for a defined time (15mS in this case) before being woken up again by the RobotC task scheduler.

This is the main task and entry point for the program. The “MotorSlewRateTask” is started, the “ArcadeDrive” is started and then it enters a loop that does nothing. All control is handled by the other two tasks. Implementing main in this fashion allows the code to be moved into the competition template easily, to enter driver control simply start the two other tasks.

Part 3

Consider a group of students sitting around a table having a discussion with their teacher. If a student wants to speak then they have to raise their hand and wait for the teacher to give them permission. If several students have their hands raised the teacher will choose each one in turn so everyone can be heard. Some students may want to speak often and keep raising their hands, others may be sleepy and not participate much at all. The teacher is also watching a clock, if a student speaks for too long then the teacher will interrupt them and give someone else a turn. At one point the school principle joins the debate, he also has to raise his hand to be able to speak but, as he is considered more important, the teacher always gives him priority.

This analogy describes quite well how the RobotC task scheduler works. The task scheduler (the teacher in my example) determines which task (student) can run. The principle represents a high priority task that has precedence over the others. When several tasks of the same priority want to run the scheduler chooses them in turn. If a task continues running too long then the scheduler stops it and gives time to others.

To show how this works in practice I’m going to use a modified version of the code presented a couple of posts back that flashes two LEDs. I’ve modified the code a little so that everything happens much faster and we can observe the signal going to the LEDs on an oscilloscope. An oscilloscope lets us look at the level of a signal (it’s voltage) over time and creates a graphical representation. More background on oscilloscopes is here http://en.wikipedia.org/wiki/Oscilloscope.

Here’s the test code we will use, very similar to before but the while loops only wait for 1mS and 2mS respectively.

If we observe the digital outputs on the scope we see the following, the value of LED_1 is shown by the yellow trace, LED_2 the blue. LED_1 is changing state every 1mS, LED_2 is changing state every 2mS. This corresponds exactly to the wait1Msec delays we have in the two tasks, each task does it’s thing and then sleeps until woken again by the task scheduler.

For the next example we replace the wait1Msec(1) statement in the flashLed_1 task with a different command, AbortTimeSlice. This command hands control back to the task scheduler which then decides if any other tasks are waiting to execute (have their hands up), if none are waiting then control is given back to flashLed_1, lets see this on the scope.

You can observe that LED_1 is now flashing very fast as the only other task we have created is the main task which sleeps for 2mS before wanting to run. Both tasks still operate but the majority of the time is spent running the flashLed_1 task. If you are wondering what the large gap in the yellow trace is, well in the previous post I explained that RobotC already has other tasks running for debugging purposes, this gap occurred when the RobotC task, presumably a more important task, needed to run.

So not much changed but it is different from before. flashLed_1 did not voluntarily give control back to the task scheduler, however, the task scheduler was watching the clock and after a while said enough is enough and let the main task run. LED_2 controlled by the main task is still changing but not as consistently as before.

One more example for today, lets now make flashLed_1 a more important task, the correct terminology is a higher priority task. We do this by providing a second parameter to the StartTask command in the following way.

StartTask( flashLed_1, 10);

Normal priority tasks are started with a priority of 7, if we provide a number which is higher then that task will have a higher priority (bigger number = more important).

You will notice that the main task (blue waveform) never runs, this is because the higher priority task does not give up control and therefore the task scheduler does not let the less important task run.

Part 5

I’m going to conclude this short tutorial on multi tasking with a discussion of the remaining useful RobotC commands relating to tasks.

We have already used StartTask to start tasks with the default task priority or a user defined priority.

StartTask( taskName );
StartTask( taskName, priority );

We looked at how abortTimeslice ( and EndTimeSlice ) affect the way tasks run. Although I did not specifically discuss wait1Msec, it’s importance in allowing the task scheduler to switch between tasks was demonstrated.

The following commands will be used less frequently.

StopAllTasks();

This does what it’s name implies, stop all tasks from running including the main task. Not sure what the use of this really is other to terminate the program.

StopTask( taskName );

A bit more useful, stop the named task.

hogCPU();
releaseCPU();

The hogCPU command tells the task scheduler that the current task requires exclusive use of the cpu until either a releaseCPU call is made or the task sleeps. I don’t see the need for this in “normal” competition software, it can be used to stop the task scheduler switching tasks in the middle of time critical processing but, as it does not stop the RobotC background tasks from running, even that use is marginal.

Use these to get and set the task priority for a currently running task. As above, I’m not sure these have much use during “normal” competition programming.

Before concluding I wanted to discuss briefly how long tasks should sleep in their processing loop. The cortex is running a form of Real Time Operating System, (RTOS), however, real time operation of every task is an illusion as the cortex can in fact only do one thing at a time. The concept of real time is very flexible, when a button is pressed on the joystick to make an action happen, for example a motor running or stopping, how fast this has to happen and whether it is considered real time is purely from the perspective of the operator. For this type of action 0.1 seconds has been used as a rule of thumb in many situations and would imply that checking joystick buttons needs to happen no faster than perhaps twice this speed, say every 50mS. The point I’m trying to make is that most tasks do not need to run that often and can spend most of their time sleeping. Updating motors or checking sensors any more than 50 to 100 times a second is not necessary so an average task can have wait1Msec(20) at the end of the processing loop without any issues.