Handling Software Timers in FreeRTOS

Software timers are an important feature of FreeRTOS, which is a popular open-source real-time operating system for embedded systems. FreeRTOS provides a set of APIs for creating and managing software timers, which can be used to trigger tasks or events at specific intervals or points in time.

The software timers in FreeRTOS are implemented using a combination of software counters and interrupts, which are used to trigger the timer callbacks when the timer expires. The software timers can be configured to operate at a specified time interval or to trigger a callback at a specific time.

What is Software Timer in FreeRTOS?

In FreeRTOS, a software timer is a mechanism that allows tasks to schedule actions to occur at specific intervals, or at specific points in time, without having to block and wait for those actions to complete.

Software timers are implemented as tasks that execute at specific intervals, and can be started, stopped, and restarted dynamically from other tasks. When a software timer expires, it generates an event that can be used to signal other tasks or to execute a specific callback function.

Software timers are often used in embedded systems to perform periodic tasks such as updating sensors, sending data, or triggering actions based on specific events. By using software timers, tasks can be designed to run independently and asynchronously, which can improve system performance and reduce the complexity of the code.

How the Software Timer works in freeRTOS?

In FreeRTOS, software timers are implemented as tasks that are created and managed by the timer service. When a software timer is created using the xTimerCreate() function, the timer service creates a timer task with a specific priority and sets a timer period, which determines when the timer task will execute.

When a software timer is started using the xTimerStart() function, the timer service waits for the timer period to elapse. When the timer period expires, the timer task is executed and the timer service generates a timer event.

The timer event can be handled in a number of ways, depending on the requirements of the system. For example, the timer event can be used to signal a semaphore or a queue, which can be used to trigger a specific action or to wake up a task that was blocked waiting for the event.

Alternatively, the timer event can be used to execute a specific callback function, which can perform a specific action or update the state of the system. The callback function is specified when the software timer is created using the pvTimerCallback parameter.

After the timer event has been processed, the timer service waits for the timer period to elapse again, and the process repeats until the software timer is stopped or deleted using the xTimerStop() or xTimerDelete() functions.

Software timers in FreeRTOS are implemented as tasks that are created and managed by the timer service. They allow tasks to schedule actions to occur at specific intervals or points in time, without blocking and waiting for those actions to complete, and can be used to perform periodic tasks or trigger actions based on specific events.

What are the APIs used for the software timers ?

FreeRTOS provides a set of API functions to create, manage and use software timers. Here are some of the main software timer API functions in FreeRTOS with their syntax and brief descriptions:

1. xTimerCreate: This API creates a new software timer and returns a handle to the timer.

Syntax:

TimerHandle_t xTimerCreate( const char *pcTimerName,

TickType_t xTimerPeriod,

UBaseType_t uxAutoReload,

void * pvTimerID,

TimerCallbackFunction_t pxCallbackFunction );

Parameters:

pcTimerName: The name of the timer, used for debugging purposes.

xTimerPeriod: The period of the timer in tick periods.

uxAutoReload: If set to pdTRUE, the timer will automatically reload with the same period after

each time it expires. If set to pdFALSE, the timer will only expire once.

pvTimerID: An optional parameter that can be used to pass a value to the callback function.

pxCallbackFunction: A pointer to the callback function that will be called when the timer expires.


2. xTimerStart: This API starts a software timer.

Syntax:

BaseType_t xTimerStart( TimerHandle_t xTimer, TickType_t xTicksToWait );

Parameters:

xTimer: The handle of the timer to start.

xTicksToWait: The time, in tick periods, to wait before starting the timer.


3. xTimerStop: This API stops a software timer.

Syntax:

BaseType_t xTimerStop( TimerHandle_t xTimer, TickType_t xTicksToWait );

Parameters:

xTimer: The handle of the timer to stop.

xTicksToWait: The time, in tick periods, to wait before stopping the timer.


4. xTimerDelete: This API deletes a software timer.

Syntax:

void xTimerDelete( TimerHandle_t xTimer, TickType_t xTicksToWait );

Parameters:

xTimer: The handle of the timer to delete.

xTicksToWait: The time, in tick periods, to wait before deleting the timer.


5. pvTimerGetTimerID This API returns a timer's ID value.

Syntax :

void *pvTimerGetTimerID( TimerHandle_t xTimer );

Parameters:

 xTimer is the handle of the timer for which the ID value needs to be obtained.

The return value is a pointer to the timer's ID value.


6. xTimerIsTimerActive ItQueries a software timer to see if it is active or dormant.

A timer will be dormant if:

It has been created but not started, or

It is an expired one-shot timer that has not been restarted.

Syntax:

BaseType_t xTimerIsTimerActive( TimerHandle_t xTimer );

Parameters:

xTimer The timer being queried.

Returns:

pdFALSE will be returned if the timer is dormant. A value other than pdFALSE will be returned if the timer is active.


Why to use Free RTOS software timer as compared to task?


FreeRTOS software timers and tasks both provide ways to schedule and execute code, but they have different use cases and trade-offs.

  1. Memory Usage: Software timers require significantly less memory compared to tasks. This is because software timers are implemented as a linked list of timer control blocks, which are much smaller in size compared to the task control blocks used for tasks.

  2. Processing Power: Software timers do not have their own stack and do not require CPU time to run, as they are executed in the context of the RTOS scheduler. This makes software timers much more efficient in terms of processing power compared to tasks.

  3. Simplicity: Software timers provide a simple and efficient way to schedule events to occur in the future without the need for complex synchronization mechanisms. For example, you can use a software timer to schedule a task to be executed once after a specified time interval, or to repeat at regular intervals.

  4. Precise Timing: Software timers provide precise timing control and can be used to schedule events to occur at precise intervals. This can be important in applications where timing accuracy is critical.

  5. Interrupt Handling: Software timers can be used to handle interrupts, which can simplify interrupt handling and reduce the number of tasks required in the system.

  6. Task Overhead: Tasks have overhead associated with their creation, including the allocation of memory for their stack, the initialization of task control blocks, and the management of task priorities. This overhead can be significant in resource-constrained systems.

What are the advantages of using Software Timers?

Here are some advantages of using software timers in embedded systems:

  1. Non-blocking operation: Using software timers enables tasks to perform actions at specific intervals or points in time, without having to block and wait for those actions to complete. This can improve the responsiveness and efficiency of the system, as tasks can be designed to run independently and asynchronously.
  2. Flexibility: Software timers can be used to perform a wide range of periodic or event-driven tasks, such as sensor updates, data logging, or communication operations. They can be configured to operate at specific intervals or to trigger actions based on specific events, allowing for a high degree of flexibility and customization.
  3. Reduced system complexity: By using software timers, tasks can be designed to perform specific actions at specific intervals or points in time, reducing the complexity of the code and making it easier to debug and maintain.
  4. Low resource usage: Software timers can be implemented using minimal hardware resources, such as software counters and periodic interrupts, which can reduce the overall cost and complexity of the system.
  5. Timely response: Software timers can be used to ensure timely response to events and conditions in the system. By triggering actions at specific intervals or points in time, the system can respond quickly and efficiently to changes in the environment or user inputs.

Software timers are a powerful and flexible tool for managing time-based operations in embedded systems. They can improve system performance, reduce complexity, and ensure timely response to events and conditions, making them an essential component of many embedded applications.

What are the Limitations of Software Timers?

While software timers offer many advantages, there are also some limitations that need to be considered. Here are some of the main limitations of software timers:

  1. Timing accuracy: The timing accuracy of software timers can be affected by factors such as task scheduling, interrupt latency, and system load. This means that it can be challenging to achieve precise and consistent timing for critical operations in the system.
  2. System overhead: Software timers can impose overhead on the system, including the use of software counters, interrupts, and memory resources. This overhead can reduce the overall performance of the system and increase power consumption.
  3. Limited resolution: The resolution of software timers is limited by the frequency of the underlying clock source and the granularity of the software timer implementation. This means that it can be challenging to achieve fine-grained timing for some operations.
  4. Interrupt conflicts: If multiple software timers are running in the system, there is a risk of interrupt conflicts, where two or more timers attempt to access the same system resources at the same time. This can cause timing inaccuracies and system instability.
  5. Limited hardware support: Some hardware platforms may not support the use of software timers or may have limited support for advanced timing features, which can limit the flexibility and functionality of the system.

The Code to implement Software Timer in FreeRTOS


#if CONFIG_FREERTOS_UNICORE
#define ARDUINO_RUNNING_CORE 0
#else
#define ARDUINO_RUNNING_CORE 1
#endif


TimerHandle_t oneshotTimer;
TimerHandle_t autoReloadTimer;


void vTimerCallback( TimerHandle_t xTimer )
{
  
  int id = (int)pvTimerGetTimerID(xTimer);
  Serial.println(id);
  
  if  (id == 0)
  {
        Serial.println("oneshotTimer expired");
  }
  else if (id == 1)
  {
        Serial.println("autoreloadTimer is running");
  }
  

}

void setup()
{
  
 Serial.begin(115200);
  
 oneshotTimer = xTimerCreate( "oneshotTimer", pdMS_TO_TICKS( 500 ), pdFALSE , ( void * ) 0, vTimerCallback );
 autoReloadTimer = xTimerCreate( "autoReloadTimer", pdMS_TO_TICKS( 1000 ), pdTRUE , ( void * ) 1, vTimerCallback );
  
  if ( (oneshotTimer ==  NULL) ||  ( autoReloadTimer ==  NULL) )
  {

    Serial.println("Timer not created");
    
  }
  
  xTimerStart( oneshotTimer, 0 );
  xTimerStart(  autoReloadTimer, 0 );

}

void loop()
{

  
  vTaskDelay( pdMS_TO_TICKS( 8000 ) );

  Serial.print(" Status of oneshotTimer  ");

  Serial.println(xTimerIsTimerActive(oneshotTimer));

  Serial.print(" Status of autoReloadTimer ");
  
  Serial.println(xTimerIsTimerActive(autoReloadTimer));
  
  if (xTimerIsTimerActive(autoReloadTimer) == pdTRUE)
  {
    
    xTimerStop(autoReloadTimer,0);
    xTimerDelete(autoReloadTimer,0);
    
    Serial.println(" autoReloadTimer stopped and deleted");
    
  }

 
  // Do nothing
}

Conclusion

In conclusion, software timers are an essential feature of FreeRTOS, providing a flexible and powerful tool for managing time-based operations in embedded systems. By allowing tasks to perform specific actions at specific intervals or points in time, software timers can improve the efficiency and responsiveness of the system, while reducing system complexity and resource usage.

While software timers have some limitations, such as timing accuracy and system overhead, they are still a valuable tool for many applications, and their advantages often outweigh their limitations. With the set of APIs provided by FreeRTOS, it is relatively easy to create and manage software timers in embedded systems, making them an essential component of many embedded applications.

Post a Comment

Previous Post Next Post