# Calling a routine every x miliseconds

I'm working on a motion controller using the mbed platform. The idea is to calculate the theoretical position in the move every x milliseconds and then compare it to the actual position from the encoder, the resulting error of which will be subject to PID.

Currently I call the procedure every x milliseconds by using the delay() function at the end of the position calculation routine.

I feel this may not be the best way of doing this. Is there a lower level way of calling the routine with a fixed time step?

Pseudo code:

volatile int ms_counter;
volatile bool passed_1ms;
volatile boole passed_20ms;

(ISR executed every 1 ms through a timer interrupt - platform dependent)
ISR {
ms_counter++;
if (ms_counter % 20 == 0) {
passed_20ms = true;
}

passed_1ms = true;
}

main()
{

// configure timer to trigger an interrupt every 1ms

while(true) {
if (passed_1ms) {
// 1ms has passed, do something
passed_1ms = false;
}
if (passed_20ms) {