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)
  if (ms_counter % 20 == 0) {
    passed_20ms = true;

  passed_1ms = true;


  // configure timer to trigger an interrupt every 1ms

  while(true) {
    if (passed_1ms) {
      // 1ms has passed, do something
      passed_1ms = false;
    if (passed_20ms) {
      // 20ms tasks go here
      passed_20ms = false;
    // Do other tasks
  • \$\begingroup\$ +1 It's also possible to perform the task inside the ISR, but for complex tasks such as computing PID, where a bit of jitter in starting the routine is acceptable, Tom's method (set a flag, poll the flag and perform the function outside the ISR) is best. One reason for doing that is that some library routines may not be re-entrant. There are other good reasons. \$\endgroup\$ – Spehro Pefhany Jul 4 '15 at 20:17
  • \$\begingroup\$ I highly recommend this approach for about every application except when hard real time requirements are required. Always keep your ISRs short and do only what's absolutely necessary. For hard real time requirements you will need to look at different approaches such as performing the calculation inside the ISR (then make sure you know how long this takes in the worst case) or assign priorities as well. Basically this is part of what a scheduler would do, just rather simple. \$\endgroup\$ – Tom L. Jul 5 '15 at 9:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.