Symbols
loading...
Files
loading...

FreeRTOS library

FreeRTOS is a library defining the following symbols:

Most used functions

Name
Location
Summary
Thread Management **************************** Create a thread and add it to Active Threads and set it to state READY.
Put a Message to a Queue.
Generic Wait Functions ****************************** Wait for Timeout (Time Delay)
Release a Semaphore token
Start the RTOS Kernel with executing the specified thread.
Additional specific APIs to Free RTOS *********** Handles the tick increment
Get the value of the Kernel SysTick timer
Calls the port specific code to raise the privilege.
If xRunningPrivileged is not pdTRUE, calls the port specific code to reset the privilege, otherwise does nothing.
Resume execution of a suspended thread.
Get a Message or Wait for a Message from a Queue.
Suspend execution of a thread.
Wait until a Semaphore token becomes available
Message Queue Management Functions ******************** Create and Initialize a Message Queue
INCLUDE_vTaskDelete must be defined as 1 for this function to be available. See the configuration section for more information. Remove a task from the RTOS real time kernel's management. The task being deleted will be removed from all ready, blocked, suspended and event lists. NOTE: The idle task is responsible for freeing the kernel allocated memory from tasks that have been deleted. It is therefore important that the idle task is not starved of microcontroller processing time if your application makes any calls to vTaskDelete (). Memory allocated by the task code is not automatically freed, and should be freed before the task is deleted. See the demo application file death.c for sample code that utilises vTaskDelete (). Example usage:
void vOtherFunction( void ) { TaskHandle_t xHandle; // Create the task, storing the handle. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); // Use the handle to delete the task. vTaskDelete( xHandle ); }
Resumes scheduler activity after it was suspended by a call to vTaskSuspendAll(). xTaskResumeAll() only resumes the scheduler. It does not unsuspend tasks that were previously suspended by a call to vTaskSuspend(). Example usage:
void vTask1( void * pvParameters ) { for( ;; ) { // Task code goes here. // ... // At some point the task wants to perform a long operation during // which it does not want to get swapped out. It cannot use // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the // operation may cause interrupts to be missed - including the // ticks. // Prevent the real time kernel swapping out the task. vTaskSuspendAll (); // Perform the operation here. There is no need to use critical // sections as we have all the microcontroller processing time. // During this time interrupts will still operate and the real // time kernel tick count will be maintained. // ... // The operation is complete. Restart the kernel. We want to force // a context switch - but there is no point if resuming the scheduler // caused a context switch already. if( !xTaskResumeAll () ) { taskYIELD (); } } }
Semaphore Management Functions ************************* Create and Initialize a Semaphore object used for managing resources
Terminate execution of a thread and remove it from Active Threads.
Obtain the state of any thread.
Suspends the scheduler without disabling interrupts. Context switches will not occur while the scheduler is suspended. After calling vTaskSuspendAll () the calling task will continue to execute without risk of being swapped out until a call to xTaskResumeAll () has been made. API functions that have the potential to cause a context switch (for example, vTaskDelayUntil(), xQueueSend(), etc.) must not be called while the scheduler is suspended. Example usage:
void vTask1( void * pvParameters ) { for( ;; ) { // Task code goes here. // ... // At some point the task wants to perform a long operation during // which it does not want to get swapped out. It cannot use // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the // operation may cause interrupts to be missed - including the // ticks. // Prevent the real time kernel swapping out the task. vTaskSuspendAll (); // Perform the operation here. There is no need to use critical // sections as we have all the microcontroller processing time. // During this time interrupts will still operate and the kernel // tick count will be maintained. // ... // The operation is complete. Restart the kernel. xTaskResumeAll (); } }
Only available when configSUPPORT_DYNAMIC_ALLOCATION is set to 1. xTaskCreateRestricted() should only be used in systems that include an MPU implementation. Create a new task and add it to the list of tasks that are ready to run. The function parameters define the memory regions and associated access permissions allocated to the task. See xTaskCreateRestrictedStatic() for a version that does not use any dynamic memory allocation. Example usage:
// Create an TaskParameters_t structure that defines the task to be created. static const TaskParameters_t xCheckTaskParameters = { vATask, // pvTaskCode - the function that implements the task. "ATask", // pcName - just a text name for the task to assist debugging. 100, // usStackDepth - the stack size DEFINED IN WORDS. NULL, // pvParameters - passed into the task function as the function parameters. ( 1UL | portPRIVILEGE_BIT ),// uxPriority - task priority, set the portPRIVILEGE_BIT if the task should run in a privileged state. cStackBuffer,// puxStackBuffer - the buffer to be used as the task stack. // xRegions - Allocate up to three separate memory regions for access by // the task, with appropriate access permissions. Different processors have // different memory alignment requirements - refer to the FreeRTOS documentation // for full information. { // Base address Length Parameters { cReadWriteArray, 32, portMPU_REGION_READ_WRITE }, { cReadOnlyArray, 32, portMPU_REGION_READ_ONLY }, { cPrivilegedOnlyAccessArray, 128, portMPU_REGION_PRIVILEGED_READ_WRITE } } }; int main( void ) { TaskHandle_t xHandle; // Create a task from the const structure defined above. The task handle // is requested (the second parameter is not NULL) but in this case just for // demonstration purposes as its not actually used. xTaskCreateRestricted( &xRegTest1Parameters, &xHandle ); // Start the scheduler. vTaskStartScheduler(); // Will only get here if there was insufficient memory to create the idle // and/or timer task. for( ;; ); }
Release a Mutex that was obtained by osMutexWait
Wait until a Mutex becomes available
Delete a queue - freeing all the memory allocated for storing of items placed on the queue.
Start or restart a timer.
Timer Management Functions ************************** Create a timer.
It is preferred that the macros xQueueSendFromISR(), xQueueSendToFrontFromISR() and xQueueSendToBackFromISR() be used in place of calling this function directly. xQueueGiveFromISR() is an equivalent for use by semaphores that don't actually copy any data. Post an item on a queue. It is safe to use this function from within an interrupt service routine. Items are queued by copy not reference so it is preferable to only queue small items, especially when called from an ISR. In most cases it would be preferable to store a pointer to the item being queued. Example usage for buffered IO (where the ISR can obtain more than one value per call):
void vBufferISR( void ) { char cIn; BaseType_t xHigherPriorityTaskWokenByPost; // We have not woken a task at the start of the ISR. xHigherPriorityTaskWokenByPost = pdFALSE; // Loop until the buffer is empty. do { // Obtain a byte from the buffer. cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); // Post each byte. xQueueGenericSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWokenByPost, queueSEND_TO_BACK ); } while( portINPUT_BYTE( BUFFER_COUNT ) ); // Now the buffer is empty we can switch context if necessary. Note that the // name of the yield function required is port specific. if( xHigherPriorityTaskWokenByPost ) { portYIELD_FROM_ISR(); } }
Starts the real time kernel tick processing. After calling the kernel has control over which tasks are executed and when. See the demo application file main.c for an example of creating tasks and starting the kernel. Example usage:
void vAFunction( void ) { // Create at least one task before starting the kernel. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL ); // Start the real time kernel with preemption. vTaskStartScheduler (); // Will not get here unless a task calls vTaskEndScheduler () }
It is preferred that the macros xQueueSend(), xQueueSendToFront() and xQueueSendToBack() are used in place of calling this function directly. Post an item on a queue. The item is queued by copy, not by reference. This function must not be called from an interrupt service routine. See xQueueSendFromISR () for an alternative which may be used in an ISR. Example usage:
struct AMessage { char ucMessageID; char ucData[ 20 ]; } xMessage; uint32_t ulVar = 10UL; void vATask( void *pvParameters ) { QueueHandle_t xQueue1, xQueue2; struct AMessage *pxMessage; // Create a queue capable of containing 10 uint32_t values. xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); // Create a queue capable of containing 10 pointers to AMessage structures. // These should be passed by pointer as they contain a lot of data. xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); // ... if( xQueue1 != 0 ) { // Send an uint32_t. Wait for 10 ticks for space to become // available if necessary. if( xQueueGenericSend( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10, queueSEND_TO_BACK ) != pdPASS ) { // Failed to post the message, even after 10 ticks. } } if( xQueue2 != 0 ) { // Send a pointer to a struct AMessage object. Don't block if the // queue is already full. pxMessage = & xMessage; xQueueGenericSend( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0, queueSEND_TO_BACK ); } // ... Rest of task code. }
Receive an item from a queue. The item is received by copy so a buffer of adequate size must be provided. The number of bytes copied into the buffer was defined when the queue was created. Successfully received items are removed from the queue. This function must not be used in an interrupt service routine. See xQueueReceiveFromISR for an alternative that can. Example usage:
struct AMessage { char ucMessageID; char ucData[ 20 ]; } xMessage; QueueHandle_t xQueue; // Task to create a queue and post a value. void vATask( void *pvParameters ) { struct AMessage *pxMessage; // Create a queue capable of containing 10 pointers to AMessage structures. // These should be passed by pointer as they contain a lot of data. xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) ); if( xQueue == 0 ) { // Failed to create the queue. } // ... // Send a pointer to a struct AMessage object. Don't block if the // queue is already full. pxMessage = & xMessage; xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 ); // ... Rest of task code. } // Task to receive from the queue. void vADifferentTask( void *pvParameters ) { struct AMessage *pxRxedMessage; if( xQueue != 0 ) { // Receive a message on the created queue. Block for 10 ticks if a // message is not immediately available. if( xQueueReceive( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) ) { // pcRxedMessage now points to the struct AMessage variable posted // by vATask. } } // ... Rest of task code. }
Signal Management ******************************* Set the specified Signal Flags of an active thread.
Mutex Management ******************************* Create and Initialize a Mutex object
Receive an item from a queue. The item is received by copy so a buffer of adequate size must be provided. The number of bytes copied into the buffer was defined when the queue was created. Successfully received items are removed from the queue. This function must not be used in an interrupt service routine. See xQueueReceiveFromISR for an alternative that can. Example usage:
struct AMessage { char ucMessageID; char ucData[ 20 ]; } xMessage; QueueHandle_t xQueue; // Task to create a queue and post a value. void vATask( void *pvParameters ) { struct AMessage *pxMessage; // Create a queue capable of containing 10 pointers to AMessage structures. // These should be passed by pointer as they contain a lot of data. xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) ); if( xQueue == 0 ) { // Failed to create the queue. } // ... // Send a pointer to a struct AMessage object. Don't block if the // queue is already full. pxMessage = & xMessage; xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 ); // ... Rest of task code. } // Task to receive from the queue. void vADifferentTask( void *pvParameters ) { struct AMessage *pxRxedMessage; if( xQueue != 0 ) { // Receive a message on the created queue. Block for 10 ticks if a // message is not immediately available. if( xQueueReceive( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) ) { // pcRxedMessage now points to the struct AMessage variable posted // by vATask. } } // ... Rest of task code. }
Delay a task for a given number of ticks. The actual time that the task remains blocked depends on the tick rate. The constant portTICK_PERIOD_MS can be used to calculate real time from the tick rate - with the resolution of one tick period. INCLUDE_vTaskDelay must be defined as 1 for this function to be available. See the configuration section for more information. vTaskDelay() specifies a time at which the task wishes to unblock relative to the time at which vTaskDelay() is called. For example, specifying a block period of 100 ticks will cause the task to unblock 100 ticks after vTaskDelay() is called. vTaskDelay() does not therefore provide a good method of controlling the frequency of a periodic task as the path taken through the code, as well as other task and interrupt activity, will effect the frequency at which vTaskDelay() gets called and therefore the time at which the task next executes. See vTaskDelayUntil() for an alternative API function designed to facilitate fixed frequency execution. It does this by specifying an absolute time (rather than a relative time) at which the calling task should unblock. Example usage: void vTaskFunction( void * pvParameters ) { // Block for 500ms. const TickType_t xDelay = 500 / portTICK_PERIOD_MS; for( ;; ) { // Simply toggle the LED every 500ms, blocking between each toggle. vToggleLED(); vTaskDelay( xDelay ); } }
Wait for one or more Signal Flags to become signaled for the current \b RUNNING thread.
INCLUDE_eTaskGetState must be defined as 1 for this function to be available. See the configuration section for more information. Obtain the state of any task. States are encoded by the eTaskState enumerated type.
Receive an item from a queue. It is safe to use this function from within an interrupt service routine. Example usage:
QueueHandle_t xQueue; // Function to create a queue and post some values. void vAFunction( void *pvParameters ) { char cValueToPost; const TickType_t xTicksToWait = ( TickType_t )0xff; // Create a queue capable of containing 10 characters. xQueue = xQueueCreate( 10, sizeof( char ) ); if( xQueue == 0 ) { // Failed to create the queue. } // ... // Post some characters that will be used within an ISR. If the queue // is full then this task will block for xTicksToWait ticks. cValueToPost = 'a'; xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); cValueToPost = 'b'; xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); // ... keep posting characters ... this task may block when the queue // becomes full. cValueToPost = 'c'; xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); } // ISR that outputs all the characters received on the queue. void vISR_Routine( void ) { BaseType_t xTaskWokenByReceive = pdFALSE; char cRxedChar; while( xQueueReceiveFromISR( xQueue, ( void * ) &cRxedChar, &xTaskWokenByReceive) ) { // A character was received. Output the character now. vOutputCharacter( cRxedChar ); // If removing the character from the queue woke the task that was // posting onto the queue cTaskWokenByReceive will have been set to // pdTRUE. No matter how many times this loop iterates only one // task will be woken. } if( cTaskWokenByPost != ( char ) pdFALSE; { taskYIELD (); } }
Create a new task and add it to the list of tasks that are ready to run. Internally, within the FreeRTOS implementation, tasks use two blocks of memory. The first block is used to hold the task's data structures. The second block is used by the task as its stack. If a task is created using xTaskCreate() then both blocks of memory are automatically dynamically allocated inside the xTaskCreate() function. (see http://www.freertos.org/a00111.html). If a task is created using xTaskCreateStatic() then the application writer must provide the required memory. xTaskCreateStatic() therefore allows a task to be created without using any dynamic memory allocation. See xTaskCreateStatic() for a version that does not use any dynamic memory allocation. xTaskCreate() can only be used to create a task that has unrestricted access to the entire microcontroller memory map. Systems that include MPU support can alternatively create an MPU constrained task using xTaskCreateRestricted(). Example usage:
// Task to be created. void vTaskCode( void * pvParameters ) { for( ;; ) { // Task code goes here. } } // Function that creates a task. void vOtherFunction( void ) { static uint8_t ucParameterToPass; TaskHandle_t xHandle = NULL; // Create the task, storing the handle. Note that the passed parameter ucParameterToPass // must exist for the lifetime of the task, so in this case is declared static. If it was just an // an automatic stack variable it might no longer exist, or at least have been corrupted, by the time // the new task attempts to access it. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, &ucParameterToPass, tskIDLE_PRIORITY, &xHandle ); configASSERT( xHandle ); // Use the handle to delete the task. if( xHandle != NULL ) { vTaskDelete( xHandle ); } }
configUSE_TRACE_FACILITY must be defined as 1 in FreeRTOSConfig.h for uxTaskGetSystemState() to be available. uxTaskGetSystemState() populates an TaskStatus_t structure for each task in the system. TaskStatus_t structures contain, among other things, members for the task handle, task name, task priority, task state, and total amount of run time consumed by the task. See the TaskStatus_t structure definition in this file for the full member list. NOTE: This function is intended for debugging use only as its use results in the scheduler remaining suspended for an extended period. Example usage:
// This example demonstrates how a human readable table of run time stats // information is generated from raw data provided by uxTaskGetSystemState(). // The human readable table is written to pcWriteBuffer void vTaskGetRunTimeStats( char *pcWriteBuffer ) { TaskStatus_t *pxTaskStatusArray; volatile UBaseType_t uxArraySize, x; uint32_t ulTotalRunTime, ulStatsAsPercentage; // Make sure the write buffer does not contain a string. pcWriteBuffer = 0x00; // Take a snapshot of the number of tasks in case it changes while this // function is executing. uxArraySize = uxTaskGetNumberOfTasks(); // Allocate a TaskStatus_t structure for each task. An array could be // allocated statically at compile time. pxTaskStatusArray = pvPortMalloc( uxArraySize * sizeof( TaskStatus_t ) ); if( pxTaskStatusArray != NULL ) { // Generate raw status information about each task. uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalRunTime ); // For percentage calculations. ulTotalRunTime /= 100UL; // Avoid divide by zero errors. if( ulTotalRunTime > 0 ) { // For each populated position in the pxTaskStatusArray array, // format the raw data as human readable ASCII data for( x = 0; x < uxArraySize; x++ ) { // What percentage of the total run time has the task used? // This will always be rounded down to the nearest integer. // ulTotalRunTimeDiv100 has already been divided by 100. ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalRunTime; if( ulStatsAsPercentage > 0UL ) { sprintf( pcWriteBuffer, "%s\t\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage ); } else { // If the percentage is zero here then the task has // consumed less than 1% of the total run time. sprintf( pcWriteBuffer, "%s\t\t%lu\t\t<1%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter ); } pcWriteBuffer += strlen( ( char * ) pcWriteBuffer ); } } // The array is no longer needed, free the memory it consumes. vPortFree( pxTaskStatusArray ); } }
Determines if pxTicksToWait ticks has passed since a time was captured using a call to vTaskSetTimeOutState(). The captured time includes the tick count and the number of times the tick count has overflowed. @see https://www.freertos.org/xTaskCheckForTimeOut.html Example Usage:
// Driver library function used to receive uxWantedBytes from an Rx buffer // that is filled by a UART interrupt. If there are not enough bytes in the // Rx buffer then the task enters the Blocked state until it is notified that // more data has been placed into the buffer. If there is still not enough // data then the task re-enters the Blocked state, and xTaskCheckForTimeOut() // is used to re-calculate the Block time to ensure the total amount of time // spent in the Blocked state does not exceed MAX_TIME_TO_WAIT. This // continues until either the buffer contains at least uxWantedBytes bytes, // or the total amount of time spent in the Blocked state reaches // MAX_TIME_TO_WAIT – at which point the task reads however many bytes are // available up to a maximum of uxWantedBytes. size_t xUART_Receive( uint8_t *pucBuffer, size_t uxWantedBytes ) { size_t uxReceived = 0; TickType_t xTicksToWait = MAX_TIME_TO_WAIT; TimeOut_t xTimeOut; // Initialize xTimeOut. This records the time at which this function // was entered. vTaskSetTimeOutState( &xTimeOut ); // Loop until the buffer contains the wanted number of bytes, or a // timeout occurs. while( UART_bytes_in_rx_buffer( pxUARTInstance ) < uxWantedBytes ) { // The buffer didn't contain enough data so this task is going to // enter the Blocked state. Adjusting xTicksToWait to account for // any time that has been spent in the Blocked state within this // function so far to ensure the total amount of time spent in the // Blocked state does not exceed MAX_TIME_TO_WAIT. if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) != pdFALSE ) { //Timed out before the wanted number of bytes were available, // exit the loop. break; } // Wait for a maximum of xTicksToWait ticks to be notified that the // receive interrupt has placed more data into the buffer. ulTaskNotifyTake( pdTRUE, xTicksToWait ); } // Attempt to read uxWantedBytes from the receive buffer into pucBuffer. // The actual number of bytes read (which might be less than // uxWantedBytes) is returned. uxReceived = UART_read_from_receive_buffer( pxUARTInstance, pucBuffer, uxWantedBytes ); return uxReceived; }
configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this function to be available. When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private "notification value", which is a 32-bit unsigned integer (uint32_t). Events can be sent to a task using an intermediary object. Examples of such objects are queues, semaphores, mutexes and event groups. Task notifications are a method of sending an event directly to a task without the need for such an intermediary object. A notification sent to a task can optionally perform an action, such as update, overwrite or increment the task's notification value. In that way task notifications can be used to send data to a task, or be used as light weight and fast binary or counting semaphores. A notification sent to a task will remain pending until it is cleared by the task calling xTaskNotifyWait() or ulTaskNotifyTake(). If the task was already in the Blocked state to wait for a notification when the notification arrives then the task will automatically be removed from the Blocked state (unblocked) and the notification cleared. A task can use xTaskNotifyWait() to [optionally] block to wait for a notification to be pending, or ulTaskNotifyTake() to [optionally] block to wait for its notification value to have a non-zero value. The task does not consume any CPU time while it is in the Blocked state. See http://www.FreeRTOS.org/RTOS-task-notifications.html for details.
Return the number of messages stored in a queue.
Set bits within an event group. This function cannot be called from an interrupt. xEventGroupSetBitsFromISR() is a version that can be called from an interrupt. Setting bits in an event group will automatically unblock tasks that are blocked waiting for the bits. Example usage:
#define BIT_0 ( 1 << 0 ) #define BIT_4 ( 1 << 4 ) void aFunction( EventGroupHandle_t xEventGroup ) { EventBits_t uxBits; // Set bit 0 and bit 4 in xEventGroup. uxBits = xEventGroupSetBits( xEventGroup, // The event group being updated. BIT_0 | BIT_4 );// The bits being set. if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) ) { // Both bit 0 and bit 4 remained set when the function returned. } else if( ( uxBits & BIT_0 ) != 0 ) { // Bit 0 remained set when the function returned, but bit 4 was // cleared. It might be that bit 4 was cleared automatically as a // task that was waiting for bit 4 was removed from the Blocked // state. } else if( ( uxBits & BIT_4 ) != 0 ) { // Bit 4 remained set when the function returned, but bit 0 was // cleared. It might be that bit 0 was cleared automatically as a // task that was waiting for bit 0 was removed from the Blocked // state. } else { // Neither bit 0 nor bit 4 remained set. It might be that a task // was waiting for both of the bits to be set, and the bits were // cleared as the task left the Blocked state. } }
Lists all the current threads, along with their current state and stack usage high water mark.
configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this function to be available. When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private "notification value", which is a 32-bit unsigned integer (uint32_t). A version of xTaskNotify() that can be used from an interrupt service routine (ISR). Events can be sent to a task using an intermediary object. Examples of such objects are queues, semaphores, mutexes and event groups. Task notifications are a method of sending an event directly to a task without the need for such an intermediary object. A notification sent to a task can optionally perform an action, such as update, overwrite or increment the task's notification value. In that way task notifications can be used to send data to a task, or be used as light weight and fast binary or counting semaphores. A notification sent to a task will remain pending until it is cleared by the task calling xTaskNotifyWait() or ulTaskNotifyTake(). If the task was already in the Blocked state to wait for a notification when the notification arrives then the task will automatically be removed from the Blocked state (unblocked) and the notification cleared. A task can use xTaskNotifyWait() to [optionally] block to wait for a notification to be pending, or ulTaskNotifyTake() to [optionally] block to wait for its notification value to have a non-zero value. The task does not consume any CPU time while it is in the Blocked state. See http://www.FreeRTOS.org/RTOS-task-notifications.html for details. eSetBits - The task's notification value is bitwise ORed with ulValue. xTaskNofify() always returns pdPASS in this case. eIncrement - The task's notification value is incremented. ulValue is not used and xTaskNotify() always returns pdPASS in this case. eSetValueWithOverwrite - The task's notification value is set to the value of ulValue, even if the task being notified had not yet processed the previous notification (the task already had a notification pending). xTaskNotify() always returns pdPASS in this case. eSetValueWithoutOverwrite - If the task being notified did not already have a notification pending then the task's notification value is set to ulValue and xTaskNotify() will return pdPASS. If the task being notified already had a notification pending then no action is performed and pdFAIL is returned. eNoAction - The task receives a notification without its notification value being updated. ulValue is not used and xTaskNotify() always returns pdPASS in this case.
size_t xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer );
Queries a stream buffer to see how much free space it contains, which is equal to the amount of data that can be sent to the stream buffer before it is full.
If the notification state of the task referenced by the handle xTask is eNotified, then set the task's notification state to eNotWaitingNotification. The task's notification value is not altered. Set xTask to NULL to clear the notification state of the calling task.
INCLUDE_vTaskDelete must be defined as 1 for this function to be available. See the configuration section for more information. Remove a task from the RTOS real time kernel's management. The task being deleted will be removed from all ready, blocked, suspended and event lists. NOTE: The idle task is responsible for freeing the kernel allocated memory from tasks that have been deleted. It is therefore important that the idle task is not starved of microcontroller processing time if your application makes any calls to vTaskDelete (). Memory allocated by the task code is not automatically freed, and should be freed before the task is deleted. See the demo application file death.c for sample code that utilises vTaskDelete (). Example usage:
void vOtherFunction( void ) { TaskHandle_t xHandle; // Create the task, storing the handle. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); // Use the handle to delete the task. vTaskDelete( xHandle ); }
INCLUDE_uxTaskPriorityGet must be defined as 1 for this function to be available. See the configuration section for more information. Obtain the priority of any task. Example usage:
void vAFunction( void ) { TaskHandle_t xHandle; // Create a task, storing the handle. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); // ... // Use the handle to obtain the priority of the created task. // It was created with tskIDLE_PRIORITY, but may have changed // it itself. if( uxTaskPriorityGet( xHandle ) != tskIDLE_PRIORITY ) { // The task has changed it's priority. } // ... // Is our priority higher than the created task? if( uxTaskPriorityGet( xHandle ) < uxTaskPriorityGet( NULL ) ) { // Our priority (obtained using NULL handle) is higher. } }
INCLUDE_vTaskSuspend must be defined as 1 for this function to be available. See the configuration section for more information. Resumes a suspended task. A task that has been suspended by one or more calls to vTaskSuspend () will be made available for running again by a single call to vTaskResume (). Example usage:
void vAFunction( void ) { TaskHandle_t xHandle; // Create a task, storing the handle. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); // ... // Use the handle to suspend the created task. vTaskSuspend( xHandle ); // ... // The created task will not run during this period, unless // another task calls vTaskResume( xHandle ). //... // Resume the suspended task ourselves. vTaskResume( xHandle ); // The created task will once again get microcontroller processing // time in accordance with its priority within the system. }
Receive an item from a queue without removing the item from the queue. The item is received by copy so a buffer of adequate size must be provided. The number of bytes copied into the buffer was defined when the queue was created. Successfully received items remain on the queue so will be returned again by the next call, or a call to xQueueReceive(). This macro must not be used in an interrupt service routine. See xQueuePeekFromISR() for an alternative that can be called from an interrupt service routine. Example usage:
struct AMessage { char ucMessageID; char ucData[ 20 ]; } xMessage; QueueHandle_t xQueue; // Task to create a queue and post a value. void vATask( void *pvParameters ) { struct AMessage *pxMessage; // Create a queue capable of containing 10 pointers to AMessage structures. // These should be passed by pointer as they contain a lot of data. xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) ); if( xQueue == 0 ) { // Failed to create the queue. } // ... // Send a pointer to a struct AMessage object. Don't block if the // queue is already full. pxMessage = & xMessage; xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 ); // ... Rest of task code. } // Task to peek the data from the queue. void vADifferentTask( void *pvParameters ) { struct AMessage *pxRxedMessage; if( xQueue != 0 ) { // Peek a message on the created queue. Block for 10 ticks if a // message is not immediately available. if( xQueuePeek( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) ) { // pcRxedMessage now points to the struct AMessage variable posted // by vATask, but the item still remains on the queue. } } // ... Rest of task code. }
Clear bits within an event group. This function cannot be called from an interrupt. Example usage:
#define BIT_0 ( 1 << 0 ) #define BIT_4 ( 1 << 4 ) void aFunction( EventGroupHandle_t xEventGroup ) { EventBits_t uxBits; // Clear bit 0 and bit 4 in xEventGroup. uxBits = xEventGroupClearBits( xEventGroup, // The event group being updated. BIT_0 | BIT_4 );// The bits being cleared. if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) ) { // Both bit 0 and bit 4 were set before xEventGroupClearBits() was // called. Both will now be clear (not set). } else if( ( uxBits & BIT_0 ) != 0 ) { // Bit 0 was set before xEventGroupClearBits() was called. It will // now be clear. } else if( ( uxBits & BIT_4 ) != 0 ) { // Bit 4 was set before xEventGroupClearBits() was called. It will // now be clear. } else { // Neither bit 0 nor bit 4 were set in the first place. } }
This is a version of xTaskGetTickCount() that is safe to be called from an ISR - provided that TickType_t is the natural word size of the microcontroller being used or interrupt nesting is either not supported or not being used.
configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this function to be available. When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private "notification value", which is a 32-bit unsigned integer (uint32_t). Events can be sent to a task using an intermediary object. Examples of such objects are queues, semaphores, mutexes and event groups. Task notifications are a method of sending an event directly to a task without the need for such an intermediary object. A notification sent to a task can optionally perform an action, such as update, overwrite or increment the task's notification value. In that way task notifications can be used to send data to a task, or be used as light weight and fast binary or counting semaphores. A notification sent to a task will remain pending until it is cleared by the task calling xTaskNotifyWait() or ulTaskNotifyTake(). If the task was already in the Blocked state to wait for a notification when the notification arrives then the task will automatically be removed from the Blocked state (unblocked) and the notification cleared. A task can use xTaskNotifyWait() to [optionally] block to wait for a notification to be pending, or ulTaskNotifyTake() to [optionally] block to wait for its notification value to have a non-zero value. The task does not consume any CPU time while it is in the Blocked state. See http://www.FreeRTOS.org/RTOS-task-notifications.html for details. eSetBits - The task's notification value is bitwise ORed with ulValue. xTaskNofify() always returns pdPASS in this case. eIncrement - The task's notification value is incremented. ulValue is not used and xTaskNotify() always returns pdPASS in this case. eSetValueWithOverwrite - The task's notification value is set to the value of ulValue, even if the task being notified had not yet processed the previous notification (the task already had a notification pending). xTaskNotify() always returns pdPASS in this case. eSetValueWithoutOverwrite - If the task being notified did not already have a notification pending then the task's notification value is set to ulValue and xTaskNotify() will return pdPASS. If the task being notified already had a notification pending then no action is performed and pdFAIL is returned. eNoAction - The task receives a notification without its notification value being updated. ulValue is not used and xTaskNotify() always returns pdPASS in this case. pulPreviousNotificationValue - Can be used to pass out the subject task's notification value before any bits are modified by the notify function.
INCLUDE_vTaskDelayUntil must be defined as 1 for this function to be available. See the configuration section for more information. Delay a task until a specified time. This function can be used by periodic tasks to ensure a constant execution frequency. This function differs from vTaskDelay () in one important aspect: vTaskDelay () will cause a task to block for the specified number of ticks from the time vTaskDelay () is called. It is therefore difficult to use vTaskDelay () by itself to generate a fixed execution frequency as the time between a task starting to execute and that task calling vTaskDelay () may not be fixed [the task may take a different path though the code between calls, or may get interrupted or preempted a different number of times each time it executes]. Whereas vTaskDelay () specifies a wake time relative to the time at which the function is called, vTaskDelayUntil () specifies the absolute (exact) time at which it wishes to unblock. The constant portTICK_PERIOD_MS can be used to calculate real time from the tick rate - with the resolution of one tick period. Example usage:
// Perform an action every 10 ticks. void vTaskFunction( void * pvParameters ) { TickType_t xLastWakeTime; const TickType_t xFrequency = 10; // Initialise the xLastWakeTime variable with the current time. xLastWakeTime = xTaskGetTickCount (); for( ;; ) { // Wait for the next cycle. vTaskDelayUntil( &xLastWakeTime, xFrequency ); // Perform action here. } }
INCLUDE_vTaskPrioritySet must be defined as 1 for this function to be available. See the configuration section for more information. Set the priority of any task. A context switch will occur before the function returns if the priority being set is higher than the currently executing task. Example usage:
void vAFunction( void ) { TaskHandle_t xHandle; // Create a task, storing the handle. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); // ... // Use the handle to raise the priority of the created task. vTaskPrioritySet( xHandle, tskIDLE_PRIORITY + 1 ); // ... // Use a NULL handle to raise our priority to the same value. vTaskPrioritySet( NULL, tskIDLE_PRIORITY + 1 ); }
INCLUDE_vTaskSuspend must be defined as 1 for this function to be available. See the configuration section for more information. Suspend any task. When suspended a task will never get any microcontroller processing time, no matter what its priority. Calls to vTaskSuspend are not accumulative - i.e. calling vTaskSuspend () twice on the same task still only requires one call to vTaskResume () to ready the suspended task. Example usage:
void vAFunction( void ) { TaskHandle_t xHandle; // Create a task, storing the handle. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); // ... // Use the handle to suspend the created task. vTaskSuspend( xHandle ); // ... // The created task will not run during this period, unless // another task calls vTaskResume( xHandle ). //... // Suspend ourselves. vTaskSuspend( NULL ); // We cannot get here unless another task calls vTaskResume // with our handle as the parameter. }
Return the number of free spaces available in a queue. This is equal to the number of items that can be sent to the queue before the queue becomes full if no items are removed.
TimerHandle_t xTimerCreate( const char * const pcTimerName, TickType_t xTimerPeriodInTicks, UBaseType_t uxAutoReload, void * pvTimerID, TimerCallbackFunction_t pxCallbackFunction ); Creates a new software timer instance, and returns a handle by which the created software timer can be referenced. Internally, within the FreeRTOS implementation, software timers use a block of memory, in which the timer data structure is stored. If a software timer is created using xTimerCreate() then the required memory is automatically dynamically allocated inside the xTimerCreate() function. (see http://www.freertos.org/a00111.html). If a software timer is created using xTimerCreateStatic() then the application writer must provide the memory that will get used by the software timer. xTimerCreateStatic() therefore allows a software timer to be created without using any dynamic memory allocation. Timers are created in the dormant state. The xTimerStart(), xTimerReset(), xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and xTimerChangePeriodFromISR() API functions can all be used to transition a timer into the active state. Example usage: @verbatim #define NUM_TIMERS 5 // An array to hold handles to the created timers. TimerHandle_t xTimers[ NUM_TIMERS ]; // An array to hold a count of the number of times each timer expires. int32_t lExpireCounters[ NUM_TIMERS ] = { 0 }; // Define a callback function that will be used by multiple timer instances. // The callback function does nothing but count the number of times the // associated timer expires, and stop the timer once the timer has expired // 10 times. void vTimerCallback( TimerHandle_t pxTimer ) { int32_t lArrayIndex; const int32_t xMaxExpiryCountBeforeStopping = 10; // Optionally do something if the pxTimer parameter is NULL. configASSERT( pxTimer ); // Which timer expired? lArrayIndex = ( int32_t ) pvTimerGetTimerID( pxTimer ); // Increment the number of times that pxTimer has expired. lExpireCounters[ lArrayIndex ] += 1; // If the timer has expired 10 times then stop it from running. if( lExpireCounters[ lArrayIndex ] == xMaxExpiryCountBeforeStopping ) { // Do not use a block time if calling a timer API function from a // timer callback function, as doing so could cause a deadlock! xTimerStop( pxTimer, 0 ); } } void main( void ) { int32_t x; // Create then start some timers. Starting the timers before the scheduler // has been started means the timers will start running immediately that // the scheduler starts. for( x = 0; x < NUM_TIMERS; x++ ) { xTimers[ x ] = xTimerCreate( "Timer", // Just a text name, not used by the kernel. ( 100 * x ), // The timer period in ticks. pdTRUE, // The timers will auto-reload themselves when they expire. ( void * ) x, // Assign each timer a unique id equal to its array index. vTimerCallback // Each timer calls the same callback when it expires. ); if( xTimers[ x ] == NULL ) { // The timer was not created. } else { // Start the timer. No block time is specified, and even if one was // it would be ignored because the scheduler has not yet been // started. if( xTimerStart( xTimers[ x ], 0 ) != pdPASS ) { // The timer could not be set into the Active state. } } } // ... // Create tasks here. // ... // Starting the scheduler will start the timers running as they have already // been set into the active state. vTaskStartScheduler(); // Should not reach here. for( ;; ); } @endverbatim
Return the thread ID of the current running thread.
Check if the RTOS kernel is already started
Allocate a memory block from a mail
INCLUDE_xTaskAbortDelay must be defined as 1 in FreeRTOSConfig.h for this function to be available. A task will enter the Blocked state when it is waiting for an event. The event it is waiting for can be a temporal event (waiting for a time), such as when vTaskDelay() is called, or an event on an object, such as when xQueueReceive() or ulTaskNotifyTake() is called. If the handle of a task that is in the Blocked state is used in a call to xTaskAbortDelay() then the task will leave the Blocked state, and return from whichever function call placed the task into the Blocked state. There is no 'FromISR' version of this function as an interrupt would need to know which object a task was blocked on in order to know which actions to take. For example, if the task was blocked on a queue the interrupt handler would then need to know if the queue was locked.
A version of uxTaskPriorityGet() that can be used from an ISR.
INCLUDE_xTaskResumeFromISR must be defined as 1 for this function to be available. See the configuration section for more information. An implementation of vTaskResume() that can be called from within an ISR. A task that has been suspended by one or more calls to vTaskSuspend () will be made available for running again by a single call to xTaskResumeFromISR (). xTaskResumeFromISR() should not be used to synchronise a task with an interrupt if there is a chance that the interrupt could arrive prior to the task being suspended - as this can lead to interrupts being missed. Use of a semaphore as a synchronisation mechanism would avoid this eventuality.
configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this function to be available. When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private "notification value", which is a 32-bit unsigned integer (uint32_t). Events can be sent to a task using an intermediary object. Examples of such objects are queues, semaphores, mutexes and event groups. Task notifications are a method of sending an event directly to a task without the need for such an intermediary object. A notification sent to a task can optionally perform an action, such as update, overwrite or increment the task's notification value. In that way task notifications can be used to send data to a task, or be used as light weight and fast binary or counting semaphores. ulTaskNotifyTake() is intended for use when a task notification is used as a faster and lighter weight binary or counting semaphore alternative. Actual FreeRTOS semaphores are taken using the xSemaphoreTake() API function, the equivalent action that instead uses a task notification is ulTaskNotifyTake(). When a task is using its notification value as a binary or counting semaphore other tasks should send notifications to it using the xTaskNotifyGive() macro, or xTaskNotify() function with the eAction parameter set to eIncrement. ulTaskNotifyTake() can either clear the task's notification value to zero on exit, in which case the notification value acts like a binary semaphore, or decrement the task's notification value on exit, in which case the notification value acts like a counting semaphore. A task can use ulTaskNotifyTake() to [optionally] block to wait for a the task's notification value to be non-zero. The task does not consume any CPU time while it is in the Blocked state. Where as xTaskNotifyWait() will return when a notification is pending, ulTaskNotifyTake() will return when the task's notification value is not zero. See http://www.FreeRTOS.org/RTOS-task-notifications.html for details.
Clears the bits specified by the ulBitsToClear bit mask in the notification value of the task referenced by xTask. Set ulBitsToClear to 0xffffffff (UINT_MAX on 32-bit architectures) to clear the notification value to 0. Set ulBitsToClear to 0 to query the task's notification value without clearing any bits.
const char * const pcTimerGetName( TimerHandle_t xTimer ); Returns the name that was assigned to a timer when the timer was created.
void vTimerSetReloadMode( TimerHandle_t xTimer, const UBaseType_t uxAutoReload ); Updates a timer to be either an auto-reload timer, in which case the timer automatically resets itself each time it expires, or a one-shot timer, in which case the timer will only expire once unless it is manually restarted.
UBaseType_t uxTimerGetReloadMode( TimerHandle_t xTimer ); Queries a timer to determine if it is an auto-reload timer, in which case the timer automatically resets itself each time it expires, or a one-shot timer, in which case the timer will only expire once unless it is manually restarted.
TickType_t xTimerGetPeriod( TimerHandle_t xTimer ); Returns the period of a timer.
TickType_t xTimerGetExpiryTime( TimerHandle_t xTimer ); Returns the time in ticks at which the timer will expire. If this is less than the current tick count then the expiry time has overflowed from the current time.
Create a new event group. Internally, within the FreeRTOS implementation, event groups use a [small] block of memory, in which the event group's structure is stored. If an event groups is created using xEventGropuCreate() then the required memory is automatically dynamically allocated inside the xEventGroupCreate() function. (see http://www.freertos.org/a00111.html). If an event group is created using xEventGropuCreateStatic() then the application writer must instead provide the memory that will get used by the event group. xEventGroupCreateStatic() therefore allows an event group to be created without using any dynamic memory allocation. Although event groups are not related to ticks, for internal implementation reasons the number of bits available for use in an event group is dependent on the configUSE_16_BIT_TICKS setting in FreeRTOSConfig.h. If configUSE_16_BIT_TICKS is 1 then each event group contains 8 usable bits (bit 0 to bit 7). If configUSE_16_BIT_TICKS is set to 0 then each event group has 24 usable bits (bit 0 to bit 23). The EventBits_t type is used to store event bits within an event group. Example usage:
// Declare a variable to hold the created event group. EventGroupHandle_t xCreatedEventGroup; // Attempt to create the event group. xCreatedEventGroup = xEventGroupCreate(); // Was the event group created successfully? if( xCreatedEventGroup == NULL ) { // The event group was not created because there was insufficient // FreeRTOS heap available. } else { // The event group was created. }
[Potentially] block to wait for one or more bits to be set within a previously created event group. This function cannot be called from an interrupt. Example usage:
#define BIT_0 ( 1 << 0 ) #define BIT_4 ( 1 << 4 ) void aFunction( EventGroupHandle_t xEventGroup ) { EventBits_t uxBits; const TickType_t xTicksToWait = 100 / portTICK_PERIOD_MS; // Wait a maximum of 100ms for either bit 0 or bit 4 to be set within // the event group. Clear the bits before exiting. uxBits = xEventGroupWaitBits( xEventGroup, // The event group being tested. BIT_0 | BIT_4, // The bits within the event group to wait for. pdTRUE, // BIT_0 and BIT_4 should be cleared before returning. pdFALSE, // Don't wait for both bits, either bit will do. xTicksToWait ); // Wait a maximum of 100ms for either bit to be set. if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) ) { // xEventGroupWaitBits() returned because both bits were set. } else if( ( uxBits & BIT_0 ) != 0 ) { // xEventGroupWaitBits() returned because just BIT_0 was set. } else if( ( uxBits & BIT_4 ) != 0 ) { // xEventGroupWaitBits() returned because just BIT_4 was set. } else { // xEventGroupWaitBits() returned because xTicksToWait ticks passed // without either BIT_0 or BIT_4 becoming set. } }
Delete an event group that was previously created by a call to xEventGroupCreate(). Tasks that are blocked on the event group will be unblocked and obtain 0 as the event group's value.
void *pvTimerGetTimerID( TimerHandle_t xTimer ); Returns the ID assigned to the timer. IDs are assigned to timers using the pvTimerID parameter of the call to xTimerCreated() that was used to create the timer, and by calling the vTimerSetTimerID() API function. If the same callback function is assigned to multiple timers then the timer ID can be used as time specific (timer local) storage. Example usage: See the xTimerCreate() API function example usage scenario.
void vTimerSetTimerID( TimerHandle_t xTimer, void *pvNewID ); Sets the ID assigned to the timer. IDs are assigned to timers using the pvTimerID parameter of the call to xTimerCreated() that was used to create the timer. If the same callback function is assigned to multiple timers then the timer ID can be used as time specific (timer local) storage. Example usage: See the xTimerCreate() API function example usage scenario.
BaseType_t xTimerIsTimerActive( TimerHandle_t xTimer ); Queries a timer to see if it is active or dormant. A timer will be dormant if: 1) It has been created but not started, or 2) It is an expired one-shot timer that has not been restarted. Timers are created in the dormant state. The xTimerStart(), xTimerReset(), xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and xTimerChangePeriodFromISR() API functions can all be used to transition a timer into the active state. Example usage: @verbatim // This function assumes xTimer has already been created. void vAFunction( TimerHandle_t xTimer ) { if( xTimerIsTimerActive( xTimer ) != pdFALSE ) // or more simply and equivalently "if( xTimerIsTimerActive( xTimer ) )" { // xTimer is active, do something. } else { // xTimer is not active, do something else. } } @endverbatim
Kernel Control Functions **************************** Initialize the RTOS Kernel for creating objects.
Allocate a memory block from a memory pool
configUSE_TRACE_FACILITY must be defined as 1 for this function to be available. See the configuration section for more information. Populates a TaskStatus_t structure with information about a task. @xGetFreeStackSpace The TaskStatus_t structure contains a member to report the stack high water mark of the task being queried. Calculating the stack high water mark takes a relatively long time, and can make the system temporarily unresponsive - so the xGetFreeStackSpace parameter is provided to allow the high water mark checking to be skipped. The high watermark value will only be written to the TaskStatus_t structure if xGetFreeStackSpace is not set to pdFALSE; Example usage:
void vAFunction( void ) { TaskHandle_t xHandle; TaskStatus_t xTaskDetails; // Obtain the handle of a task from its name. xHandle = xTaskGetHandle( "Task_Name" ); // Check the handle is not NULL. configASSERT( xHandle ); // Use the handle to obtain further information about the task. vTaskGetInfo( xHandle, &xTaskDetails, pdTRUE, // Include the high water mark in xTaskDetails. eInvalid ); // Include the task state in xTaskDetails. }
Capture the current time for future use with xTaskCheckForTimeOut().
Utility task that simply returns pdTRUE if the task referenced by xTask is currently in the Suspended state, or pdFALSE if the task referenced by xTask is in any other state.
Checks whether or not the processor is privileged.
Lowers the privilege level by setting the bit 0 of the CONTROL register. Bit 0 of the CONTROL register defines the privilege level of Thread Mode. Bit[0] = 0 --> The processor is running privileged Bit[0] = 1 --> The processor is running unprivileged.
Change priority of an active thread.
Get current priority of an active thread.
Pass control to next thread that is in state \b READY.
Delay a task until a specified time
Create and Initialize mail queue
Put a mail to a queue
Get a mail from a queue
Free a memory block from a mail
Delete a Message Queue
void vTaskNotifyGiveFromISR( TaskHandle_t xTaskHandle, BaseType_t *pxHigherPriorityTaskWoken ); configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this macro to be available. When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private "notification value", which is a 32-bit unsigned integer (uint32_t). A version of xTaskNotifyGive() that can be called from an interrupt service routine (ISR). Events can be sent to a task using an intermediary object. Examples of such objects are queues, semaphores, mutexes and event groups. Task notifications are a method of sending an event directly to a task without the need for such an intermediary object. A notification sent to a task can optionally perform an action, such as update, overwrite or increment the task's notification value. In that way task notifications can be used to send data to a task, or be used as light weight and fast binary or counting semaphores. vTaskNotifyGiveFromISR() is intended for use when task notifications are used as light weight and faster binary or counting semaphore equivalents. Actual FreeRTOS semaphores are given from an ISR using the xSemaphoreGiveFromISR() API function, the equivalent action that instead uses a task notification is vTaskNotifyGiveFromISR(). When task notifications are being used as a binary or counting semaphore equivalent then the task being notified should wait for the notification using the ulTaskNotificationTake() API function rather than the xTaskNotifyWait() API function. See http://www.FreeRTOS.org/RTOS-task-notifications.html for more details.
A version of xQueuePeek() that can be called from an interrupt service routine (ISR). Receive an item from a queue without removing the item from the queue. The item is received by copy so a buffer of adequate size must be provided. The number of bytes copied into the buffer was defined when the queue was created. Successfully received items remain on the queue so will be returned again by the next call, or a call to xQueueReceive().
A version of xEventGroupGetBits() that can be called from an ISR.
Create and Initialize a memory pool
Return an allocated memory block back to a specific memory pool
Memory regions are assigned to a restricted task when the task is created by a call to xTaskCreateRestricted(). These regions can be redefined using vTaskAllocateMPURegions(). Example usage:
// Define an array of MemoryRegion_t structures that configures an MPU region // allowing read/write access for 1024 bytes starting at the beginning of the // ucOneKByte array. The other two of the maximum 3 definable regions are // unused so set to zero. static const MemoryRegion_t xAltRegions[ portNUM_CONFIGURABLE_REGIONS ] = { // Base address Length Parameters { ucOneKByte, 1024, portMPU_REGION_READ_WRITE }, { 0, 0, 0 }, { 0, 0, 0 } }; void vATask( void *pvParameters ) { // This task was created such that it has access to certain regions of // memory as defined by the MPU configuration. At some point it is // desired that these MPU regions are replaced with that defined in the // xAltRegions const struct above. Use a call to vTaskAllocateMPURegions() // for this purpose. NULL is used as the task handle to indicate that this // function should modify the MPU regions of the calling task. vTaskAllocateMPURegions( NULL, xAltRegions ); // Now the task can continue its function, but from this point on can only // access its stack and the ucOneKByte array (unless any other statically // defined or shared regions have been declared elsewhere). }
NOTE: This function takes a relatively long time to complete and should be used sparingly.
INCLUDE_uxTaskGetStackHighWaterMark must be set to 1 in FreeRTOSConfig.h for this function to be available. Returns the high water mark of the stack associated with xTask. That is, the minimum free stack space there has been (in words, so on a 32 bit machine a value of 1 means 4 bytes) since the task started. The smaller the returned number the closer the task has come to overflowing its stack. uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are the same except for their return type. Using configSTACK_DEPTH_TYPE allows the user to determine the return type. It gets around the problem of the value overflowing on 8-bit types without breaking backward compatibility for applications that expect an 8-bit return type.
xTaskGetIdleTaskHandle() is only available if INCLUDE_xTaskGetIdleTaskHandle is set to 1 in FreeRTOSConfig.h. Simply returns the handle of the idle task. It is not valid to call xTaskGetIdleTaskHandle() before the scheduler has been started.
configUSE_TRACE_FACILITY and configUSE_STATS_FORMATTING_FUNCTIONS must both be defined as 1 for this function to be available. See the configuration section of the FreeRTOS.org website for more information. NOTE 1: This function will disable interrupts for its duration. It is not intended for normal application runtime use but as a debug aid. Lists all the current tasks, along with their current state and stack usage high water mark. Tasks are reported as blocked ('B'), ready ('R'), deleted ('D') or suspended ('S'). PLEASE NOTE: This function is provided for convenience only, and is used by many of the demo applications. Do not consider it to be part of the scheduler. vTaskList() calls uxTaskGetSystemState(), then formats part of the uxTaskGetSystemState() output into a human readable table that displays task names, states and stack usage. vTaskList() has a dependency on the sprintf() C library function that might bloat the code size, use a lot of stack, and provide different results on different platforms. An alternative, tiny, third party, and limited functionality implementation of sprintf() is provided in many of the FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note printf-stdarg.c does not provide a full snprintf() implementation!). It is recommended that production systems call uxTaskGetSystemState() directly to get access to raw stats data, rather than indirectly through a call to vTaskList().
configGENERATE_RUN_TIME_STATS and configUSE_STATS_FORMATTING_FUNCTIONS must both be defined as 1 for this function to be available. The application must also then provide definitions for portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and portGET_RUN_TIME_COUNTER_VALUE() to configure a peripheral timer/counter and return the timers current count value respectively. The counter should be at least 10 times the frequency of the tick count. Setting configGENERATE_RUN_TIME_STATS to 1 will result in a total accumulated execution time being stored for each task. The resolution of the accumulated time value depends on the frequency of the timer configured by the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() macro. While uxTaskGetSystemState() and vTaskGetRunTimeStats() writes the total execution time of each task into a buffer, ulTaskGetIdleRunTimeCounter() returns the total execution time of just the idle task.
Atomically set bits within an event group, then wait for a combination of bits to be set within the same event group. This functionality is typically used to synchronise multiple tasks, where each task has to wait for the other tasks to reach a synchronisation point before proceeding. This function cannot be used from an interrupt. The function will return before its block time expires if the bits specified by the uxBitsToWait parameter are set, or become set within that time. In this case all the bits specified by uxBitsToWait will be automatically cleared before the function returns. Example usage:
// Bits used by the three tasks. #define TASK_0_BIT ( 1 << 0 ) #define TASK_1_BIT ( 1 << 1 ) #define TASK_2_BIT ( 1 << 2 ) #define ALL_SYNC_BITS ( TASK_0_BIT | TASK_1_BIT | TASK_2_BIT ) // Use an event group to synchronise three tasks. It is assumed this event // group has already been created elsewhere. EventGroupHandle_t xEventBits; void vTask0( void *pvParameters ) { EventBits_t uxReturn; TickType_t xTicksToWait = 100 / portTICK_PERIOD_MS; for( ;; ) { // Perform task functionality here. // Set bit 0 in the event flag to note this task has reached the // sync point. The other two tasks will set the other two bits defined // by ALL_SYNC_BITS. All three tasks have reached the synchronisation // point when all the ALL_SYNC_BITS are set. Wait a maximum of 100ms // for this to happen. uxReturn = xEventGroupSync( xEventBits, TASK_0_BIT, ALL_SYNC_BITS, xTicksToWait ); if( ( uxReturn & ALL_SYNC_BITS ) == ALL_SYNC_BITS ) { // All three tasks reached the synchronisation point before the call // to xEventGroupSync() timed out. } } } void vTask1( void *pvParameters ) { for( ;; ) { // Perform task functionality here. // Set bit 1 in the event flag to note this task has reached the // synchronisation point. The other two tasks will set the other two // bits defined by ALL_SYNC_BITS. All three tasks have reached the // synchronisation point when all the ALL_SYNC_BITS are set. Wait // indefinitely for this to happen. xEventGroupSync( xEventBits, TASK_1_BIT, ALL_SYNC_BITS, portMAX_DELAY ); // xEventGroupSync() was called with an indefinite block time, so // this task will only reach here if the syncrhonisation was made by all // three tasks, so there is no need to test the return value. } } void vTask2( void *pvParameters ) { for( ;; ) { // Perform task functionality here. // Set bit 2 in the event flag to note this task has reached the // synchronisation point. The other two tasks will set the other two // bits defined by ALL_SYNC_BITS. All three tasks have reached the // synchronisation point when all the ALL_SYNC_BITS are set. Wait // indefinitely for this to happen. xEventGroupSync( xEventBits, TASK_2_BIT, ALL_SYNC_BITS, portMAX_DELAY ); // xEventGroupSync() was called with an indefinite block time, so // this task will only reach here if the syncrhonisation was made by all // three tasks, so there is no need to test the return value. } }
TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ); Simply returns the handle of the timer service/daemon task. It it not valid to call xTimerGetTimerDaemonTaskHandle() before the scheduler has been started.
Memory regions are assigned to a restricted task when the task is created by a call to xTaskCreateRestricted(). These regions can be redefined using vTaskAllocateMPURegions(). Example usage:
// Define an array of MemoryRegion_t structures that configures an MPU region // allowing read/write access for 1024 bytes starting at the beginning of the // ucOneKByte array. The other two of the maximum 3 definable regions are // unused so set to zero. static const MemoryRegion_t xAltRegions[ portNUM_CONFIGURABLE_REGIONS ] = { // Base address Length Parameters { ucOneKByte, 1024, portMPU_REGION_READ_WRITE }, { 0, 0, 0 }, { 0, 0, 0 } }; void vATask( void *pvParameters ) { // This task was created such that it has access to certain regions of // memory as defined by the MPU configuration. At some point it is // desired that these MPU regions are replaced with that defined in the // xAltRegions const struct above. Use a call to vTaskAllocateMPURegions() // for this purpose. NULL is used as the task handle to indicate that this // function should modify the MPU regions of the calling task. vTaskAllocateMPURegions( NULL, xAltRegions ); // Now the task can continue its function, but from this point on can only // access its stack and the ucOneKByte array (unless any other statically // defined or shared regions have been declared elsewhere). }
INCLUDE_xTaskAbortDelay must be defined as 1 in FreeRTOSConfig.h for this function to be available. A task will enter the Blocked state when it is waiting for an event. The event it is waiting for can be a temporal event (waiting for a time), such as when vTaskDelay() is called, or an event on an object, such as when xQueueReceive() or ulTaskNotifyTake() is called. If the handle of a task that is in the Blocked state is used in a call to xTaskAbortDelay() then the task will leave the Blocked state, and return from whichever function call placed the task into the Blocked state. There is no 'FromISR' version of this function as an interrupt would need to know which object a task was blocked on in order to know which actions to take. For example, if the task was blocked on a queue the interrupt handler would then need to know if the queue was locked.
INCLUDE_uxTaskPriorityGet must be defined as 1 for this function to be available. See the configuration section for more information. Obtain the priority of any task. Example usage:
void vAFunction( void ) { TaskHandle_t xHandle; // Create a task, storing the handle. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); // ... // Use the handle to obtain the priority of the created task. // It was created with tskIDLE_PRIORITY, but may have changed // it itself. if( uxTaskPriorityGet( xHandle ) != tskIDLE_PRIORITY ) { // The task has changed it's priority. } // ... // Is our priority higher than the created task? if( uxTaskPriorityGet( xHandle ) < uxTaskPriorityGet( NULL ) ) { // Our priority (obtained using NULL handle) is higher. } }
INCLUDE_eTaskGetState must be defined as 1 for this function to be available. See the configuration section for more information. Obtain the state of any task. States are encoded by the eTaskState enumerated type.
NOTE: This function takes a relatively long time to complete and should be used sparingly.
INCLUDE_uxTaskGetStackHighWaterMark must be set to 1 in FreeRTOSConfig.h for this function to be available. Returns the high water mark of the stack associated with xTask. That is, the minimum free stack space there has been (in words, so on a 32 bit machine a value of 1 means 4 bytes) since the task started. The smaller the returned number the closer the task has come to overflowing its stack. uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are the same except for their return type. Using configSTACK_DEPTH_TYPE allows the user to determine the return type. It gets around the problem of the value overflowing on 8-bit types without breaking backward compatibility for applications that expect an 8-bit return type.
xTaskGetIdleTaskHandle() is only available if INCLUDE_xTaskGetIdleTaskHandle is set to 1 in FreeRTOSConfig.h. Simply returns the handle of the idle task. It is not valid to call xTaskGetIdleTaskHandle() before the scheduler has been started.
configGENERATE_RUN_TIME_STATS and configUSE_STATS_FORMATTING_FUNCTIONS must both be defined as 1 for this function to be available. The application must also then provide definitions for portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and portGET_RUN_TIME_COUNTER_VALUE() to configure a peripheral timer/counter and return the timers current count value respectively. The counter should be at least 10 times the frequency of the tick count. Setting configGENERATE_RUN_TIME_STATS to 1 will result in a total accumulated execution time being stored for each task. The resolution of the accumulated time value depends on the frequency of the timer configured by the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() macro. While uxTaskGetSystemState() and vTaskGetRunTimeStats() writes the total execution time of each task into a buffer, ulTaskGetIdleRunTimeCounter() returns the total execution time of just the idle task.
configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this function to be available. When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private "notification value", which is a 32-bit unsigned integer (uint32_t). Events can be sent to a task using an intermediary object. Examples of such objects are queues, semaphores, mutexes and event groups. Task notifications are a method of sending an event directly to a task without the need for such an intermediary object. A notification sent to a task can optionally perform an action, such as update, overwrite or increment the task's notification value. In that way task notifications can be used to send data to a task, or be used as light weight and fast binary or counting semaphores. A notification sent to a task will remain pending until it is cleared by the task calling xTaskNotifyWait() or ulTaskNotifyTake(). If the task was already in the Blocked state to wait for a notification when the notification arrives then the task will automatically be removed from the Blocked state (unblocked) and the notification cleared. A task can use xTaskNotifyWait() to [optionally] block to wait for a notification to be pending, or ulTaskNotifyTake() to [optionally] block to wait for its notification value to have a non-zero value. The task does not consume any CPU time while it is in the Blocked state. See http://www.FreeRTOS.org/RTOS-task-notifications.html for details. eSetBits - The task's notification value is bitwise ORed with ulValue. xTaskNofify() always returns pdPASS in this case. eIncrement - The task's notification value is incremented. ulValue is not used and xTaskNotify() always returns pdPASS in this case. eSetValueWithOverwrite - The task's notification value is set to the value of ulValue, even if the task being notified had not yet processed the previous notification (the task already had a notification pending). xTaskNotify() always returns pdPASS in this case. eSetValueWithoutOverwrite - If the task being notified did not already have a notification pending then the task's notification value is set to ulValue and xTaskNotify() will return pdPASS. If the task being notified already had a notification pending then no action is performed and pdFAIL is returned. eNoAction - The task receives a notification without its notification value being updated. ulValue is not used and xTaskNotify() always returns pdPASS in this case. pulPreviousNotificationValue - Can be used to pass out the subject task's notification value before any bits are modified by the notify function.
configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this function to be available. When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private "notification value", which is a 32-bit unsigned integer (uint32_t). Events can be sent to a task using an intermediary object. Examples of such objects are queues, semaphores, mutexes and event groups. Task notifications are a method of sending an event directly to a task without the need for such an intermediary object. A notification sent to a task can optionally perform an action, such as update, overwrite or increment the task's notification value. In that way task notifications can be used to send data to a task, or be used as light weight and fast binary or counting semaphores. A notification sent to a task will remain pending until it is cleared by the task calling xTaskNotifyWait() or ulTaskNotifyTake(). If the task was already in the Blocked state to wait for a notification when the notification arrives then the task will automatically be removed from the Blocked state (unblocked) and the notification cleared. A task can use xTaskNotifyWait() to [optionally] block to wait for a notification to be pending, or ulTaskNotifyTake() to [optionally] block to wait for its notification value to have a non-zero value. The task does not consume any CPU time while it is in the Blocked state. See http://www.FreeRTOS.org/RTOS-task-notifications.html for details.
configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this function to be available. When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private "notification value", which is a 32-bit unsigned integer (uint32_t). Events can be sent to a task using an intermediary object. Examples of such objects are queues, semaphores, mutexes and event groups. Task notifications are a method of sending an event directly to a task without the need for such an intermediary object. A notification sent to a task can optionally perform an action, such as update, overwrite or increment the task's notification value. In that way task notifications can be used to send data to a task, or be used as light weight and fast binary or counting semaphores. ulTaskNotifyTake() is intended for use when a task notification is used as a faster and lighter weight binary or counting semaphore alternative. Actual FreeRTOS semaphores are taken using the xSemaphoreTake() API function, the equivalent action that instead uses a task notification is ulTaskNotifyTake(). When a task is using its notification value as a binary or counting semaphore other tasks should send notifications to it using the xTaskNotifyGive() macro, or xTaskNotify() function with the eAction parameter set to eIncrement. ulTaskNotifyTake() can either clear the task's notification value to zero on exit, in which case the notification value acts like a binary semaphore, or decrement the task's notification value on exit, in which case the notification value acts like a counting semaphore. A task can use ulTaskNotifyTake() to [optionally] block to wait for a the task's notification value to be non-zero. The task does not consume any CPU time while it is in the Blocked state. Where as xTaskNotifyWait() will return when a notification is pending, ulTaskNotifyTake() will return when the task's notification value is not zero. See http://www.FreeRTOS.org/RTOS-task-notifications.html for details.
If the notification state of the task referenced by the handle xTask is eNotified, then set the task's notification state to eNotWaitingNotification. The task's notification value is not altered. Set xTask to NULL to clear the notification state of the calling task.
Clears the bits specified by the ulBitsToClear bit mask in the notification value of the task referenced by xTask. Set ulBitsToClear to 0xffffffff (UINT_MAX on 32-bit architectures) to clear the notification value to 0. Set ulBitsToClear to 0 to query the task's notification value without clearing any bits.
configUSE_TRACE_FACILITY must be defined as 1 for this function to be available. See the configuration section for more information. Populates a TaskStatus_t structure with information about a task. @xGetFreeStackSpace The TaskStatus_t structure contains a member to report the stack high water mark of the task being queried. Calculating the stack high water mark takes a relatively long time, and can make the system temporarily unresponsive - so the xGetFreeStackSpace parameter is provided to allow the high water mark checking to be skipped. The high watermark value will only be written to the TaskStatus_t structure if xGetFreeStackSpace is not set to pdFALSE; Example usage:
void vAFunction( void ) { TaskHandle_t xHandle; TaskStatus_t xTaskDetails; // Obtain the handle of a task from its name. xHandle = xTaskGetHandle( "Task_Name" ); // Check the handle is not NULL. configASSERT( xHandle ); // Use the handle to obtain further information about the task. vTaskGetInfo( xHandle, &xTaskDetails, pdTRUE, // Include the high water mark in xTaskDetails. eInvalid ); // Include the task state in xTaskDetails. }
INCLUDE_vTaskPrioritySet must be defined as 1 for this function to be available. See the configuration section for more information. Set the priority of any task. A context switch will occur before the function returns if the priority being set is higher than the currently executing task. Example usage:
void vAFunction( void ) { TaskHandle_t xHandle; // Create a task, storing the handle. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); // ... // Use the handle to raise the priority of the created task. vTaskPrioritySet( xHandle, tskIDLE_PRIORITY + 1 ); // ... // Use a NULL handle to raise our priority to the same value. vTaskPrioritySet( NULL, tskIDLE_PRIORITY + 1 ); }
INCLUDE_vTaskSuspend must be defined as 1 for this function to be available. See the configuration section for more information. Suspend any task. When suspended a task will never get any microcontroller processing time, no matter what its priority. Calls to vTaskSuspend are not accumulative - i.e. calling vTaskSuspend () twice on the same task still only requires one call to vTaskResume () to ready the suspended task. Example usage:
void vAFunction( void ) { TaskHandle_t xHandle; // Create a task, storing the handle. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); // ... // Use the handle to suspend the created task. vTaskSuspend( xHandle ); // ... // The created task will not run during this period, unless // another task calls vTaskResume( xHandle ). //... // Suspend ourselves. vTaskSuspend( NULL ); // We cannot get here unless another task calls vTaskResume // with our handle as the parameter. }
INCLUDE_vTaskSuspend must be defined as 1 for this function to be available. See the configuration section for more information. Resumes a suspended task. A task that has been suspended by one or more calls to vTaskSuspend () will be made available for running again by a single call to vTaskResume (). Example usage:
void vAFunction( void ) { TaskHandle_t xHandle; // Create a task, storing the handle. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); // ... // Use the handle to suspend the created task. vTaskSuspend( xHandle ); // ... // The created task will not run during this period, unless // another task calls vTaskResume( xHandle ). //... // Resume the suspended task ourselves. vTaskResume( xHandle ); // The created task will once again get microcontroller processing // time in accordance with its priority within the system. }
Suspends the scheduler without disabling interrupts. Context switches will not occur while the scheduler is suspended. After calling vTaskSuspendAll () the calling task will continue to execute without risk of being swapped out until a call to xTaskResumeAll () has been made. API functions that have the potential to cause a context switch (for example, vTaskDelayUntil(), xQueueSend(), etc.) must not be called while the scheduler is suspended. Example usage:
void vTask1( void * pvParameters ) { for( ;; ) { // Task code goes here. // ... // At some point the task wants to perform a long operation during // which it does not want to get swapped out. It cannot use // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the // operation may cause interrupts to be missed - including the // ticks. // Prevent the real time kernel swapping out the task. vTaskSuspendAll (); // Perform the operation here. There is no need to use critical // sections as we have all the microcontroller processing time. // During this time interrupts will still operate and the kernel // tick count will be maintained. // ... // The operation is complete. Restart the kernel. xTaskResumeAll (); } }
Resumes scheduler activity after it was suspended by a call to vTaskSuspendAll(). xTaskResumeAll() only resumes the scheduler. It does not unsuspend tasks that were previously suspended by a call to vTaskSuspend(). Example usage:
void vTask1( void * pvParameters ) { for( ;; ) { // Task code goes here. // ... // At some point the task wants to perform a long operation during // which it does not want to get swapped out. It cannot use // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the // operation may cause interrupts to be missed - including the // ticks. // Prevent the real time kernel swapping out the task. vTaskSuspendAll (); // Perform the operation here. There is no need to use critical // sections as we have all the microcontroller processing time. // During this time interrupts will still operate and the real // time kernel tick count will be maintained. // ... // The operation is complete. Restart the kernel. We want to force // a context switch - but there is no point if resuming the scheduler // caused a context switch already. if( !xTaskResumeAll () ) { taskYIELD (); } } }
Capture the current time for future use with xTaskCheckForTimeOut().
Determines if pxTicksToWait ticks has passed since a time was captured using a call to vTaskSetTimeOutState(). The captured time includes the tick count and the number of times the tick count has overflowed. @see https://www.freertos.org/xTaskCheckForTimeOut.html Example Usage:
// Driver library function used to receive uxWantedBytes from an Rx buffer // that is filled by a UART interrupt. If there are not enough bytes in the // Rx buffer then the task enters the Blocked state until it is notified that // more data has been placed into the buffer. If there is still not enough // data then the task re-enters the Blocked state, and xTaskCheckForTimeOut() // is used to re-calculate the Block time to ensure the total amount of time // spent in the Blocked state does not exceed MAX_TIME_TO_WAIT. This // continues until either the buffer contains at least uxWantedBytes bytes, // or the total amount of time spent in the Blocked state reaches // MAX_TIME_TO_WAIT – at which point the task reads however many bytes are // available up to a maximum of uxWantedBytes. size_t xUART_Receive( uint8_t *pucBuffer, size_t uxWantedBytes ) { size_t uxReceived = 0; TickType_t xTicksToWait = MAX_TIME_TO_WAIT; TimeOut_t xTimeOut; // Initialize xTimeOut. This records the time at which this function // was entered. vTaskSetTimeOutState( &xTimeOut ); // Loop until the buffer contains the wanted number of bytes, or a // timeout occurs. while( UART_bytes_in_rx_buffer( pxUARTInstance ) < uxWantedBytes ) { // The buffer didn't contain enough data so this task is going to // enter the Blocked state. Adjusting xTicksToWait to account for // any time that has been spent in the Blocked state within this // function so far to ensure the total amount of time spent in the // Blocked state does not exceed MAX_TIME_TO_WAIT. if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) != pdFALSE ) { //Timed out before the wanted number of bytes were available, // exit the loop. break; } // Wait for a maximum of xTicksToWait ticks to be notified that the // receive interrupt has placed more data into the buffer. ulTaskNotifyTake( pdTRUE, xTicksToWait ); } // Attempt to read uxWantedBytes from the receive buffer into pucBuffer. // The actual number of bytes read (which might be less than // uxWantedBytes) is returned. uxReceived = UART_read_from_receive_buffer( pxUARTInstance, pucBuffer, uxWantedBytes ); return uxReceived; }
Receive an item from a queue without removing the item from the queue. The item is received by copy so a buffer of adequate size must be provided. The number of bytes copied into the buffer was defined when the queue was created. Successfully received items remain on the queue so will be returned again by the next call, or a call to xQueueReceive(). This macro must not be used in an interrupt service routine. See xQueuePeekFromISR() for an alternative that can be called from an interrupt service routine. Example usage:
struct AMessage { char ucMessageID; char ucData[ 20 ]; } xMessage; QueueHandle_t xQueue; // Task to create a queue and post a value. void vATask( void *pvParameters ) { struct AMessage *pxMessage; // Create a queue capable of containing 10 pointers to AMessage structures. // These should be passed by pointer as they contain a lot of data. xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) ); if( xQueue == 0 ) { // Failed to create the queue. } // ... // Send a pointer to a struct AMessage object. Don't block if the // queue is already full. pxMessage = & xMessage; xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 ); // ... Rest of task code. } // Task to peek the data from the queue. void vADifferentTask( void *pvParameters ) { struct AMessage *pxRxedMessage; if( xQueue != 0 ) { // Peek a message on the created queue. Block for 10 ticks if a // message is not immediately available. if( xQueuePeek( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) ) { // pcRxedMessage now points to the struct AMessage variable posted // by vATask, but the item still remains on the queue. } } // ... Rest of task code. }
Return the number of messages stored in a queue.
Return the number of free spaces available in a queue. This is equal to the number of items that can be sent to the queue before the queue becomes full if no items are removed.
Delete a queue - freeing all the memory allocated for storing of items placed on the queue.
Only available when configSUPPORT_DYNAMIC_ALLOCATION is set to 1. xTaskCreateRestricted() should only be used in systems that include an MPU implementation. Create a new task and add it to the list of tasks that are ready to run. The function parameters define the memory regions and associated access permissions allocated to the task. See xTaskCreateRestrictedStatic() for a version that does not use any dynamic memory allocation. Example usage:
// Create an TaskParameters_t structure that defines the task to be created. static const TaskParameters_t xCheckTaskParameters = { vATask, // pvTaskCode - the function that implements the task. "ATask", // pcName - just a text name for the task to assist debugging. 100, // usStackDepth - the stack size DEFINED IN WORDS. NULL, // pvParameters - passed into the task function as the function parameters. ( 1UL | portPRIVILEGE_BIT ),// uxPriority - task priority, set the portPRIVILEGE_BIT if the task should run in a privileged state. cStackBuffer,// puxStackBuffer - the buffer to be used as the task stack. // xRegions - Allocate up to three separate memory regions for access by // the task, with appropriate access permissions. Different processors have // different memory alignment requirements - refer to the FreeRTOS documentation // for full information. { // Base address Length Parameters { cReadWriteArray, 32, portMPU_REGION_READ_WRITE }, { cReadOnlyArray, 32, portMPU_REGION_READ_ONLY }, { cPrivilegedOnlyAccessArray, 128, portMPU_REGION_PRIVILEGED_READ_WRITE } } }; int main( void ) { TaskHandle_t xHandle; // Create a task from the const structure defined above. The task handle // is requested (the second parameter is not NULL) but in this case just for // demonstration purposes as its not actually used. xTaskCreateRestricted( &xRegTest1Parameters, &xHandle ); // Start the scheduler. vTaskStartScheduler(); // Will only get here if there was insufficient memory to create the idle // and/or timer task. for( ;; ); }
size_t xStreamBufferSend( StreamBufferHandle_t xStreamBuffer, const void *pvTxData, size_t xDataLengthBytes, TickType_t xTicksToWait );
Sends bytes to a stream buffer. The bytes are copied into the stream buffer. ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer implementation (so also the message buffer implementation, as message buffers are built on top of stream buffers) assumes there is only one task or interrupt that will write to the buffer (the writer), and only one task or interrupt that will read from the buffer (the reader). It is safe for the writer and reader to be different tasks or interrupts, but, unlike other FreeRTOS objects, it is not safe to have multiple different writers or multiple different readers. If there are to be multiple different writers then the application writer must place each call to a writing API function (such as xStreamBufferSend()) inside a critical section and set the send block time to 0. Likewise, if there are to be multiple different readers then the application writer must place each call to a reading API function (such as xStreamBufferReceive()) inside a critical section and set the receive block time to 0. Use xStreamBufferSend() to write to a stream buffer from a task. Use xStreamBufferSendFromISR() to write to a stream buffer from an interrupt service routine (ISR). Example use:
void vAFunction( StreamBufferHandle_t xStreamBuffer ) { size_t xBytesSent; uint8_t ucArrayToSend[] = { 0, 1, 2, 3 }; char *pcStringToSend = "String to send"; const TickType_t x100ms = pdMS_TO_TICKS( 100 ); // Send an array to the stream buffer, blocking for a maximum of 100ms to // wait for enough space to be available in the stream buffer. xBytesSent = xStreamBufferSend( xStreamBuffer, ( void * ) ucArrayToSend, sizeof( ucArrayToSend ), x100ms ); if( xBytesSent != sizeof( ucArrayToSend ) ) { // The call to xStreamBufferSend() times out before there was enough // space in the buffer for the data to be written, but it did // successfully write xBytesSent bytes. } // Send the string to the stream buffer. Return immediately if there is not // enough space in the buffer. xBytesSent = xStreamBufferSend( xStreamBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), 0 ); if( xBytesSent != strlen( pcStringToSend ) ) { // The entire string could not be added to the stream buffer because // there was not enough free space in the buffer, but xBytesSent bytes // were sent. Could try again to send the remaining bytes. } }
BaseType_t xStreamBufferReset( StreamBufferHandle_t xStreamBuffer );
Resets a stream buffer to its initial, empty, state. Any data that was in the stream buffer is discarded. A stream buffer can only be reset if there are no tasks blocked waiting to either send to or receive from the stream buffer.
BaseType_t xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer, size_t xTriggerLevel );
A stream buffer's trigger level is the number of bytes that must be in the stream buffer before a task that is blocked on the stream buffer to wait for data is moved out of the blocked state. For example, if a task is blocked on a read of an empty stream buffer that has a trigger level of 1 then the task will be unblocked when a single byte is written to the buffer or the task's block time expires. As another example, if a task is blocked on a read of an empty stream buffer that has a trigger level of 10 then the task will not be unblocked until the stream buffer contains at least 10 bytes or the task's block time expires. If a reading task's block time expires before the trigger level is reached then the task will still receive however many bytes are actually available. Setting a trigger level of 0 will result in a trigger level of 1 being used. It is not valid to specify a trigger level that is greater than the buffer size. A trigger level is set when the stream buffer is created, and can be modified using xStreamBufferSetTriggerLevel().
size_t xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer );
Queries a stream buffer to see how much data it contains, which is equal to the number of bytes that can be read from the stream buffer before the stream buffer would be empty.
BaseType_t xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer );
Queries a stream buffer to see if it is full. A stream buffer is full if it does not have any free space, and therefore cannot accept any more data.
size_t xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer, void *pvRxData, size_t xBufferLengthBytes, TickType_t xTicksToWait );
Receives bytes from a stream buffer. ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer implementation (so also the message buffer implementation, as message buffers are built on top of stream buffers) assumes there is only one task or interrupt that will write to the buffer (the writer), and only one task or interrupt that will read from the buffer (the reader). It is safe for the writer and reader to be different tasks or interrupts, but, unlike other FreeRTOS objects, it is not safe to have multiple different writers or multiple different readers. If there are to be multiple different writers then the application writer must place each call to a writing API function (such as xStreamBufferSend()) inside a critical section and set the send block time to 0. Likewise, if there are to be multiple different readers then the application writer must place each call to a reading API function (such as xStreamBufferReceive()) inside a critical section and set the receive block time to 0. Use xStreamBufferReceive() to read from a stream buffer from a task. Use xStreamBufferReceiveFromISR() to read from a stream buffer from an interrupt service routine (ISR). Example use:
void vAFunction( StreamBuffer_t xStreamBuffer ) { uint8_t ucRxData[ 20 ]; size_t xReceivedBytes; const TickType_t xBlockTime = pdMS_TO_TICKS( 20 ); // Receive up to another sizeof( ucRxData ) bytes from the stream buffer. // Wait in the Blocked state (so not using any CPU processing time) for a // maximum of 100ms for the full sizeof( ucRxData ) number of bytes to be // available. xReceivedBytes = xStreamBufferReceive( xStreamBuffer, ( void * ) ucRxData, sizeof( ucRxData ), xBlockTime ); if( xReceivedBytes > 0 ) { // A ucRxData contains another xRecievedBytes bytes of data, which can // be processed here.... } }
BaseType_t xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer );
Queries a stream buffer to see if it is empty. A stream buffer is empty if it does not contain any data.
void vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer );
Deletes a stream buffer that was previously created using a call to xStreamBufferCreate() or xStreamBufferCreateStatic(). If the stream buffer was created using dynamic memory (that is, by xStreamBufferCreate()), then the allocated memory is freed. A stream buffer handle must not be used after the stream buffer has been deleted.
Returns the current count value of a counting semaphore
Get the number of messaged stored in a queue.
A version of xEventGroupClearBits() that can be called from an interrupt. Setting bits in an event group is not a deterministic operation because there are an unknown number of tasks that may be waiting for the bit or bits being set. FreeRTOS does not allow nondeterministic operations to be performed while interrupts are disabled, so protects event groups that are accessed from tasks by suspending the scheduler rather than disabling interrupts. As a result event groups cannot be accessed directly from an interrupt service routine. Therefore xEventGroupClearBitsFromISR() sends a message to the timer task to have the clear operation performed in the context of the timer task. Example usage:
#define BIT_0 ( 1 << 0 ) #define BIT_4 ( 1 << 4 ) // An event group which it is assumed has already been created by a call to // xEventGroupCreate(). EventGroupHandle_t xEventGroup; void anInterruptHandler( void ) { // Clear bit 0 and bit 4 in xEventGroup. xResult = xEventGroupClearBitsFromISR( xEventGroup, // The event group being updated. BIT_0 | BIT_4 ); // The bits being set. if( xResult == pdPASS ) { // The message was posted successfully. } }
A version of xEventGroupSetBits() that can be called from an interrupt. Setting bits in an event group is not a deterministic operation because there are an unknown number of tasks that may be waiting for the bit or bits being set. FreeRTOS does not allow nondeterministic operations to be performed in interrupts or from critical sections. Therefore xEventGroupSetBitsFromISR() sends a message to the timer task to have the set operation performed in the context of the timer task - where a scheduler lock is used in place of a critical section. Example usage:
#define BIT_0 ( 1 << 0 ) #define BIT_4 ( 1 << 4 ) // An event group which it is assumed has already been created by a call to // xEventGroupCreate(). EventGroupHandle_t xEventGroup; void anInterruptHandler( void ) { BaseType_t xHigherPriorityTaskWoken, xResult; // xHigherPriorityTaskWoken must be initialised to pdFALSE. xHigherPriorityTaskWoken = pdFALSE; // Set bit 0 and bit 4 in xEventGroup. xResult = xEventGroupSetBitsFromISR( xEventGroup, // The event group being updated. BIT_0 | BIT_4 // The bits being set. &xHigherPriorityTaskWoken ); // Was the message posted successfully? if( xResult == pdPASS ) { // If xHigherPriorityTaskWoken is now set to pdTRUE then a context // switch should be requested. The macro used is port specific and // will be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() - // refer to the documentation page for the port being used. portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); } }
Clear the specified Signal Flags of an active thread.
Allocate a memory block from a memory pool and set memory block to zero
Allocate a memory block from a mail and set memory block to zero
Suspend execution of a all active threads.
Resume execution of a all suspended threads.
Abort the delay for a specific thread
Receive an item from a queue without removing the item from the queue.
Get the available space in a message queue.
Create and Initialize a Recursive Mutex
Release a Recursive Mutex
NOTE: At the time of writing only the x86 real mode port, which runs on a PC in place of DOS, implements this function. Stops the real time kernel tick. All created tasks will be automatically deleted and multitasking (either preemptive or cooperative) will stop. Execution then resumes from the point where vTaskStartScheduler () was called, as if vTaskStartScheduler () had just returned. See the demo application file main. c in the demo/PC directory for an example that uses vTaskEndScheduler (). vTaskEndScheduler () requires an exit function to be defined within the portable layer (see vPortEndScheduler () in port. c for the PC port). This performs hardware specific operations such as stopping the kernel tick. vTaskEndScheduler () will cause all of the resources allocated by the kernel to be freed - but will not free resources allocated by application tasks. Example usage:
void vTaskCode( void * pvParameters ) { for( ;; ) { // Task code goes here. // At some point we want to end the real time kernel processing // so call ... vTaskEndScheduler (); } } void vAFunction( void ) { // Create at least one task before starting the kernel. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL ); // Start the real time kernel with preemption. vTaskStartScheduler (); // Will only get here when the vTaskCode () task has called // vTaskEndScheduler (). When we get here we are back to single task // execution. }
INCLUDE_uxTaskGetStackHighWaterMark2 must be set to 1 in FreeRTOSConfig.h for this function to be available. Returns the high water mark of the stack associated with xTask. That is, the minimum free stack space there has been (in words, so on a 32 bit machine a value of 1 means 4 bytes) since the task started. The smaller the returned number the closer the task has come to overflowing its stack. uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are the same except for their return type. Using configSTACK_DEPTH_TYPE allows the user to determine the return type. It gets around the problem of the value overflowing on 8-bit types without breaking backward compatibility for applications that expect an 8-bit return type.
Calls the hook function associated with xTask. Passing xTask as NULL has the effect of calling the Running tasks (the calling task) hook function. pvParameter is passed to the hook function for the task to interpret as it wants. The return value is the value returned by the task hook function registered by the user.
configUSE_TRACE_FACILITY and configUSE_STATS_FORMATTING_FUNCTIONS must both be defined as 1 for this function to be available. See the configuration section of the FreeRTOS.org website for more information. NOTE 1: This function will disable interrupts for its duration. It is not intended for normal application runtime use but as a debug aid. Lists all the current tasks, along with their current state and stack usage high water mark. Tasks are reported as blocked ('B'), ready ('R'), deleted ('D') or suspended ('S'). PLEASE NOTE: This function is provided for convenience only, and is used by many of the demo applications. Do not consider it to be part of the scheduler. vTaskList() calls uxTaskGetSystemState(), then formats part of the uxTaskGetSystemState() output into a human readable table that displays task names, states and stack usage. vTaskList() has a dependency on the sprintf() C library function that might bloat the code size, use a lot of stack, and provide different results on different platforms. An alternative, tiny, third party, and limited functionality implementation of sprintf() is provided in many of the FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note printf-stdarg.c does not provide a full snprintf() implementation!). It is recommended that production systems call uxTaskGetSystemState() directly to get access to raw stats data, rather than indirectly through a call to vTaskList().
configGENERATE_RUN_TIME_STATS and configUSE_STATS_FORMATTING_FUNCTIONS must both be defined as 1 for this function to be available. The application must also then provide definitions for portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and portGET_RUN_TIME_COUNTER_VALUE() to configure a peripheral timer/counter and return the timers current count value respectively. The counter should be at least 10 times the frequency of the tick count. NOTE 1: This function will disable interrupts for its duration. It is not intended for normal application runtime use but as a debug aid. Setting configGENERATE_RUN_TIME_STATS to 1 will result in a total accumulated execution time being stored for each task. The resolution of the accumulated time value depends on the frequency of the timer configured by the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() macro. Calling vTaskGetRunTimeStats() writes the total execution time of each task into a buffer, both as an absolute count value and as a percentage of the total system execution time. NOTE 2: This function is provided for convenience only, and is used by many of the demo applications. Do not consider it to be part of the scheduler. vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part of the uxTaskGetSystemState() output into a human readable table that displays the amount of time each task has spent in the Running state in both absolute and percentage terms. vTaskGetRunTimeStats() has a dependency on the sprintf() C library function that might bloat the code size, use a lot of stack, and provide different results on different platforms. An alternative, tiny, third party, and limited functionality implementation of sprintf() is provided in many of the FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note printf-stdarg.c does not provide a full snprintf() implementation!). It is recommended that production systems call uxTaskGetSystemState() directly to get access to raw stats data, rather than indirectly through a call to vTaskGetRunTimeStats().
size_t xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer, const void *pvTxData, size_t xDataLengthBytes, BaseType_t *pxHigherPriorityTaskWoken );
Interrupt safe version of the API function that sends a stream of bytes to the stream buffer. ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer implementation (so also the message buffer implementation, as message buffers are built on top of stream buffers) assumes there is only one task or interrupt that will write to the buffer (the writer), and only one task or interrupt that will read from the buffer (the reader). It is safe for the writer and reader to be different tasks or interrupts, but, unlike other FreeRTOS objects, it is not safe to have multiple different writers or multiple different readers. If there are to be multiple different writers then the application writer must place each call to a writing API function (such as xStreamBufferSend()) inside a critical section and set the send block time to 0. Likewise, if there are to be multiple different readers then the application writer must place each call to a reading API function (such as xStreamBufferReceive()) inside a critical section and set the receive block time to 0. Use xStreamBufferSend() to write to a stream buffer from a task. Use xStreamBufferSendFromISR() to write to a stream buffer from an interrupt service routine (ISR). Example use:
// A stream buffer that has already been created. StreamBufferHandle_t xStreamBuffer; void vAnInterruptServiceRoutine( void ) { size_t xBytesSent; char *pcStringToSend = "String to send"; BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE. // Attempt to send the string to the stream buffer. xBytesSent = xStreamBufferSendFromISR( xStreamBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), &xHigherPriorityTaskWoken ); if( xBytesSent != strlen( pcStringToSend ) ) { // There was not enough free space in the stream buffer for the entire // string to be written, ut xBytesSent bytes were written. } // If xHigherPriorityTaskWoken was set to pdTRUE inside // xStreamBufferSendFromISR() then a task that has a priority above the // priority of the currently executing task was unblocked and a context // switch should be performed to ensure the ISR returns to the unblocked // task. In most FreeRTOS ports this is done by simply passing // xHigherPriorityTaskWoken into taskYIELD_FROM_ISR(), which will test the // variables value, and perform the context switch if necessary. Check the // documentation for the port in use for port specific instructions. taskYIELD_FROM_ISR( xHigherPriorityTaskWoken ); }
size_t xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer, void *pvRxData, size_t xBufferLengthBytes, BaseType_t *pxHigherPriorityTaskWoken );
An interrupt safe version of the API function that receives bytes from a stream buffer. Use xStreamBufferReceive() to read bytes from a stream buffer from a task. Use xStreamBufferReceiveFromISR() to read bytes from a stream buffer from an interrupt service routine (ISR). Example use:
// A stream buffer that has already been created. StreamBuffer_t xStreamBuffer; void vAnInterruptServiceRoutine( void ) { uint8_t ucRxData[ 20 ]; size_t xReceivedBytes; BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE. // Receive the next stream from the stream buffer. xReceivedBytes = xStreamBufferReceiveFromISR( xStreamBuffer, ( void * ) ucRxData, sizeof( ucRxData ), &xHigherPriorityTaskWoken ); if( xReceivedBytes > 0 ) { // ucRxData contains xReceivedBytes read from the stream buffer. // Process the stream here.... } // If xHigherPriorityTaskWoken was set to pdTRUE inside // xStreamBufferReceiveFromISR() then a task that has a priority above the // priority of the currently executing task was unblocked and a context // switch should be performed to ensure the ISR returns to the unblocked // task. In most FreeRTOS ports this is done by simply passing // xHigherPriorityTaskWoken into taskYIELD_FROM_ISR(), which will test the // variables value, and perform the context switch if necessary. Check the // documentation for the port in use for port specific instructions. taskYIELD_FROM_ISR( xHigherPriorityTaskWoken ); }
BaseType_t xStreamBufferSendCompletedFromISR( StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken );
For advanced users only. The sbSEND_COMPLETED() macro is called from within the FreeRTOS APIs when data is sent to a message buffer or stream buffer. If there was a task that was blocked on the message or stream buffer waiting for data to arrive then the sbSEND_COMPLETED() macro sends a notification to the task to remove it from the Blocked state. xStreamBufferSendCompletedFromISR() does the same thing. It is provided to enable application writers to implement their own version of sbSEND_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME. See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for additional information.
BaseType_t xStreamBufferReceiveCompletedFromISR( StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken );
For advanced users only. The sbRECEIVE_COMPLETED() macro is called from within the FreeRTOS APIs when data is read out of a message buffer or stream buffer. If there was a task that was blocked on the message or stream buffer waiting for data to arrive then the sbRECEIVE_COMPLETED() macro sends a notification to the task to remove it from the Blocked state. xStreamBufferReceiveCompletedFromISR() does the same thing. It is provided to enable application writers to implement their own version of sbRECEIVE_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME. See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for additional information.
Check if a thread is already suspended or not.
INCLUDE_uxTaskGetStackHighWaterMark2 must be set to 1 in FreeRTOSConfig.h for this function to be available. Returns the high water mark of the stack associated with xTask. That is, the minimum free stack space there has been (in words, so on a 32 bit machine a value of 1 means 4 bytes) since the task started. The smaller the returned number the closer the task has come to overflowing its stack. uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are the same except for their return type. Using configSTACK_DEPTH_TYPE allows the user to determine the return type. It gets around the problem of the value overflowing on 8-bit types without breaking backward compatibility for applications that expect an 8-bit return type.
Calls the hook function associated with xTask. Passing xTask as NULL has the effect of calling the Running tasks (the calling task) hook function. pvParameter is passed to the hook function for the task to interpret as it wants. The return value is the value returned by the task hook function registered by the user.
configGENERATE_RUN_TIME_STATS and configUSE_STATS_FORMATTING_FUNCTIONS must both be defined as 1 for this function to be available. The application must also then provide definitions for portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and portGET_RUN_TIME_COUNTER_VALUE() to configure a peripheral timer/counter and return the timers current count value respectively. The counter should be at least 10 times the frequency of the tick count. NOTE 1: This function will disable interrupts for its duration. It is not intended for normal application runtime use but as a debug aid. Setting configGENERATE_RUN_TIME_STATS to 1 will result in a total accumulated execution time being stored for each task. The resolution of the accumulated time value depends on the frequency of the timer configured by the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() macro. Calling vTaskGetRunTimeStats() writes the total execution time of each task into a buffer, both as an absolute count value and as a percentage of the total system execution time. NOTE 2: This function is provided for convenience only, and is used by many of the demo applications. Do not consider it to be part of the scheduler. vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part of the uxTaskGetSystemState() output into a human readable table that displays the amount of time each task has spent in the Running state in both absolute and percentage terms. vTaskGetRunTimeStats() has a dependency on the sprintf() C library function that might bloat the code size, use a lot of stack, and provide different results on different platforms. An alternative, tiny, third party, and limited functionality implementation of sprintf() is provided in many of the FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note printf-stdarg.c does not provide a full snprintf() implementation!). It is recommended that production systems call uxTaskGetSystemState() directly to get access to raw stats data, rather than indirectly through a call to vTaskGetRunTimeStats().
BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, TickType_t xTicksToWait ); Used to defer the execution of a function to the RTOS daemon task (the timer service task, hence this function is implemented in timers.c and is prefixed with 'Timer').
BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, BaseType_t *pxHigherPriorityTaskWoken ); Used from application interrupt service routines to defer the execution of a function to the RTOS daemon task (the timer service task, hence this function is implemented in timers.c and is prefixed with 'Timer'). Ideally an interrupt service routine (ISR) is kept as short as possible, but sometimes an ISR either has a lot of processing to do, or needs to perform processing that is not deterministic. In these cases xTimerPendFunctionCallFromISR() can be used to defer processing of a function to the RTOS daemon task. A mechanism is provided that allows the interrupt to return directly to the task that will subsequently execute the pended callback function. This allows the callback function to execute contiguously in time with the interrupt - just as if the callback had executed in the interrupt itself. Example usage: @verbatim // The callback function that will execute in the context of the daemon task. // Note callback functions must all use this same prototype. void vProcessInterface( void *pvParameter1, uint32_t ulParameter2 ) { BaseType_t xInterfaceToService; // The interface that requires servicing is passed in the second // parameter. The first parameter is not used in this case. xInterfaceToService = ( BaseType_t ) ulParameter2; // ...Perform the processing here... } // An ISR that receives data packets from multiple interfaces void vAnISR( void ) { BaseType_t xInterfaceToService, xHigherPriorityTaskWoken; // Query the hardware to determine which interface needs processing. xInterfaceToService = prvCheckInterfaces(); // The actual processing is to be deferred to a task. Request the // vProcessInterface() callback function is executed, passing in the // number of the interface that needs processing. The interface to // service is passed in the second parameter. The first parameter is // not used in this case. xHigherPriorityTaskWoken = pdFALSE; xTimerPendFunctionCallFromISR( vProcessInterface, NULL, ( uint32_t ) xInterfaceToService, &xHigherPriorityTaskWoken ); // If xHigherPriorityTaskWoken is now set to pdTRUE then a context // switch should be requested. The macro used is port specific and will // be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() - refer to // the documentation page for the port being used. portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); } @endverbatim
Create a new co-routine and add it to the list of co-routines that are ready to run. Example usage:
// Co-routine to be created. void vFlashCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex ) { // Variables in co-routines must be declared static if they must maintain value across a blocking call. // This may not be necessary for const variables. static const char cLedToFlash[ 2 ] = { 5, 6 }; static const TickType_t uxFlashRates[ 2 ] = { 200, 400 }; // Must start every co-routine with a call to crSTART(); crSTART( xHandle ); for( ;; ) { // This co-routine just delays for a fixed period, then toggles // an LED. Two co-routines are created using this function, so // the uxIndex parameter is used to tell the co-routine which // LED to flash and how int32_t to delay. This assumes xQueue has // already been created. vParTestToggleLED( cLedToFlash[ uxIndex ] ); crDELAY( xHandle, uxFlashRates[ uxIndex ] ); } // Must end every co-routine with a call to crEND(); crEND(); } // Function that creates two co-routines. void vOtherFunction( void ) { uint8_t ucParameterToPass; TaskHandle_t xHandle; // Create two co-routines at priority 0. The first is given index 0 // so (from the code above) toggles LED 5 every 200 ticks. The second // is given index 1 so toggles LED 6 every 400 ticks. for( uxIndex = 0; uxIndex < 2; uxIndex++ ) { xCoRoutineCreate( vFlashCoRoutine, 0, uxIndex ); } }
Run a co-routine. vCoRoutineSchedule() executes the highest priority co-routine that is able to run. The co-routine will execute until it either blocks, yields or is preempted by a task. Co-routines execute cooperatively so one co-routine cannot be preempted by another, but can be preempted by a task. If an application comprises of both tasks and co-routines then vCoRoutineSchedule should be called from the idle task (in an idle task hook). Example usage:
// This idle task hook will schedule a co-routine each time it is called. // The rest of the idle task will execute between co-routine calls. void vApplicationIdleHook( void ) { vCoRoutineSchedule(); } // Alternatively, if you do not require any other part of the idle task to // execute, the idle task hook can call vCoRoutineSchedule() within an // infinite loop. void vApplicationIdleHook( void ) { for( ;; ) { vCoRoutineSchedule(); } }

Other commonly used symbols

Name
Location
Summary
Type by which queues are referenced. For example, a call to xQueueCreate() returns an QueueHandle_t variable that can then be used as a parameter to xQueueSend(), xQueueReceive(), etc.
Thread Definition structure contains startup information of a thread.
Type by which tasks are referenced. For example, a call to xTaskCreate returns (via a pointer parameter) an TaskHandle_t variable that can then be used as a parameter to vTaskDelete to delete the task.
Event structure contains detailed information about an event.
Access a Thread definition.
Definition structure for message queue.
Type by which software timers are referenced. For example, a call to xTimerCreate() returns an TimerHandle_t variable that can then be used to reference the subject timer in calls to other software timer API functions (for example, xTimerStart(), xTimerReset(), etc.).
Type by which stream buffers are referenced. For example, a call to xStreamBufferCreate() returns an StreamBufferHandle_t variable that can then be used as a parameter to xStreamBufferSend(), xStreamBufferReceive(), etc.
Macro to disable all maskable interrupts.
Semaphore Definition structure contains setup information for a semaphore.
asm keyword for GNU Compiler
Type by which event groups are referenced. For example, a call to xEventGroupCreate() returns an EventGroupHandle_t variable that can then be used as a parameter to other event group functions.
Access a Message Queue Definition.
Macro to mark the end of a critical code region. Preemptive context switches cannot occur when in a critical region. NOTE: This may alter the stack (depending on the portable implementation) so must be used with care!
Macro to mark the start of a critical code region. Preemptive context switches cannot occur when in a critical region. NOTE: This may alter the stack (depending on the portable implementation) so must be used with care!
Timer Definition structure contains timer parameters.
Mail ID identifies the mail queue (pointer to a mail queue control block).
Defines the priority used by the idle task. This must not be modified.
Mutex Definition structure contains setup information for a mutex.
Access a Semaphore definition.
Pool ID identifies the memory pool (pointer to a memory pool control block).
Creates a new binary semaphore instance, and returns a handle by which the new semaphore can be referenced. In many usage scenarios it is faster and more memory efficient to use a direct to task notification in place of a binary semaphore! http://www.freertos.org/RTOS-task-notifications.html Internally, within the FreeRTOS implementation, binary semaphores use a block of memory, in which the semaphore structure is stored. If a binary semaphore is created using xSemaphoreCreateBinary() then the required memory is automatically dynamically allocated inside the xSemaphoreCreateBinary() function. (see http://www.freertos.org/a00111.html). If a binary semaphore is created using xSemaphoreCreateBinaryStatic() then the application writer must provide the memory. xSemaphoreCreateBinaryStatic() therefore allows a binary semaphore to be created without using any dynamic memory allocation. The old vSemaphoreCreateBinary() macro is now deprecated in favour of this xSemaphoreCreateBinary() function. Note that binary semaphores created using the vSemaphoreCreateBinary() macro are created in a state such that the first call to 'take' the semaphore would pass, whereas binary semaphores created using xSemaphoreCreateBinary() are created in a state such that the the semaphore must first be 'given' before it can be 'taken'. This type of semaphore can be used for pure synchronisation between tasks or between an interrupt and a task. The semaphore need not be given back once obtained, so one task/interrupt can continuously 'give' the semaphore while another continuously 'takes' the semaphore. For this reason this type of semaphore does not use a priority inheritance mechanism. For an alternative that does use priority inheritance see xSemaphoreCreateMutex(). Example usage:
SemaphoreHandle_t xSemaphore = NULL; void vATask( void * pvParameters ) { // Semaphore cannot be used before a call to xSemaphoreCreateBinary(). // This is a macro so pass the variable in directly. xSemaphore = xSemaphoreCreateBinary(); if( xSemaphore != NULL ) { // The semaphore was created successfully. // The semaphore can now be used. } }
inline keyword for GNU Compiler
Access a Timer definition.
Definition structure for mail queue.
Creates a new queue instance, and returns a handle by which the new queue can be referenced. Internally, within the FreeRTOS implementation, queues use two blocks of memory. The first block is used to hold the queue's data structures. The second block is used to hold items placed into the queue. If a queue is created using xQueueCreate() then both blocks of memory are automatically dynamically allocated inside the xQueueCreate() function. (see http://www.freertos.org/a00111.html). If a queue is created using xQueueCreateStatic() then the application writer must provide the memory that will get used by the queue. xQueueCreateStatic() therefore allows a queue to be created without using any dynamic memory allocation. http://www.FreeRTOS.org/Embedded-RTOS-Queues.html Example usage:
struct AMessage { char ucMessageID; char ucData[ 20 ]; }; void vATask( void *pvParameters ) { QueueHandle_t xQueue1, xQueue2; // Create a queue capable of containing 10 uint32_t values. xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); if( xQueue1 == 0 ) { // Queue was not created and must not be used. } // Create a queue capable of containing 10 pointers to AMessage structures. // These should be passed by pointer as they contain a lot of data. xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); if( xQueue2 == 0 ) { // Queue was not created and must not be used. } // ... Rest of task code. }
This is a macro that calls xQueueGenericSend(). It is included for backward compatibility with versions of FreeRTOS.org that did not include the xQueueSendToFront() and xQueueSendToBack() macros. It is equivalent to xQueueSendToBack(). Post an item on a queue. The item is queued by copy, not by reference. This function must not be called from an interrupt service routine. See xQueueSendFromISR () for an alternative which may be used in an ISR. Example usage:
struct AMessage { char ucMessageID; char ucData[ 20 ]; } xMessage; uint32_t ulVar = 10UL; void vATask( void *pvParameters ) { QueueHandle_t xQueue1, xQueue2; struct AMessage *pxMessage; // Create a queue capable of containing 10 uint32_t values. xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); // Create a queue capable of containing 10 pointers to AMessage structures. // These should be passed by pointer as they contain a lot of data. xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); // ... if( xQueue1 != 0 ) { // Send an uint32_t. Wait for 10 ticks for space to become // available if necessary. if( xQueueSend( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS ) { // Failed to post the message, even after 10 ticks. } } if( xQueue2 != 0 ) { // Send a pointer to a struct AMessage object. Don't block if the // queue is already full. pxMessage = & xMessage; xQueueSend( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 ); } // ... Rest of task code. }
This is a macro that calls xQueueGenericSendFromISR(). It is included for backward compatibility with versions of FreeRTOS.org that did not include the xQueueSendToBackFromISR() and xQueueSendToFrontFromISR() macros. Post an item to the back of a queue. It is safe to use this function from within an interrupt service routine. Items are queued by copy not reference so it is preferable to only queue small items, especially when called from an ISR. In most cases it would be preferable to store a pointer to the item being queued. Example usage for buffered IO (where the ISR can obtain more than one value per call):
void vBufferISR( void ) { char cIn; BaseType_t xHigherPriorityTaskWoken; // We have not woken a task at the start of the ISR. xHigherPriorityTaskWoken = pdFALSE; // Loop until the buffer is empty. do { // Obtain a byte from the buffer. cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); // Post the byte. xQueueSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); } while( portINPUT_BYTE( BUFFER_COUNT ) ); // Now the buffer is empty we can switch context if necessary. if( xHigherPriorityTaskWoken ) { // Actual macro used here is port specific. portYIELD_FROM_ISR (); } }
Access a Mutex definition.
Definition structure for memory block allocation.
Macro to release a semaphore. The semaphore must have previously been created with a call to xSemaphoreCreateBinary(), xSemaphoreCreateMutex() or xSemaphoreCreateCounting(). and obtained using sSemaphoreTake(). This macro must not be used from an ISR. See xSemaphoreGiveFromISR () for an alternative which can be used from an ISR. This macro must also not be used on semaphores created using xSemaphoreCreateRecursiveMutex(). Example usage:
SemaphoreHandle_t xSemaphore = NULL; void vATask( void * pvParameters ) { // Create the semaphore to guard a shared resource. xSemaphore = vSemaphoreCreateBinary(); if( xSemaphore != NULL ) { if( xSemaphoreGive( xSemaphore ) != pdTRUE ) { // We would expect this call to fail because we cannot give // a semaphore without first "taking" it! } // Obtain the semaphore - don't block if the semaphore is not // immediately available. if( xSemaphoreTake( xSemaphore, ( TickType_t ) 0 ) ) { // We now have the semaphore and can access the shared resource. // ... // We have finished accessing the shared resource so can free the // semaphore. if( xSemaphoreGive( xSemaphore ) != pdTRUE ) { // We would not expect this call to fail because we must have // obtained the semaphore to get here. } } } }
Macro for forcing a context switch.
This is a macro that calls xQueueGenericSend(). Post an item to the back of a queue. The item is queued by copy, not by reference. This function must not be called from an interrupt service routine. See xQueueSendFromISR () for an alternative which may be used in an ISR. Example usage:
struct AMessage { char ucMessageID; char ucData[ 20 ]; } xMessage; uint32_t ulVar = 10UL; void vATask( void *pvParameters ) { QueueHandle_t xQueue1, xQueue2; struct AMessage *pxMessage; // Create a queue capable of containing 10 uint32_t values. xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); // Create a queue capable of containing 10 pointers to AMessage structures. // These should be passed by pointer as they contain a lot of data. xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); // ... if( xQueue1 != 0 ) { // Send an uint32_t. Wait for 10 ticks for space to become // available if necessary. if( xQueueSendToBack( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS ) { // Failed to post the message, even after 10 ticks. } } if( xQueue2 != 0 ) { // Send a pointer to a struct AMessage object. Don't block if the // queue is already full. pxMessage = & xMessage; xQueueSendToBack( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 ); } // ... Rest of task code. }
Macro to obtain a semaphore. The semaphore must have previously been created with a call to xSemaphoreCreateBinary(), xSemaphoreCreateMutex() or xSemaphoreCreateCounting(). Example usage:
SemaphoreHandle_t xSemaphore = NULL; // A task that creates a semaphore. void vATask( void * pvParameters ) { // Create the semaphore to guard a shared resource. xSemaphore = xSemaphoreCreateBinary(); } // A task that uses the semaphore. void vAnotherTask( void * pvParameters ) { // ... Do other things. if( xSemaphore != NULL ) { // See if we can obtain the semaphore. If the semaphore is not available // wait 10 ticks to see if it becomes free. if( xSemaphoreTake( xSemaphore, ( TickType_t ) 10 ) == pdTRUE ) { // We were able to obtain the semaphore and can now access the // shared resource. // ... // We have finished accessing the shared resource. Release the // semaphore. xSemaphoreGive( xSemaphore ); } else { // We could not obtain the semaphore and can therefore not access // the shared resource safely. } } }
Macro to release a semaphore. The semaphore must have previously been created with a call to xSemaphoreCreateBinary() or xSemaphoreCreateCounting(). Mutex type semaphores (those created using a call to xSemaphoreCreateMutex()) must not be used with this macro. This macro can be used from an ISR. Example usage:
\#define LONG_TIME 0xffff \#define TICKS_TO_WAIT 10 SemaphoreHandle_t xSemaphore = NULL; // Repetitive task. void vATask( void * pvParameters ) { for( ;; ) { // We want this task to run every 10 ticks of a timer. The semaphore // was created before this task was started. // Block waiting for the semaphore to become available. if( xSemaphoreTake( xSemaphore, LONG_TIME ) == pdTRUE ) { // It is time to execute. // ... // We have finished our task. Return to the top of the loop where // we will block on the semaphore until it is time to execute // again. Note when using the semaphore for synchronisation with an // ISR in this manner there is no need to 'give' the semaphore back. } } } // Timer ISR void vTimerISR( void * pvParameters ) { static uint8_t ucLocalTickCount = 0; static BaseType_t xHigherPriorityTaskWoken; // A timer tick has occurred. // ... Do other time functions. // Is it time for vATask () to run? xHigherPriorityTaskWoken = pdFALSE; ucLocalTickCount++; if( ucLocalTickCount >= TICKS_TO_WAIT ) { // Unblock the task by releasing the semaphore. xSemaphoreGiveFromISR( xSemaphore, &xHigherPriorityTaskWoken ); // Reset the count so we release the semaphore again in 10 ticks time. ucLocalTickCount = 0; } if( xHigherPriorityTaskWoken != pdFALSE ) { // We can force a context switch here. Context switching from an // ISR uses port specific syntax. Check the demo task for your port // to find the syntax required. } }
Macro to take a semaphore from an ISR. The semaphore must have previously been created with a call to xSemaphoreCreateBinary() or xSemaphoreCreateCounting(). Mutex type semaphores (those created using a call to xSemaphoreCreateMutex()) must not be used with this macro. This macro can be used from an ISR, however taking a semaphore from an ISR is not a common operation. It is likely to only be useful when taking a counting semaphore when an interrupt is obtaining an object from a resource pool (when the semaphore count indicates the number of resources available).
Entry point of a thread.
Access a Mail Queue Definition.
Entry point of a timer call back function.
BaseType_t xTimerStop( TimerHandle_t xTimer, TickType_t xTicksToWait ); Timer functionality is provided by a timer service/daemon task. Many of the public FreeRTOS timer API functions send commands to the timer service task through a queue called the timer command queue. The timer command queue is private to the kernel itself and is not directly accessible to application code. The length of the timer command queue is set by the configTIMER_QUEUE_LENGTH configuration constant. xTimerStop() stops a timer that was previously started using either of the The xTimerStart(), xTimerReset(), xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() or xTimerChangePeriodFromISR() API functions. Stopping a timer ensures the timer is not in the active state. The configUSE_TIMERS configuration constant must be set to 1 for xTimerStop() to be available. Example usage: See the xTimerCreate() API function example usage scenario.
BaseType_t xTimerChangePeriod( TimerHandle_t xTimer, TickType_t xNewPeriod, TickType_t xTicksToWait ); Timer functionality is provided by a timer service/daemon task. Many of the public FreeRTOS timer API functions send commands to the timer service task through a queue called the timer command queue. The timer command queue is private to the kernel itself and is not directly accessible to application code. The length of the timer command queue is set by the configTIMER_QUEUE_LENGTH configuration constant. xTimerChangePeriod() changes the period of a timer that was previously created using the xTimerCreate() API function. xTimerChangePeriod() can be called to change the period of an active or dormant state timer. The configUSE_TIMERS configuration constant must be set to 1 for xTimerChangePeriod() to be available. Example usage: @verbatim // This function assumes xTimer has already been created. If the timer // referenced by xTimer is already active when it is called, then the timer // is deleted. If the timer referenced by xTimer is not active when it is // called, then the period of the timer is set to 500ms and the timer is // started. void vAFunction( TimerHandle_t xTimer ) { if( xTimerIsTimerActive( xTimer ) != pdFALSE ) // or more simply and equivalently "if( xTimerIsTimerActive( xTimer ) )" { // xTimer is already active - delete it. xTimerDelete( xTimer ); } else { // xTimer is not active, change its period to 500ms. This will also // cause the timer to start. Block for a maximum of 100 ticks if the // change period command cannot immediately be sent to the timer // command queue. if( xTimerChangePeriod( xTimer, 500 / portTICK_PERIOD_MS, 100 ) == pdPASS ) { // The command was successfully sent. } else { // The command could not be sent, even after waiting for 100 ticks // to pass. Take appropriate action here. } } } @endverbatim
BaseType_t xTimerDelete( TimerHandle_t xTimer, TickType_t xTicksToWait ); Timer functionality is provided by a timer service/daemon task. Many of the public FreeRTOS timer API functions send commands to the timer service task through a queue called the timer command queue. The timer command queue is private to the kernel itself and is not directly accessible to application code. The length of the timer command queue is set by the configTIMER_QUEUE_LENGTH configuration constant. xTimerDelete() deletes a timer that was previously created using the xTimerCreate() API function. The configUSE_TIMERS configuration constant must be set to 1 for xTimerDelete() to be available. Example usage: See the xTimerChangePeriod() API function example usage scenario.
BaseType_t xTimerStopFromISR( TimerHandle_t xTimer, BaseType_t *pxHigherPriorityTaskWoken ); A version of xTimerStop() that can be called from an interrupt service routine. Example usage: @verbatim // This scenario assumes xTimer has already been created and started. When // an interrupt occurs, the timer should be simply stopped. // The interrupt service routine that stops the timer. void vAnExampleInterruptServiceRoutine( void ) { BaseType_t xHigherPriorityTaskWoken = pdFALSE; // The interrupt has occurred - simply stop the timer. // xHigherPriorityTaskWoken was set to pdFALSE where it was defined // (within this function). As this is an interrupt service routine, only // FreeRTOS API functions that end in "FromISR" can be used. if( xTimerStopFromISR( xTimer, &xHigherPriorityTaskWoken ) != pdPASS ) { // The stop command was not executed successfully. Take appropriate // action here. } // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch // should be performed. The syntax required to perform a context switch // from inside an ISR varies from port to port, and from compiler to // compiler. Inspect the demos for the port you are using to find the // actual syntax required. if( xHigherPriorityTaskWoken != pdFALSE ) { // Call the interrupt safe yield function here (actual function // depends on the FreeRTOS port being used). } } @endverbatim
BaseType_t xTimerChangePeriodFromISR( TimerHandle_t xTimer, TickType_t xNewPeriod, BaseType_t *pxHigherPriorityTaskWoken ); A version of xTimerChangePeriod() that can be called from an interrupt service routine. Example usage: @verbatim // This scenario assumes xTimer has already been created and started. When // an interrupt occurs, the period of xTimer should be changed to 500ms. // The interrupt service routine that changes the period of xTimer. void vAnExampleInterruptServiceRoutine( void ) { BaseType_t xHigherPriorityTaskWoken = pdFALSE; // The interrupt has occurred - change the period of xTimer to 500ms. // xHigherPriorityTaskWoken was set to pdFALSE where it was defined // (within this function). As this is an interrupt service routine, only // FreeRTOS API functions that end in "FromISR" can be used. if( xTimerChangePeriodFromISR( xTimer, &xHigherPriorityTaskWoken ) != pdPASS ) { // The command to change the timers period was not executed // successfully. Take appropriate action here. } // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch // should be performed. The syntax required to perform a context switch // from inside an ISR varies from port to port, and from compiler to // compiler. Inspect the demos for the port you are using to find the // actual syntax required. if( xHigherPriorityTaskWoken != pdFALSE ) { // Call the interrupt safe yield function here (actual function // depends on the FreeRTOS port being used). } } @endverbatim
This is a macro that calls xQueueGenericSendFromISR(). Post an item to the back of a queue. It is safe to use this macro from within an interrupt service routine. Items are queued by copy not reference so it is preferable to only queue small items, especially when called from an ISR. In most cases it would be preferable to store a pointer to the item being queued. Example usage for buffered IO (where the ISR can obtain more than one value per call):
void vBufferISR( void ) { char cIn; BaseType_t xHigherPriorityTaskWoken; // We have not woken a task at the start of the ISR. xHigherPriorityTaskWoken = pdFALSE; // Loop until the buffer is empty. do { // Obtain a byte from the buffer. cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); // Post the byte. xQueueSendToBackFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); } while( portINPUT_BYTE( BUFFER_COUNT ) ); // Now the buffer is empty we can switch context if necessary. if( xHigherPriorityTaskWoken ) { taskYIELD (); } }
In many usage scenarios it is faster and more memory efficient to use a direct to task notification in place of a binary semaphore! http://www.freertos.org/RTOS-task-notifications.html This old vSemaphoreCreateBinary() macro is now deprecated in favour of the xSemaphoreCreateBinary() function. Note that binary semaphores created using the vSemaphoreCreateBinary() macro are created in a state such that the first call to 'take' the semaphore would pass, whereas binary semaphores created using xSemaphoreCreateBinary() are created in a state such that the the semaphore must first be 'given' before it can be 'taken'. Macro that implements a semaphore by using the existing queue mechanism. The queue length is 1 as this is a binary semaphore. The data size is 0 as we don't want to actually store any data - we just want to know if the queue is empty or full. This type of semaphore can be used for pure synchronisation between tasks or between an interrupt and a task. The semaphore need not be given back once obtained, so one task/interrupt can continuously 'give' the semaphore while another continuously 'takes' the semaphore. For this reason this type of semaphore does not use a priority inheritance mechanism. For an alternative that does use priority inheritance see xSemaphoreCreateMutex(). Example usage:
SemaphoreHandle_t xSemaphore = NULL; void vATask( void * pvParameters ) { // Semaphore cannot be used before a call to vSemaphoreCreateBinary (). // This is a macro so pass the variable in directly. vSemaphoreCreateBinary( xSemaphore ); if( xSemaphore != NULL ) { // The semaphore was created successfully. // The semaphore can now be used. } }
xSemaphoreTakeRecursive( SemaphoreHandle_t xMutex, TickType_t xBlockTime ) Macro to recursively obtain, or 'take', a mutex type semaphore. The mutex must have previously been created using a call to xSemaphoreCreateRecursiveMutex(); configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this macro to be available. This macro must not be used on mutexes created using xSemaphoreCreateMutex(). A mutex used recursively can be 'taken' repeatedly by the owner. The mutex doesn't become available again until the owner has called xSemaphoreGiveRecursive() for each successful 'take' request. For example, if a task successfully 'takes' the same mutex 5 times then the mutex will not be available to any other task until it has also 'given' the mutex back exactly five times. Example usage:
SemaphoreHandle_t xMutex = NULL; // A task that creates a mutex. void vATask( void * pvParameters ) { // Create the mutex to guard a shared resource. xMutex = xSemaphoreCreateRecursiveMutex(); } // A task that uses the mutex. void vAnotherTask( void * pvParameters ) { // ... Do other things. if( xMutex != NULL ) { // See if we can obtain the mutex. If the mutex is not available // wait 10 ticks to see if it becomes free. if( xSemaphoreTakeRecursive( xSemaphore, ( TickType_t ) 10 ) == pdTRUE ) { // We were able to obtain the mutex and can now access the // shared resource. // ... // For some reason due to the nature of the code further calls to // xSemaphoreTakeRecursive() are made on the same mutex. In real // code these would not be just sequential calls as this would make // no sense. Instead the calls are likely to be buried inside // a more complex call structure. xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); // The mutex has now been 'taken' three times, so will not be // available to another task until it has also been given back // three times. Again it is unlikely that real code would have // these calls sequentially, but instead buried in a more complex // call structure. This is just for illustrative purposes. xSemaphoreGiveRecursive( xMutex ); xSemaphoreGiveRecursive( xMutex ); xSemaphoreGiveRecursive( xMutex ); // Now the mutex can be taken by other tasks. } else { // We could not obtain the mutex and can therefore not access // the shared resource safely. } } }
Macro to recursively release, or 'give', a mutex type semaphore. The mutex must have previously been created using a call to xSemaphoreCreateRecursiveMutex(); configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this macro to be available. This macro must not be used on mutexes created using xSemaphoreCreateMutex(). A mutex used recursively can be 'taken' repeatedly by the owner. The mutex doesn't become available again until the owner has called xSemaphoreGiveRecursive() for each successful 'take' request. For example, if a task successfully 'takes' the same mutex 5 times then the mutex will not be available to any other task until it has also 'given' the mutex back exactly five times. Example usage:
SemaphoreHandle_t xMutex = NULL; // A task that creates a mutex. void vATask( void * pvParameters ) { // Create the mutex to guard a shared resource. xMutex = xSemaphoreCreateRecursiveMutex(); } // A task that uses the mutex. void vAnotherTask( void * pvParameters ) { // ... Do other things. if( xMutex != NULL ) { // See if we can obtain the mutex. If the mutex is not available // wait 10 ticks to see if it becomes free. if( xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ) == pdTRUE ) { // We were able to obtain the mutex and can now access the // shared resource. // ... // For some reason due to the nature of the code further calls to // xSemaphoreTakeRecursive() are made on the same mutex. In real // code these would not be just sequential calls as this would make // no sense. Instead the calls are likely to be buried inside // a more complex call structure. xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); // The mutex has now been 'taken' three times, so will not be // available to another task until it has also been given back // three times. Again it is unlikely that real code would have // these calls sequentially, it would be more likely that the calls // to xSemaphoreGiveRecursive() would be called as a call stack // unwound. This is just for demonstrative purposes. xSemaphoreGiveRecursive( xMutex ); xSemaphoreGiveRecursive( xMutex ); xSemaphoreGiveRecursive( xMutex ); // Now the mutex can be taken by other tasks. } else { // We could not obtain the mutex and can therefore not access // the shared resource safely. } } }
Creates a new mutex type semaphore instance, and returns a handle by which the new mutex can be referenced. Internally, within the FreeRTOS implementation, mutex semaphores use a block of memory, in which the mutex structure is stored. If a mutex is created using xSemaphoreCreateMutex() then the required memory is automatically dynamically allocated inside the xSemaphoreCreateMutex() function. (see http://www.freertos.org/a00111.html). If a mutex is created using xSemaphoreCreateMutexStatic() then the application writer must provided the memory. xSemaphoreCreateMutexStatic() therefore allows a mutex to be created without using any dynamic memory allocation. Mutexes created using this function can be accessed using the xSemaphoreTake() and xSemaphoreGive() macros. The xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros must not be used. This type of semaphore uses a priority inheritance mechanism so a task 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the semaphore it is no longer required. Mutex type semaphores cannot be used from within interrupt service routines. See xSemaphoreCreateBinary() for an alternative implementation that can be used for pure synchronisation (where one task or interrupt always 'gives' the semaphore and another always 'takes' the semaphore) and from within interrupt service routines. Example usage:
SemaphoreHandle_t xSemaphore; void vATask( void * pvParameters ) { // Semaphore cannot be used before a call to xSemaphoreCreateMutex(). // This is a macro so pass the variable in directly. xSemaphore = xSemaphoreCreateMutex(); if( xSemaphore != NULL ) { // The semaphore was created successfully. // The semaphore can now be used. } }
Creates a new recursive mutex type semaphore instance, and returns a handle by which the new recursive mutex can be referenced. Internally, within the FreeRTOS implementation, recursive mutexs use a block of memory, in which the mutex structure is stored. If a recursive mutex is created using xSemaphoreCreateRecursiveMutex() then the required memory is automatically dynamically allocated inside the xSemaphoreCreateRecursiveMutex() function. (see http://www.freertos.org/a00111.html). If a recursive mutex is created using xSemaphoreCreateRecursiveMutexStatic() then the application writer must provide the memory that will get used by the mutex. xSemaphoreCreateRecursiveMutexStatic() therefore allows a recursive mutex to be created without using any dynamic memory allocation. Mutexes created using this macro can be accessed using the xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros. The xSemaphoreTake() and xSemaphoreGive() macros must not be used. A mutex used recursively can be 'taken' repeatedly by the owner. The mutex doesn't become available again until the owner has called xSemaphoreGiveRecursive() for each successful 'take' request. For example, if a task successfully 'takes' the same mutex 5 times then the mutex will not be available to any other task until it has also 'given' the mutex back exactly five times. This type of semaphore uses a priority inheritance mechanism so a task 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the semaphore it is no longer required. Mutex type semaphores cannot be used from within interrupt service routines. See xSemaphoreCreateBinary() for an alternative implementation that can be used for pure synchronisation (where one task or interrupt always 'gives' the semaphore and another always 'takes' the semaphore) and from within interrupt service routines. Example usage:
SemaphoreHandle_t xSemaphore; void vATask( void * pvParameters ) { // Semaphore cannot be used before a call to xSemaphoreCreateMutex(). // This is a macro so pass the variable in directly. xSemaphore = xSemaphoreCreateRecursiveMutex(); if( xSemaphore != NULL ) { // The semaphore was created successfully. // The semaphore can now be used. } }
Creates a new counting semaphore instance, and returns a handle by which the new counting semaphore can be referenced. In many usage scenarios it is faster and more memory efficient to use a direct to task notification in place of a counting semaphore! http://www.freertos.org/RTOS-task-notifications.html Internally, within the FreeRTOS implementation, counting semaphores use a block of memory, in which the counting semaphore structure is stored. If a counting semaphore is created using xSemaphoreCreateCounting() then the required memory is automatically dynamically allocated inside the xSemaphoreCreateCounting() function. (see http://www.freertos.org/a00111.html). If a counting semaphore is created using xSemaphoreCreateCountingStatic() then the application writer can instead optionally provide the memory that will get used by the counting semaphore. xSemaphoreCreateCountingStatic() therefore allows a counting semaphore to be created without using any dynamic memory allocation. Counting semaphores are typically used for two things: 1) Counting events. In this usage scenario an event handler will 'give' a semaphore each time an event occurs (incrementing the semaphore count value), and a handler task will 'take' a semaphore each time it processes an event (decrementing the semaphore count value). The count value is therefore the difference between the number of events that have occurred and the number that have been processed. In this case it is desirable for the initial count value to be zero. 2) Resource management. In this usage scenario the count value indicates the number of resources available. To obtain control of a resource a task must first obtain a semaphore - decrementing the semaphore count value. When the count value reaches zero there are no free resources. When a task finishes with the resource it 'gives' the semaphore back - incrementing the semaphore count value. In this case it is desirable for the initial count value to be equal to the maximum count value, indicating that all resources are free. Example usage:
SemaphoreHandle_t xSemaphore; void vATask( void * pvParameters ) { SemaphoreHandle_t xSemaphore = NULL; // Semaphore cannot be used before a call to xSemaphoreCreateCounting(). // The max value to which the semaphore can count should be 10, and the // initial value assigned to the count should be 0. xSemaphore = xSemaphoreCreateCounting( 10, 0 ); if( xSemaphore != NULL ) { // The semaphore was created successfully. // The semaphore can now be used. } }
Delete a semaphore. This function must be used with care. For example, do not delete a mutex type semaphore if the mutex is held by a task.
If the semaphore is a counting semaphore then uxSemaphoreGetCount() returns its current count value. If the semaphore is a binary semaphore then uxSemaphoreGetCount() returns 1 if the semaphore is available, and 0 if the semaphore is not available.
Checks whether or not the processor is privileged.
Raise an SVC request to raise privilege.
Lowers the privilege level by setting the bit 0 of the CONTROL register.
Macro to enable microcontroller interrupts.
configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this macro to be available. When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private "notification value", which is a 32-bit unsigned integer (uint32_t). Events can be sent to a task using an intermediary object. Examples of such objects are queues, semaphores, mutexes and event groups. Task notifications are a method of sending an event directly to a task without the need for such an intermediary object. A notification sent to a task can optionally perform an action, such as update, overwrite or increment the task's notification value. In that way task notifications can be used to send data to a task, or be used as light weight and fast binary or counting semaphores. xTaskNotifyGive() is a helper macro intended for use when task notifications are used as light weight and faster binary or counting semaphore equivalents. Actual FreeRTOS semaphores are given using the xSemaphoreGive() API function, the equivalent action that instead uses a task notification is xTaskNotifyGive(). When task notifications are being used as a binary or counting semaphore equivalent then the task being notified should wait for the notification using the ulTaskNotificationTake() API function rather than the xTaskNotifyWait() API function. See http://www.FreeRTOS.org/RTOS-task-notifications.html for more details.
BaseType_t xTimerStart( TimerHandle_t xTimer, TickType_t xTicksToWait ); Timer functionality is provided by a timer service/daemon task. Many of the public FreeRTOS timer API functions send commands to the timer service task through a queue called the timer command queue. The timer command queue is private to the kernel itself and is not directly accessible to application code. The length of the timer command queue is set by the configTIMER_QUEUE_LENGTH configuration constant. xTimerStart() starts a timer that was previously created using the xTimerCreate() API function. If the timer had already been started and was already in the active state, then xTimerStart() has equivalent functionality to the xTimerReset() API function. Starting a timer ensures the timer is in the active state. If the timer is not stopped, deleted, or reset in the mean time, the callback function associated with the timer will get called 'n' ticks after xTimerStart() was called, where 'n' is the timers defined period. It is valid to call xTimerStart() before the scheduler has been started, but when this is done the timer will not actually start until the scheduler is started, and the timers expiry time will be relative to when the scheduler is started, not relative to when xTimerStart() was called. The configUSE_TIMERS configuration constant must be set to 1 for xTimerStart() to be available. Example usage: See the xTimerCreate() API function example usage scenario.
BaseType_t xTimerReset( TimerHandle_t xTimer, TickType_t xTicksToWait ); Timer functionality is provided by a timer service/daemon task. Many of the public FreeRTOS timer API functions send commands to the timer service task through a queue called the timer command queue. The timer command queue is private to the kernel itself and is not directly accessible to application code. The length of the timer command queue is set by the configTIMER_QUEUE_LENGTH configuration constant. xTimerReset() re-starts a timer that was previously created using the xTimerCreate() API function. If the timer had already been started and was already in the active state, then xTimerReset() will cause the timer to re-evaluate its expiry time so that it is relative to when xTimerReset() was called. If the timer was in the dormant state then xTimerReset() has equivalent functionality to the xTimerStart() API function. Resetting a timer ensures the timer is in the active state. If the timer is not stopped, deleted, or reset in the mean time, the callback function associated with the timer will get called 'n' ticks after xTimerReset() was called, where 'n' is the timers defined period. It is valid to call xTimerReset() before the scheduler has been started, but when this is done the timer will not actually start until the scheduler is started, and the timers expiry time will be relative to when the scheduler is started, not relative to when xTimerReset() was called. The configUSE_TIMERS configuration constant must be set to 1 for xTimerReset() to be available. Example usage: @verbatim // When a key is pressed, an LCD back-light is switched on. If 5 seconds pass // without a key being pressed, then the LCD back-light is switched off. In // this case, the timer is a one-shot timer. TimerHandle_t xBacklightTimer = NULL; // The callback function assigned to the one-shot timer. In this case the // parameter is not used. void vBacklightTimerCallback( TimerHandle_t pxTimer ) { // The timer expired, therefore 5 seconds must have passed since a key // was pressed. Switch off the LCD back-light. vSetBacklightState( BACKLIGHT_OFF ); } // The key press event handler. void vKeyPressEventHandler( char cKey ) { // Ensure the LCD back-light is on, then reset the timer that is // responsible for turning the back-light off after 5 seconds of // key inactivity. Wait 10 ticks for the command to be successfully sent // if it cannot be sent immediately. vSetBacklightState( BACKLIGHT_ON ); if( xTimerReset( xBacklightTimer, 100 ) != pdPASS ) { // The reset command was not executed successfully. Take appropriate // action here. } // Perform the rest of the key processing here. } void main( void ) { int32_t x; // Create then start the one-shot timer that is responsible for turning // the back-light off if no keys are pressed within a 5 second period. xBacklightTimer = xTimerCreate( "BacklightTimer", // Just a text name, not used by the kernel. ( 5000 / portTICK_PERIOD_MS), // The timer period in ticks. pdFALSE, // The timer is a one-shot timer. 0, // The id is not used by the callback so can take any value. vBacklightTimerCallback // The callback function that switches the LCD back-light off. ); if( xBacklightTimer == NULL ) { // The timer was not created. } else { // Start the timer. No block time is specified, and even if one was // it would be ignored because the scheduler has not yet been // started. if( xTimerStart( xBacklightTimer, 0 ) != pdPASS ) { // The timer could not be set into the Active state. } } // ... // Create tasks here. // ... // Starting the scheduler will start the timer running as it has already // been set into the active state. vTaskStartScheduler(); // Should not reach here. for( ;; ); } @endverbatim
BaseType_t xTimerStartFromISR( TimerHandle_t xTimer, BaseType_t *pxHigherPriorityTaskWoken ); A version of xTimerStart() that can be called from an interrupt service routine. Example usage: @verbatim // This scenario assumes xBacklightTimer has already been created. When a // key is pressed, an LCD back-light is switched on. If 5 seconds pass // without a key being pressed, then the LCD back-light is switched off. In // this case, the timer is a one-shot timer, and unlike the example given for // the xTimerReset() function, the key press event handler is an interrupt // service routine. // The callback function assigned to the one-shot timer. In this case the // parameter is not used. void vBacklightTimerCallback( TimerHandle_t pxTimer ) { // The timer expired, therefore 5 seconds must have passed since a key // was pressed. Switch off the LCD back-light. vSetBacklightState( BACKLIGHT_OFF ); } // The key press interrupt service routine. void vKeyPressEventInterruptHandler( void ) { BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Ensure the LCD back-light is on, then restart the timer that is // responsible for turning the back-light off after 5 seconds of // key inactivity. This is an interrupt service routine so can only // call FreeRTOS API functions that end in "FromISR". vSetBacklightState( BACKLIGHT_ON ); // xTimerStartFromISR() or xTimerResetFromISR() could be called here // as both cause the timer to re-calculate its expiry time. // xHigherPriorityTaskWoken was initialised to pdFALSE when it was // declared (in this function). if( xTimerStartFromISR( xBacklightTimer, &xHigherPriorityTaskWoken ) != pdPASS ) { // The start command was not executed successfully. Take appropriate // action here. } // Perform the rest of the key processing here. // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch // should be performed. The syntax required to perform a context switch // from inside an ISR varies from port to port, and from compiler to // compiler. Inspect the demos for the port you are using to find the // actual syntax required. if( xHigherPriorityTaskWoken != pdFALSE ) { // Call the interrupt safe yield function here (actual function // depends on the FreeRTOS port being used). } } @endverbatim
BaseType_t xTimerResetFromISR( TimerHandle_t xTimer, BaseType_t *pxHigherPriorityTaskWoken ); A version of xTimerReset() that can be called from an interrupt service routine. Example usage: @verbatim // This scenario assumes xBacklightTimer has already been created. When a // key is pressed, an LCD back-light is switched on. If 5 seconds pass // without a key being pressed, then the LCD back-light is switched off. In // this case, the timer is a one-shot timer, and unlike the example given for // the xTimerReset() function, the key press event handler is an interrupt // service routine. // The callback function assigned to the one-shot timer. In this case the // parameter is not used. void vBacklightTimerCallback( TimerHandle_t pxTimer ) { // The timer expired, therefore 5 seconds must have passed since a key // was pressed. Switch off the LCD back-light. vSetBacklightState( BACKLIGHT_OFF ); } // The key press interrupt service routine. void vKeyPressEventInterruptHandler( void ) { BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Ensure the LCD back-light is on, then reset the timer that is // responsible for turning the back-light off after 5 seconds of // key inactivity. This is an interrupt service routine so can only // call FreeRTOS API functions that end in "FromISR". vSetBacklightState( BACKLIGHT_ON ); // xTimerStartFromISR() or xTimerResetFromISR() could be called here // as both cause the timer to re-calculate its expiry time. // xHigherPriorityTaskWoken was initialised to pdFALSE when it was // declared (in this function). if( xTimerResetFromISR( xBacklightTimer, &xHigherPriorityTaskWoken ) != pdPASS ) { // The reset command was not executed successfully. Take appropriate // action here. } // Perform the rest of the key processing here. // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch // should be performed. The syntax required to perform a context switch // from inside an ISR varies from port to port, and from compiler to // compiler. Inspect the demos for the port you are using to find the // actual syntax required. if( xHigherPriorityTaskWoken != pdFALSE ) { // Call the interrupt safe yield function here (actual function // depends on the FreeRTOS port being used). } } @endverbatim
Post an item to the front of a queue. The item is queued by copy, not by reference. This function must not be called from an interrupt service routine. See xQueueSendFromISR () for an alternative which may be used in an ISR. Example usage:
struct AMessage { char ucMessageID; char ucData[ 20 ]; } xMessage; uint32_t ulVar = 10UL; void vATask( void *pvParameters ) { QueueHandle_t xQueue1, xQueue2; struct AMessage *pxMessage; // Create a queue capable of containing 10 uint32_t values. xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); // Create a queue capable of containing 10 pointers to AMessage structures. // These should be passed by pointer as they contain a lot of data. xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); // ... if( xQueue1 != 0 ) { // Send an uint32_t. Wait for 10 ticks for space to become // available if necessary. if( xQueueSendToFront( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS ) { // Failed to post the message, even after 10 ticks. } } if( xQueue2 != 0 ) { // Send a pointer to a struct AMessage object. Don't block if the // queue is already full. pxMessage = & xMessage; xQueueSendToFront( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 ); } // ... Rest of task code. }
Only for use with queues that have a length of one - so the queue is either empty or full. Post an item on a queue. If the queue is already full then overwrite the value held in the queue. The item is queued by copy, not by reference. This function must not be called from an interrupt service routine. See xQueueOverwriteFromISR () for an alternative which may be used in an ISR. Example usage:
void vFunction( void *pvParameters ) { QueueHandle_t xQueue; uint32_t ulVarToSend, ulValReceived; // Create a queue to hold one uint32_t value. It is strongly // recommended *not* to use xQueueOverwrite() on queues that can // contain more than one value, and doing so will trigger an assertion // if configASSERT() is defined. xQueue = xQueueCreate( 1, sizeof( uint32_t ) ); // Write the value 10 to the queue using xQueueOverwrite(). ulVarToSend = 10; xQueueOverwrite( xQueue, &ulVarToSend ); // Peeking the queue should now return 10, but leave the value 10 in // the queue. A block time of zero is used as it is known that the // queue holds a value. ulValReceived = 0; xQueuePeek( xQueue, &ulValReceived, 0 ); if( ulValReceived != 10 ) { // Error unless the item was removed by a different task. } // The queue is still full. Use xQueueOverwrite() to overwrite the // value held in the queue with 100. ulVarToSend = 100; xQueueOverwrite( xQueue, &ulVarToSend ); // This time read from the queue, leaving the queue empty once more. // A block time of 0 is used again. xQueueReceive( xQueue, &ulValReceived, 0 ); // The value read should be the last value written, even though the // queue was already full when the value was written. if( ulValReceived != 100 ) { // Error! } // ... }
This is a macro that calls xQueueGenericSendFromISR(). Post an item to the front of a queue. It is safe to use this macro from within an interrupt service routine. Items are queued by copy not reference so it is preferable to only queue small items, especially when called from an ISR. In most cases it would be preferable to store a pointer to the item being queued. Example usage for buffered IO (where the ISR can obtain more than one value per call):
void vBufferISR( void ) { char cIn; BaseType_t xHigherPrioritTaskWoken; // We have not woken a task at the start of the ISR. xHigherPriorityTaskWoken = pdFALSE; // Loop until the buffer is empty. do { // Obtain a byte from the buffer. cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); // Post the byte. xQueueSendToFrontFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); } while( portINPUT_BYTE( BUFFER_COUNT ) ); // Now the buffer is empty we can switch context if necessary. if( xHigherPriorityTaskWoken ) { taskYIELD (); } }
A version of xQueueOverwrite() that can be used in an interrupt service routine (ISR). Only for use with queues that can hold a single item - so the queue is either empty or full. Post an item on a queue. If the queue is already full then overwrite the value held in the queue. The item is queued by copy, not by reference. Example usage:
QueueHandle_t xQueue; void vFunction( void *pvParameters ) { // Create a queue to hold one uint32_t value. It is strongly // recommended *not* to use xQueueOverwriteFromISR() on queues that can // contain more than one value, and doing so will trigger an assertion // if configASSERT() is defined. xQueue = xQueueCreate( 1, sizeof( uint32_t ) ); } void vAnInterruptHandler( void ) { // xHigherPriorityTaskWoken must be set to pdFALSE before it is used. BaseType_t xHigherPriorityTaskWoken = pdFALSE; uint32_t ulVarToSend, ulValReceived; // Write the value 10 to the queue using xQueueOverwriteFromISR(). ulVarToSend = 10; xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken ); // The queue is full, but calling xQueueOverwriteFromISR() again will still // pass because the value held in the queue will be overwritten with the // new value. ulVarToSend = 100; xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken ); // Reading from the queue will now return 100. // ... if( xHigherPrioritytaskWoken == pdTRUE ) { // Writing to the queue caused a task to unblock and the unblocked task // has a priority higher than or equal to the priority of the currently // executing task (the task this interrupt interrupted). Perform a context // switch so this interrupt returns directly to the unblocked task. portYIELD_FROM_ISR(); // or portEND_SWITCHING_ISR() depending on the port. } }
If xMutex is indeed a mutex type semaphore, return the current mutex holder. If xMutex is not a mutex type semaphore, or the mutex is available (not held by a task), return NULL. Note: This is a good way of determining if the calling task is the mutex holder, but not a good way of determining the identity of the mutex holder as the holder may change between the function exiting and the returned value being tested.
If xMutex is indeed a mutex type semaphore, return the current mutex holder. If xMutex is not a mutex type semaphore, or the mutex is available (not held by a task), return NULL.
Returns the current value of the bits in an event group. This function cannot be used from an interrupt.
\page cmsis_os_h Header File Template: cmsis_os.h The file \b cmsis_os.h is a template header file for a CMSIS-RTOS compliant Real-Time Operating System (RTOS). Each RTOS that is compliant with CMSIS-RTOS shall provide a specific \b cmsis_os.h header file that represents its implementation. The file cmsis_os.h contains: - CMSIS-RTOS API function definitions - struct definitions for parameters and return types - status and priority values used by CMSIS-RTOS API functions - macros for defining threads and other kernel objects Name conventions and header file modifications All definitions are prefixed with \b os to give an unique name space for CMSIS-RTOS functions. Definitions that are prefixed \b os_ are not used in the application code but local to this header file. All definitions and functions that belong to a module are grouped and have a common prefix, i.e. \b osThread. Definitions that are marked with CAN BE CHANGED can be adapted towards the needs of the actual CMSIS-RTOS implementation. These definitions can be specific to the underlying RTOS kernel. Definitions that are marked with MUST REMAIN UNCHANGED cannot be altered. Otherwise the CMSIS-RTOS implementation is no longer compliant to the standard. Note that some functions are optional and need not to be provided by every CMSIS-RTOS implementation. Function calls from interrupt service routines The following CMSIS-RTOS functions can be called from threads and interrupt service routines (ISR): - osSignalSet - osSemaphoreRelease - osPoolAlloc, osPoolCAlloc, osPoolFree - osMessagePut, osMessageGet - osMailAlloc, osMailCAlloc, osMailGet, osMailPut, osMailFree Functions that cannot be called from an ISR are verifying the interrupt status and return in case that they are called from an ISR context the status code \b osErrorISR. In some implementations this condition might be caught using the HARD FAULT vector. Some CMSIS-RTOS implementations support CMSIS-RTOS function calls from multiple ISR at the same time. If this is impossible, the CMSIS-RTOS rejects calls by nested ISR functions with the status code \b osErrorISRRecursive. Define and reference object definitions With \#define osObjectsExternal objects are defined as external symbols. This allows to create a consistent header file that is used throughout a project as shown below: Header File \code #include // CMSIS RTOS header file // Thread definition extern void thread_sample (void const *argument); // function prototype osThreadDef (thread_sample, osPriorityBelowNormal, 1, 100); // Pool definition osPoolDef(MyPool, 10, long); \endcode This header file defines all objects when included in a C/C++ source file. When \#define osObjectsExternal is present before the header file, the objects are defined as external symbols. A single consistent header file can therefore be used throughout the whole project. Example \code #include "osObjects.h" // Definition of the CMSIS-RTOS objects \endcode \code #define osObjectExternal // Objects will be defined as external symbols #include "osObjects.h" // Reference to the CMSIS-RTOS objects \endcode
The RTOS kernel system timer frequency in Hz
Convert a microseconds value to a RTOS kernel system timer value.
Access a Memory Pool definition.
This macro MUST always be called at the start of a co-routine function. Example usage:
// Co-routine to be created. void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex ) { // Variables in co-routines must be declared static if they must maintain value across a blocking call. static int32_t ulAVariable; // Must start every co-routine with a call to crSTART(); crSTART( xHandle ); for( ;; ) { // Co-routine functionality goes here. } // Must end every co-routine with a call to crEND(); crEND(); }
This macro MUST always be called at the end of a co-routine function. Example usage:
// Co-routine to be created. void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex ) { // Variables in co-routines must be declared static if they must maintain value across a blocking call. static int32_t ulAVariable; // Must start every co-routine with a call to crSTART(); crSTART( xHandle ); for( ;; ) { // Co-routine functionality goes here. } // Must end every co-routine with a call to crEND(); crEND(); }
Delay a co-routine for a fixed period of time. crDELAY can only be called from the co-routine function itself - not from within a function called by the co-routine function. This is because co-routines do not maintain their own stack. Example usage:
// Co-routine to be created. void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex ) { // Variables in co-routines must be declared static if they must maintain value across a blocking call. // This may not be necessary for const variables. // We are to delay for 200ms. static const xTickType xDelayTime = 200 / portTICK_PERIOD_MS; // Must start every co-routine with a call to crSTART(); crSTART( xHandle ); for( ;; ) { // Delay for 200ms. crDELAY( xHandle, xDelayTime ); // Do something here. } // Must end every co-routine with a call to crEND(); crEND(); }
crQUEUE_SEND( CoRoutineHandle_t xHandle, QueueHandle_t pxQueue, void *pvItemToQueue, TickType_t xTicksToWait, BaseType_t *pxResult )
The macro's crQUEUE_SEND() and crQUEUE_RECEIVE() are the co-routine equivalent to the xQueueSend() and xQueueReceive() functions used by tasks. crQUEUE_SEND and crQUEUE_RECEIVE can only be used from a co-routine whereas xQueueSend() and xQueueReceive() can only be used from tasks. crQUEUE_SEND can only be called from the co-routine function itself - not from within a function called by the co-routine function. This is because co-routines do not maintain their own stack. See the co-routine section of the WEB documentation for information on passing data between tasks and co-routines and between ISR's and co-routines. Example usage:
// Co-routine function that blocks for a fixed period then posts a number onto // a queue. static void prvCoRoutineFlashTask( CoRoutineHandle_t xHandle, UBaseType_t uxIndex ) { // Variables in co-routines must be declared static if they must maintain value across a blocking call. static BaseType_t xNumberToPost = 0; static BaseType_t xResult; // Co-routines must begin with a call to crSTART(). crSTART( xHandle ); for( ;; ) { // This assumes the queue has already been created. crQUEUE_SEND( xHandle, xCoRoutineQueue, &xNumberToPost, NO_DELAY, &xResult ); if( xResult != pdPASS ) { // The message was not posted! } // Increment the number to be posted onto the queue. xNumberToPost++; // Delay for 100 ticks. crDELAY( xHandle, 100 ); } // Co-routines must end with a call to crEND(). crEND(); }
The macro's crQUEUE_SEND() and crQUEUE_RECEIVE() are the co-routine equivalent to the xQueueSend() and xQueueReceive() functions used by tasks. crQUEUE_SEND and crQUEUE_RECEIVE can only be used from a co-routine whereas xQueueSend() and xQueueReceive() can only be used from tasks. crQUEUE_RECEIVE can only be called from the co-routine function itself - not from within a function called by the co-routine function. This is because co-routines do not maintain their own stack. See the co-routine section of the WEB documentation for information on passing data between tasks and co-routines and between ISR's and co-routines. Example usage:
// A co-routine receives the number of an LED to flash from a queue. It // blocks on the queue until the number is received. static void prvCoRoutineFlashWorkTask( CoRoutineHandle_t xHandle, UBaseType_t uxIndex ) { // Variables in co-routines must be declared static if they must maintain value across a blocking call. static BaseType_t xResult; static UBaseType_t uxLEDToFlash; // All co-routines must start with a call to crSTART(). crSTART( xHandle ); for( ;; ) { // Wait for data to become available on the queue. crQUEUE_RECEIVE( xHandle, xCoRoutineQueue, &uxLEDToFlash, portMAX_DELAY, &xResult ); if( xResult == pdPASS ) { // We received the LED to flash - flash it! vParTestToggleLED( uxLEDToFlash ); } } crEND(); }
The macro's crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() are the co-routine equivalent to the xQueueSendFromISR() and xQueueReceiveFromISR() functions used by tasks. crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() can only be used to pass data between a co-routine and and ISR, whereas xQueueSendFromISR() and xQueueReceiveFromISR() can only be used to pass data between a task and and ISR. crQUEUE_SEND_FROM_ISR can only be called from an ISR to send data to a queue that is being used from within a co-routine. See the co-routine section of the WEB documentation for information on passing data between tasks and co-routines and between ISR's and co-routines. Example usage:
// A co-routine that blocks on a queue waiting for characters to be received. static void vReceivingCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex ) { char cRxedChar; BaseType_t xResult; // All co-routines must start with a call to crSTART(). crSTART( xHandle ); for( ;; ) { // Wait for data to become available on the queue. This assumes the // queue xCommsRxQueue has already been created! crQUEUE_RECEIVE( xHandle, xCommsRxQueue, &uxLEDToFlash, portMAX_DELAY, &xResult ); // Was a character received? if( xResult == pdPASS ) { // Process the character here. } } // All co-routines must end with a call to crEND(). crEND(); } // An ISR that uses a queue to send characters received on a serial port to // a co-routine. void vUART_ISR( void ) { char cRxedChar; BaseType_t xCRWokenByPost = pdFALSE; // We loop around reading characters until there are none left in the UART. while( UART_RX_REG_NOT_EMPTY() ) { // Obtain the character from the UART. cRxedChar = UART_RX_REG; // Post the character onto a queue. xCRWokenByPost will be pdFALSE // the first time around the loop. If the post causes a co-routine // to be woken (unblocked) then xCRWokenByPost will be set to pdTRUE. // In this manner we can ensure that if more than one co-routine is // blocked on the queue only one is woken by this ISR no matter how // many characters are posted to the queue. xCRWokenByPost = crQUEUE_SEND_FROM_ISR( xCommsRxQueue, &cRxedChar, xCRWokenByPost ); } }
The macro's crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() are the co-routine equivalent to the xQueueSendFromISR() and xQueueReceiveFromISR() functions used by tasks. crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() can only be used to pass data between a co-routine and and ISR, whereas xQueueSendFromISR() and xQueueReceiveFromISR() can only be used to pass data between a task and and ISR. crQUEUE_RECEIVE_FROM_ISR can only be called from an ISR to receive data from a queue that is being used from within a co-routine (a co-routine posted to the queue). See the co-routine section of the WEB documentation for information on passing data between tasks and co-routines and between ISR's and co-routines. Example usage:
// A co-routine that posts a character to a queue then blocks for a fixed // period. The character is incremented each time. static void vSendingCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex ) { // cChar holds its value while this co-routine is blocked and must therefore // be declared static. static char cCharToTx = 'a'; BaseType_t xResult; // All co-routines must start with a call to crSTART(). crSTART( xHandle ); for( ;; ) { // Send the next character to the queue. crQUEUE_SEND( xHandle, xCoRoutineQueue, &cCharToTx, NO_DELAY, &xResult ); if( xResult == pdPASS ) { // The character was successfully posted to the queue. } else { // Could not post the character to the queue. } // Enable the UART Tx interrupt to cause an interrupt in this // hypothetical UART. The interrupt will obtain the character // from the queue and send it. ENABLE_RX_INTERRUPT(); // Increment to the next character then block for a fixed period. // cCharToTx will maintain its value across the delay as it is // declared static. cCharToTx++; if( cCharToTx > 'x' ) { cCharToTx = 'a'; } crDELAY( 100 ); } // All co-routines must end with a call to crEND(). crEND(); } // An ISR that uses a queue to receive characters to send on a UART. void vUART_ISR( void ) { char cCharToTx; BaseType_t xCRWokenByPost = pdFALSE; while( UART_TX_REG_EMPTY() ) { // Are there any characters in the queue waiting to be sent? // xCRWokenByPost will automatically be set to pdTRUE if a co-routine // is woken by the post - ensuring that only a single co-routine is // woken no matter how many times we go around this loop. if( crQUEUE_RECEIVE_FROM_ISR( pxQueue, &cCharToTx, &xCRWokenByPost ) ) { SEND_CHARACTER( cCharToTx ); } } }
message_buffer.h
StreamBufferHandle_t xStreamBufferCreate( size_t xBufferSizeBytes, size_t xTriggerLevelBytes );
Creates a new stream buffer using dynamically allocated memory. See xStreamBufferCreateStatic() for a version that uses statically allocated memory (memory that is allocated at compile time). configSUPPORT_DYNAMIC_ALLOCATION must be set to 1 or left undefined in FreeRTOSConfig.h for xStreamBufferCreate() to be available. Example use:
void vAFunction( void ) { StreamBufferHandle_t xStreamBuffer; const size_t xStreamBufferSizeBytes = 100, xTriggerLevel = 10; // Create a stream buffer that can hold 100 bytes. The memory used to hold // both the stream buffer structure and the data in the stream buffer is // allocated dynamically. xStreamBuffer = xStreamBufferCreate( xStreamBufferSizeBytes, xTriggerLevel ); if( xStreamBuffer == NULL ) { // There was not enough heap memory space available to create the // stream buffer. } else { // The stream buffer was created successfully and can now be used. } }
StreamBufferHandle_t xStreamBufferCreateStatic( size_t xBufferSizeBytes, size_t xTriggerLevelBytes, uint8_t *pucStreamBufferStorageArea, StaticStreamBuffer_t *pxStaticStreamBuffer );
Creates a new stream buffer using statically allocated memory. See xStreamBufferCreate() for a version that uses dynamically allocated memory. configSUPPORT_STATIC_ALLOCATION must be set to 1 in FreeRTOSConfig.h for xStreamBufferCreateStatic() to be available. Example use:
// Used to dimension the array used to hold the streams. The available space // will actually be one less than this, so 999. #define STORAGE_SIZE_BYTES 1000 // Defines the memory that will actually hold the streams within the stream // buffer. static uint8_t ucStorageBuffer[ STORAGE_SIZE_BYTES ]; // The variable used to hold the stream buffer structure. StaticStreamBuffer_t xStreamBufferStruct; void MyFunction( void ) { StreamBufferHandle_t xStreamBuffer; const size_t xTriggerLevel = 1; xStreamBuffer = xStreamBufferCreateStatic( sizeof( ucBufferStorage ), xTriggerLevel, ucBufferStorage, &xStreamBufferStruct ); // As neither the pucStreamBufferStorageArea or pxStaticStreamBuffer // parameters were NULL, xStreamBuffer will not be NULL, and can be used to // reference the created stream buffer in other stream buffer API calls. // Other code that uses the stream buffer can go here. }

Dependencies