Example12 in Freertos LPC17xx Practical Guide

oahmad2 wrote on Tuesday, April 13, 2010:

I was looking at Example 12 that shows the implementation of using a binary semaphore to synchronize a Task with an Interrupt. 

In the vHandlerTask, it is not clear to me as to why we need to take the semaphore before the infinite loop.  I read the explanation and it is not clear…I would have let it suffice with the ‘forever block’ for xSemaphoreTake inside the infinite loop.

richard_damon wrote on Tuesday, April 13, 2010:

Semaphores start in the “Ready” state, so the first take will automatically succeed. If you didn’t take once outside the loop, then the first time through the loop, the take would succeed, even if the interrupt hasn’t happened yet.

rtel wrote on Tuesday, April 13, 2010:

The binary semaphore can either be ‘full’ or ‘empty’ (hence binary).  When it is full a call to xSemaphoreTake() will pass.  When it is empty a call to xSemaphoreTake() will fail because there is no semaphore to take.

In this example the semaphore is used to signal events, in effect to synchronise a task with an interrupt.  The interrupt gives the semaphore, to make the semaphore full, and in so doing unblocks the task.  The task, once unblocked, takes the semaphore to make the semaphore empty once again.  It then goes around the loop to call xSemaphoreTake() again, at which point it will once again enter the Blocked state to wait for the next interrupt.

However, the semaphore is created to already be in the full state.  If the task did not take the semaphore before entering the infinite loop the first call to xSemaphoreTake() would therefore pass - even though no interrupts had yet occurred.  The first call to xSemaphoreTake() (outside the loop) ensures the semaphore is empty before the infinite loop is entered - the semaphore should be empty because no interrupts have yet occurred.  Now the first call to xSemaphoreTake() will cause the task to enter the Blocked state, because the semaphore is already empty.

Hope this helps your understanding and does not cloud it even more :o)


rtel wrote on Tuesday, April 13, 2010:

Now why did I feel the need to write four paragraphs, when richard_damon managed to say the same thing in two lines?

oahmad2 wrote on Tuesday, April 13, 2010:

It is crystal clear now. Thanks for taking the time to explain!