Discussion on using tasks in ROBOTC

So here is some code (no guarantee on this) that synchronizes two tasks with the SPI comms.

#pragma config(Sensor, dgtl9,  test1,          sensorDigitalOut)
#pragma config(Sensor, dgtl10, test2,          sensorDigitalOut)
#pragma config(Sensor, dgtl11, test3,          sensorDigitalOut)
#pragma config(Sensor, dgtl12, testmain,       sensorDigitalOut)
//*!!Code automatically generated by 'ROBOTC' configuration wizard               !!*//

long  spiTimer;

void spiSync()
{
    wait1Msec(1000);
    // Synchronize with spi
    long oldspi = nIfiSPIMsgCounts;
    while( nIfiSPIMsgCounts == oldspi ) {
        ; // block
    }
    // now do it again for safety
    oldspi = nIfiSPIMsgCounts;
    while( nIfiSPIMsgCounts == oldspi ) {
        ; // block
    }
    spiTimer = nSysTime;
}

task task1()
{
    while(1)
      {
      while(1) {
        if( (nSysTime - spiTimer) % 15 >= 8 ) {
          for(int i=0;i<10;i++)
            // do the task work
            SensorValue test1 ] = !SensorValue test1 ];
          break;
        }
        else
          abortTimeslice();
      }
      
      wait1Msec(13);  // somewhere close, but less than, 15
      }
}

task task2()
{
    while(1)
      {
      while(1) {
        if( (nSysTime - spiTimer) % 15 >= 4 ) {
          for(int i=0;i<10;i++)
            // do the task work
            SensorValue test2 ] = !SensorValue test2 ];
          break;
        }
        else
          abortTimeslice();
      }
            
      wait1Msec(13); // somewhere close, but less than, 15
      }
}

task task3()
{
    int oldspi, newspi;
    
    while( true )
        {
        // digi out low
        SensorValue test3 ] = 0;

        // did nIfiSPIMsgCounts change
        newspi = nIfiSPIMsgCounts;
        if( oldspi != newspi )
            SensorValue test3 ] = 1;    

        // note for next time around
        oldspi = newspi;
        
        // next task
        abortTimeslice();            
        }
}

task main()
{
    spiSync();

    startTask( task1 );
    startTask( task2 );    
    startTask( task3 );    

    while(1)
      {
      SensorValue testmain ] = !SensorValue testmain ];
      abortTimeslice();
      }
}

Task1 is synchronized at SPI comms + 8mS
Task2 is synchronized at SPI comms + 4mS
Task3 just shows, by detection, where the SPI comms counter changes.
main is always running so you can see where the SPI comms is occurring.

and the scope capture showing the result. This is for the mentors that have RTOS experience and will understand what is happening here, students, don’t worry about this.