Assuming that the scheduler is cooperative and these fragments of code you have posted are somehow called in some "big-loop", then, most non-trivial tasks would typically be implemented as state-machines. Given:
class cElapsedTime
{
cElapsedTime()
{
zero() ;
}
void zero()
{
timestamp = millis() ;
}
bool time()
{
return millis() - m_timestamp ;
}
} ;
enum
{
STATE_A,
STATE_B
} state = STATE_A;
cElapsedTime control_task_delay ;
Then toggle between two states to execute different code blocks after each delay period. By continuously comparing the elapsed time with the current value of _speedVar
, the delay can be changed at any time. If _speedVar
changed from 10 seconds to 5, and elapsed time is 7 seconds, the delayed code will be executed immediatly; if the time is extended, so will the delay:
if( control_task_delay.time() >= _speedVar )
{
switch( state )
{
case STATE_A :
// Some function
control_task_delay.zero() // Restart delay
state = STATE_B ; // Next state
break ;
case STATE_B :
// Some function
control_task_delay.zero() // Restart delay
state = STATE_A ; // Next state
break ;
}
}
It is not clear in your code fragment that the first // Some function
is not identical to the second; perhaps // Some other function
would have clarified? However if they were in fact identical then the code would be simply:
if( control_task_delay.time() >= _speedVar )
{
// Some function
control_task_delay.zero() // Restart delay
}
You can see that it is the same principle you have applied to your UART polling task - using a non-blocking test. That said, there is perhaps no need for separate tasks in any case; you could have:
if( Serial.available() )
{
_speedVar = Serial.read();
}
if( control_task_delay.time() >= _speedVar )
{
switch( state )
{
case STATE_A :
// Some function
control_task_delay.zero() // Restart delay
state = STATE_B ; // Next state
break ;
case STATE_B :
// Some function
control_task_delay.zero() // Restart delay
state = STATE_A ; // Next state
break ;
}
}
It is not clear in your code fragment that the first // Some function
is not identical to the second; perhaps // Some other function
would have clarified? However if they were in fact identical then the code would be simply:
if( control_task_delay.time() >= _speedVar )
{
// Some function
control_task_delay.zero() // Restart delay
}
if( control_task_delay.time() >= _speedVar )
{
switch( state )
{
case STATE_A :
// Some function
control_task_delay.zero() // Restart delay
state = STATE_B ; // Next state
break ;
case STATE_B :
// Some function
control_task_delay.zero() // Restart delay
state = STATE_A ; // Next state
break ;
}
}
It is hard to see what the "scheduler" is achieving in this scenario.