3 years, 3 months ago.

High frequency, time critical operation best-practice/pattern?

Maybe I am missing something, but was wondering about the "right" way to run, say, a spi transaction at 10 thousands times per second rate.

By not using RTOS, I lose scheduler usefulness.

By using a microseconds driven Ticker, I can't use SPI class at all, since mutex locking is not allowed in ISR context.

By using an EventQueue, I can't schedule anything with an interval shorter than a millisecond.

Any other options?

Thanks!

1 Answer

3 years, 2 months ago.

Hello Lorenzo,

I would try to use a Ticker to flag that a transaction has been requested. For example as below:

#include "mbed.h"

#define INTERVAL    50
#define COUNT       100

Ticker          ticker;
Timer           timer;
volatile bool   transactionRequested;
volatile int    counter = 0;
uint8_t         delay[COUNT];

void onTick()
{
    timer.reset();
    transactionRequested = true;
}

int main()
{
    counter = 0;
    timer.start();
    ticker.attach_us(callback(onTick), INTERVAL);

    while (counter < COUNT)
    {
        if (transactionRequested)
        {
            delay[counter++] = timer.read_us();
            transactionRequested = false;
            
            // ...
            // ...
            // ...
            
        }
    }

    for (int i = 0; i < COUNT; i++)
        printf("delay[%d] = %dus\r\n", i, delay[i]);
}

The shortest achievable interval could be figured out by applying the try and fail method. Delays longer than the set interval indicate that the requested call interval was not met.

Accepted Answer