A semaphore is a protected variable that is used to control access to shared system resources (such as memory or serial ports), to signal the occurrence of events and task synchronization. A task can request a semaphore and wait until the resource or event takes place (called pending). A task can also post to a semaphore to indicate it no longer needs a resource, or to signal an event has taken place. To create a semaphore you declare one of type OS_SEM and initialize with OSSemInit()
: OS_SEM
MySemaphore; OSSemInit( &MySemaphore, 0 ); // set initial value to 0
Your application tasks can now use the post and pend functions on the semaphore: OSSemPost( &MySemaphore ); // post to a semaphore
OSSemPend( &MySemaphore, 0 ); // pend on a semaphore
The second parameter in the OSSemPend()
function specifies the number of time ticks to wait. A value of 0 waits forever. A good way to express a wait value is to use the TICKS_PER_SECOND definition provided by the RTOS: OSSemPend( &MySemaphore, TICKS_PER_SECOND * 5)
to wait 5 seconds.