cancel
Showing results for 
Search instead for 
Did you mean: 

Can semaphore in FreeRTOS be used for triggering less than 1ms ?

Alan Tan
Associate II

Hi,

I wish to use FreeRTOS to create task with semaphore to wake up the task for every 2kHz.

I know FreeRTOS timer tick is 1ms (1kHz) the most.

I create a HW timer to interrupt every 2k.

Question, is the semaphore and the task able to be woken up every 2kHz ?

Thanks.

4 REPLIES 4
Jack Peacock_2
Senior III

Yes this is possible if you are careful about interrupts. You will have to assign the HW timer a high priority to ensure it is processed quickly. When you access the semaphore in the ISR be sure to get the wakeup flag status from the FreeRTOS API, and use that flag when exiting the ISR so that your timer task will be scheduled for execution immediately. You need to assign a high priority to the timer task so that it isn't preempted by some other IRQ/task combination.

The task won't execute on exact 2KHz boundaries but *** should be close. Expect some jitter from ISR and RTOS overhead.

Jack Peacock

Thanks for quick response.

Do you aware if there is any sample that i could leverage on? Especially on the part of wake up Flag from FreeRTOS API and exit the ISR ?

Another question on the Tick, i think it is not advisable to change rate from 1000 to 2000 right ?

Jack Peacock_2
Senior III

You don't need to change the tick rate. The key is forcing the task scheduler to run after an interrupt.

void EXTI9_5_IRQHandler(void)
{
	BaseType_t xTaskWokenByPost;				// RTOS task context switch required flag
 
       xSemaphoreGiveFromISR( buf->Flag, &xTaskWokenByPost );
 
       portEND_SWITCHING_ISR( xTaskWokenByPost );              // Check for context switch
}

Above are a few lines that illustrate how to schedule in FreeRTOS after an interrupt. Here a semaphore is used in a GIVE, with the task woken flag used in APIs inside an interrupt handler. At the end of the interrupt FreeRTOS sees from the flag a new task may need to be scheduled since an event changed task status.

Task scheduling doesn't depend entirely on the preemption tick. Any event can request a task schedule change inside an interrupt.

Jack Peacock

Piranha
Chief II

Official FreeRTOS documentation also has such an examples.

https://www.freertos.org/a00124.html

In addition don't miss the tip at the top:

TIP: In many usage scenarios it is faster and more memory efficient to use a direct to task notification instead of a semaphore

https://www.freertos.org/RTOS-task-notifications.html