xTaskGetTickCount

I repeatedly run into the problem of trying to use xTaskGetTickCount within an interrupt (actually I’m trying to use some other code that sets up a timer) but this crashes the system because of the critical section. Rather than writing an interrupt safe version that does not use a critical section, would this be a possible solution? Instead of: portTickType xTaskGetTickCount( void )
{
portTickType xTicks; /* Critical section required if running on a 16 bit processor. */
taskENTER_CRITICAL();
{
xTicks = xTickCount;
}
taskEXIT_CRITICAL(); return xTicks;
} do: portTickType xTaskGetTickCount( void )
{
portTickType xTicks; do {
xTicks = xTickCount;
} while (xTicks != xTickCount); return xTicks;
} The loop will repeat if xTickCount is updated while it is being read. Since xTickCount is declared as volatile, the loop condition should not be optimised away by the compiler.

xTaskGetTickCount

I’m surprised that no one else seems to have run into the problem with not being able to use xTaskGetTickCount in interrupts. For example what if you want to put a timestamp on some received data? Or what if you want to record the last time a particular interrupt was raised? At present it is not possible. I imagine that fixing this issue would stop one or two “why does my project keep crashing” posts in this forum because it is not immediately obvious that this function cannot be used in an interrupt.

xTaskGetTickCount

There are two simple mods to get around the problem, one is to add a function xTaskGetTickCountFromISR function that just return xTickCount, the second is remove the static qualifier on the declaration of xTickCount and just access the variable in the ISR.

xTaskGetTickCount

Calling vTaskSetTimeOutState() will also allow you access to the tick count, but indirectly.

xTaskGetTickCount

richard_damon: sure, it’s easy to get to the information if one patches the FreeRTOS source. However I prefer not to do this sort of thing for a number of reasons, e.g. it makes upgrading more difficult. It would be better if the original FreeRTOS source would provide a function that works in both cases (no patches necessary and no “interrupt version” that must be used in interrupts otherwise a crash results). I believe my version of the function would be one way to achieve this and using a loop to check if an update occurred while reading might even be more efficient than the critical section. It is also a method not seldomly used in embedded systems for checking if updates occur while reading peripherals (e.g. when reading a 16 bit running timer on an 8 bit processor). davedoors: interesting tip but this does not appear to be part of the FreeRTOS API so might not be available in this form in future versions.