Multitasking Tips

From ROBOTC API Guide
Revision as of 20:08, 16 May 2012 by Bfeher (Talk | contribs)

Jump to: navigation, search




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

This tip was posted by jpearman over at http://www.vexforum.com/showpost.php?p=225688&postcount=23. Modified by magicode at: http://www.vexforum.com/showpost.php?p=225688&postcount=24

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

#define SENSOR      SensorValueSimulations
int SensorValueSimulations[kNumbOfRealSensors];


Here is the code to play with, if you try this in the PC emulator look for SensorValueSimulations[8] and SensorValueSimulations[9] changing as these represent the first two digital ports.

In part 2 on multi-tasking we will create a more complex example doing something more relevant to VEX robotics.

#pragma config(Sensor, dgtl1,  LED_1,               sensorDigitalOut)
#pragma config(Sensor, dgtl2,  LED_2,               sensorDigitalOut)
//*!!Code automatically generated by 'ROBOTC' configuration wizard               !!*//
 
// Detect if we are running in PC emulation and switch to
// using a simulation of the sensors as we cannot see the real leds
#if (_TARGET == "Emulator")
#define SENSOR      SensorValueSimulations
int SensorValueSimulations[kNumbOfRealSensors];
#else
#define SENSOR      SensorValue
#endif
 
// Flash the first LED  
task flashLed_1()
{
    while( true )
        {
        // output to 1
        SENSOR[ LED_1 ] = 1;
        wait1Msec( 500 );
 
        // output to 0
        SENSOR[ LED_1 ] = 0;
        wait1Msec( 500 );
        }
}
 
// Main task - flash the second LED
task main()
{
    // Start the other task
    StartTask( flashLed_1 );
 
    // Do our own thing
    while( true )
        {
        // output to 1
        SENSOR[ LED_2 ] = 1;
        wait1Msec( 250 );
 
        // output to 0
        SENSOR[ LED_2 ] = 0;
        wait1Msec( 250 );
        }
}

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 what
 
task 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 task
 
task main(){
  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

This tip was posted by jpearman over at http://www.vexforum.com/showpost.php?p=225727&postcount=25.

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.

OK, a section by section breakdown of the code:

#pragma config(Motor,  port2,           DriveLeft_1,   tmotorNormal, openLoop)
#pragma config(Motor,  port3,           DriveLeft_2,   tmotorNormal, openLoop)
#pragma config(Motor,  port4,           DriveRight_1,  tmotorNormal, openLoop, reversed)
#pragma config(Motor,  port5,           DriveRight_2,  tmotorNormal, openLoop, reversed)

Usual RobotC setup, we have 4 motors, 2 on each side for driving the robot:


/*                                                                             */
/*  definitions used by driver control                                         */
/*                                                                             */
/*-----------------------------------------------------------------------------*/
 
#define     JOY_DRIVE_V     vexJSLeftV
#define     JOY_DRIVE_H     vexJSLeftH
#define     JOY_THRESHOLD   15

definitions used by the arcade driver control:


/*-----------------------------------------------------------------------------*/
/*                                                                             */
/*  definitiona and variables for the motor slew rate controller.              */
/*                                                                             */
/*-----------------------------------------------------------------------------*/
 
#define MOTOR_NUM               kNumbOfTotalMotors
#define MOTOR_MAX_VALUE         127
#define MOTOR_MIN_VALUE         (-127)
#define MOTOR_DEFAULT_SLEW_RATE 10      // Default will cause 375mS from full fwd to rev
#define MOTOR_FAST_SLEW_RATE    256     // essentially off
#define MOTOR_TASK_DELAY        15      // task 1/frequency in mS (about 66Hz)
#define MOTOR_DEADBAND          10
 
// Array to hold requested speed for the motors
int motorReq[ MOTOR_NUM ];
 
// Array to hold "slew rate" for the motors, the maximum change every time the task
// runs checking current mootor speed.
int motorSlew[ MOTOR_NUM ];

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:


/*-----------------------------------------------------------------------------*/
/*                                                                             */
/*  Task  - compares the requested speed of each motor to the current speed    */
/*          and increments or decrements to reduce the difference as nexessary */
/*                                                                             */
/*-----------------------------------------------------------------------------*/
 
task MotorSlewRateTask()
{
    int motorIndex;
    int motorTmp;
 
    // Initialize stuff
    for(motorIndex=0;motorIndex<MOTOR_NUM;motorIndex++)
        {
        motorReq[motorIndex] = 0;
        motorSlew[motorIndex] = MOTOR_DEFAULT_SLEW_RATE;
        }
 
    // run task until stopped
    while( true )
        {
        // run loop for every motor
        for( motorIndex=0; motorIndex<MOTOR_NUM; motorIndex++)
            {
            // So we don't keep accessing the internal storage
            motorTmp = motor[ motorIndex ];
 
            // Do we need to change the motor value ?
            if( motorTmp != motorReq[motorIndex] )
                {
                // increasing motor value
                if( motorReq[motorIndex] > motorTmp )
                    {
                    motorTmp += motorSlew[motorIndex];
                    // limit
                    if( motorTmp > motorReq[motorIndex] )
                        motorTmp = motorReq[motorIndex];
                    }
 
                // decreasing motor value
                if( motorReq[motorIndex] < motorTmp )
                    {
                    motorTmp -= motorSlew[motorIndex];
                    // limit
                    if( motorTmp < motorReq[motorIndex] )
                        motorTmp = motorReq[motorIndex];
                    }
 
                // finally set motor
                motor[motorIndex] = motorTmp;
                }
            }
 
        // Wait approx the speed of motor update over the spi bus
        wait1Msec( MOTOR_TASK_DELAY );
        }
}

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.


void
DriveLeftMotor( int value )
{
    motorReq[ DriveLeft_1 ] = value;
    motorReq[ DriveLeft_2 ] = value;
}
 
void
DriveRightMotor( int value )
{
    motorReq[ DriveRight_1 ] = value;
    motorReq[ DriveRight_2 ] = value;
}

Two intermediate subroutines to control left and right drive of the robot. Instead of send a new value to the motor directly the new speed is written into the variable holding the new requested speed.


task ArcadeDrive()
{
    int    ctl_v;
    int    ctl_h;
    int    drive_l;
    int    drive_r;
 
    // Basic arcade control
    while( true )
        {
        // Get joystick H and V control
        ctl_v = vexRT[ JOY_DRIVE_V ];
        ctl_h = vexRT[ JOY_DRIVE_H ];
 
        // Ignore joystick near center
        if( (abs(ctl_v) <= JOY_THRESHOLD) && (abs(ctl_h) <= JOY_THRESHOLD) )
	        {
	        drive_l = 0;
                drive_r = 0;
	        }
	    else
	        {
                // Create drive for left and right motors
	        drive_l = (ctl_v + ctl_h) / 2;
	    	drive_r = (ctl_v - ctl_h) / 2;
	    	}
 
	    // Now send out to motors
	    DriveLeftMotor( drive_l );
            DriveRightMotor( drive_r );
 
            // don't hog CPU
	    wait1Msec( 25 );
	    }
}

This task controls the robot’s drive, it’s fairly standard arcade drive control, nothing fancy.


task main()
{
    // Start motor slew rate control
    StartTask( MotorSlewRateTask );
 
    // Start driver control tasks
    StartTask( ArcadeDrive );
 
    // Everything done in other tasks
    while( true )
        {
        wait1Msec( 100 );
        }
}

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

This tip was posted by jpearman over at http://www.vexforum.com/showpost.php?p=226282&postcount=28.

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.

#pragma config(Sensor, dgtl1,  LED_1,               sensorDigitalOut)
#pragma config(Sensor, dgtl4,  LED_2,               sensorDigitalOut)
//*!!Code automatically generated by 'ROBOTC' configuration wizard               !!*//
 
// Flash the first LED
task flashLed_1()
{
    while( true )
        {
        // toggle output
        SensorValue[ LED_1 ] = 1 - SensorValue[ LED_1 ];
 
        wait1Msec( 1 );
        }
}
 
// Main task - flash the second LED
task main()
{
    // Start the other task
    StartTask( flashLed_1, 6 );
 
    // Do our own thing
    while( true )
        {
        // toggle output
        SensorValue[ LED_2 ] = 1 - SensorValue[ LED_2 ];
 
        wait1Msec( 2 );
        }
}

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.

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.

// Flash the first LED
task flashLed_1()
{
    while( true )
        {
        // toggle output
        SensorValue[ LED_1 ] = 1 - SensorValue[ LED_1 ];
 
        AbortTimeSlice();
        }
}

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.

Part 4

This tip was posted by jpearman over at http://www.vexforum.com/showpost.php?p=226297&postcount=29.

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

// Flash the first LED
task flashLed_1()
{
    while( true )
        {
        // toggle output
        SensorValue[ LED_1 ] = 1 - SensorValue[ LED_1 ];
        }
}

And the waveform showing what the two LEDs are doing.

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.

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).

Here’s the modified code.

// 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 );
        }
}

And here’s the waveform.

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.