How to periodically perform an action using a timer

  • version

    1.1.1

  • scope

    Example.

    This code is provided as example code for a user to base their code on.

  • description

    How to periodically perform an action using a timer

  • boards

    Unless otherwise specified, this example runs on the SliceKIT Core Board, but can easily be run on any XMOS device by using a different XN file.

Timers can be used to periodically perform an action. First input the current time from the timer:

t :> time;

The following loop uses the timerafter predicate to print a message once a second 100 times:

for (int i = 0; i < 100; i++) {
  t when timerafter(time) :> void;
  time += XS1_TIMER_MHZ * 1000 * 1000;
  printstr("This message is printed once a second\n");
}

If you want to periodically perform an action while also responding to other events, you can use a loop containing a select statement:

for (int i = 0; i < 100; i++) {
  select {
  case t when timerafter(time) :> void:
    time += XS1_TIMER_MHZ * 1000 * 1000;
    printstr("This message is printed once a second\n");
    break;
  // Insert cases to handle other events here...
  }
}

Note in the above examples the time input from the timer is discarded in the loop by inputting it to void. To see why this form is the preferred solution, suppose you had instead written the following:

for (int i = 0; i < 100; i++) {
  t when timerafter(time) :> time;
  time += XS1_TIMER_MHZ * 1000 * 1000;
  printstr("This message is printed once a second\n");
}

Because the processor completes the input shortly after the time specified is reached, the input in the loop may actually increment the value of time by a small amount. This amount may be compounded over multiple loop iterations, leading to drift over time.