D Programming/RTAI/LXRT

To make the task timing with RTAI you have two possibilities

  • periodic timer mode
  • oneshot timer mode

You can read about this in An overview of RTAI schedulers. To show the differences:

periodic mode
The 8254 chip is used. It runs with a fixed frequency of 1193180 Hz. If you want to make a cyclic event for 1 kHz, it can set the timer period to 100 µs. In the cyclic task always call an rt_sleep_until() with the next time. The result is 1 kHz task with jitter of 100 µs.
oneshot mode
The internal clock goes with the cpu clock. For each timer event, RTAI has to reprogram the timer for the next event. This is an overhead, but has the advantage of highest time resolution.

To make a cyclic task with LXRT, first create a new thread as usual.

threadHandle = rt_thread_create( &threadFunc )

then implement the thread like this

void threadFunc()
  {
    RT_TASK *handler;
    handler = rt_task_init( 0, 0, 0, 0);
    if (handler==null){
      // error handling
    }    
    rt_allow_nonroot_hrt();
    mlockall(MCL_CURRENT | MCL_FUTURE);
    
    //rt_set_periodic_mode();
    rt_set_oneshot_mode();
    
    RTIME period = nano2count( 1_000_000_000l );
    start_rt_timer(period);
    
    rt_make_hard_real_time();
    RTIME currentTime = rt_get_time_ns();
    while( stopCondition )
    {
      currentTime += period;
      rt_sleep_until( currentTime );
      
      // the work to do ...
    }
    
    stop_rt_timer();
    rt_make_soft_real_time();
    rt_task_delete(handler);
  }

With such setup, you can achieve jitter lessen than 10 µs.