Bird
Raised Fist0
FreeRTOSprogramming~15 mins

Changing timer period at runtime in FreeRTOS - Deep Dive

Choose your learning style10 modes available
Overview - Changing timer period at runtime
What is it?
Changing timer period at runtime means adjusting the time interval after which a FreeRTOS software timer triggers its callback function while the system is running. Instead of setting a fixed timer period at creation, you can modify it dynamically based on program needs. This allows your application to respond flexibly to changing conditions without restarting the timer or system.
Why it matters
Without the ability to change timer periods at runtime, applications would be rigid and less efficient, requiring timers to be stopped and recreated for different intervals. This limits responsiveness and wastes resources. Being able to adjust timer periods on the fly enables better control over timing behavior, improving real-time responsiveness and resource management in embedded systems.
Where it fits
Before learning this, you should understand FreeRTOS basics, especially how software timers work and how to create and start them. After mastering this, you can explore advanced timer management techniques, such as timer callbacks with parameters, timer synchronization, and dynamic timer creation and deletion.
Mental Model
Core Idea
A FreeRTOS software timer’s period can be changed anytime while running, letting the timer callback happen sooner or later without stopping or recreating the timer.
Think of it like...
It’s like setting an alarm clock that you can change while it’s still ticking, so you can wake up earlier or later without turning it off and on again.
┌─────────────────────────────┐
│ FreeRTOS Software Timer     │
│ ┌───────────────┐           │
│ │ Timer Period  │◄───Change─┤
│ └───────────────┘           │
│       │                    │
│       ▼                    │
│  Timer Callback            │
└─────────────────────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding FreeRTOS Software Timers
🤔
Concept: Learn what a FreeRTOS software timer is and how it works.
A FreeRTOS software timer is a tool that calls a function after a set time period. You create it with a fixed period and a callback function. When the timer expires, the callback runs. Timers can be one-shot or auto-reload (repeat).
Result
You know how to create and start a timer that calls a function after a fixed delay.
Understanding timers as delayed function calls helps you see why changing their period affects when the function runs.
2
FoundationCreating and Starting a Timer
🤔
Concept: Learn the basic API to create and start a FreeRTOS timer.
Use xTimerCreate() to make a timer with a name, period, auto-reload flag, ID, and callback. Then use xTimerStart() to start it. Example: TimerHandle_t timer = xTimerCreate("MyTimer", pdMS_TO_TICKS(1000), pdTRUE, NULL, callback); xTimerStart(timer, 0);
Result
A timer runs every 1000 milliseconds and calls the callback repeatedly.
Knowing how to start a timer sets the stage for changing its period later.
3
IntermediateChanging Timer Period with xTimerChangePeriod
🤔Before reading on: do you think changing the timer period requires stopping and restarting the timer? Commit to your answer.
Concept: Learn the API function that changes the timer period while it is running.
FreeRTOS provides xTimerChangePeriod() to change the timer’s period on the fly. You pass the timer handle and the new period in ticks. The timer adjusts its countdown to the new period without needing to stop or delete it. Example: xTimerChangePeriod(timer, pdMS_TO_TICKS(500), 0); // Change period to 500 ms
Result
The timer callback now triggers every 500 milliseconds instead of 1000.
Knowing that the timer can change period without stopping avoids unnecessary timer restarts and keeps timing smooth.
4
IntermediateEffect of Changing Period on Timer Behavior
🤔If you change the timer period to a shorter time, do you think the callback happens immediately or after the new period? Commit to your answer.
Concept: Understand how the timer countdown resets or adjusts when the period changes.
When you call xTimerChangePeriod(), the timer resets its countdown to the new period from that moment. If the new period is shorter, the callback happens sooner. If longer, it delays the callback accordingly. This lets you speed up or slow down timer events dynamically.
Result
The timer callback timing shifts immediately to match the new period.
Understanding countdown reset helps predict when callbacks occur after period changes.
5
IntermediateUsing xTimerReset vs xTimerChangePeriod
🤔Do you think xTimerReset changes the timer period or just restarts the countdown? Commit to your answer.
Concept: Distinguish between resetting a timer and changing its period.
xTimerReset() restarts the timer countdown using the current period without changing it. xTimerChangePeriod() changes the period and restarts the countdown. Use xTimerReset() to restart timing; use xTimerChangePeriod() to adjust timing length.
Result
You can restart the timer without changing period or change period and restart countdown.
Knowing the difference prevents bugs where timer period stays the same unintentionally.
6
AdvancedChanging Timer Period Safely in ISR Context
🤔Can you call xTimerChangePeriod() directly inside an interrupt service routine? Commit to your answer.
Concept: Learn how to change timer period safely from an interrupt using the FromISR API.
FreeRTOS provides xTimerChangePeriodFromISR() for changing timer periods inside interrupts. It is safe and uses special mechanisms to avoid conflicts. You must also handle the higher priority task wake-up flag. Example: BaseType_t xHigherPriorityTaskWoken = pdFALSE; xTimerChangePeriodFromISR(timer, pdMS_TO_TICKS(200), &xHigherPriorityTaskWoken); portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
Result
Timer period changes safely without corrupting kernel state during interrupts.
Knowing ISR-safe APIs prevents subtle bugs and system crashes in real-time systems.
7
ExpertInternal Timer Management and Period Change Effects
🤔Does changing the timer period affect the timer’s internal expiry time or just the period value? Commit to your answer.
Concept: Understand how FreeRTOS manages timer expiry internally and how period changes update expiry time.
FreeRTOS timers are managed in a timer list sorted by expiry time. Changing the period recalculates the expiry time based on the current tick count plus the new period. The timer is then repositioned in the list. This ensures the callback triggers at the correct new time without stopping the timer task.
Result
Timer expiry is dynamically updated, maintaining accurate timing after period changes.
Understanding internal timer list management explains why changing period is efficient and safe.
Under the Hood
FreeRTOS software timers are managed by a dedicated timer service task. Timers are stored in a sorted list by their expiry tick count. When you change a timer’s period, FreeRTOS recalculates the timer’s next expiry tick by adding the new period to the current tick count. It then removes and reinserts the timer in the list to maintain order. The timer service task checks this list and calls the timer’s callback when the system tick reaches the expiry tick.
Why designed this way?
This design allows efficient management of multiple timers with minimal CPU overhead. Using a sorted list ensures the timer service task only needs to check the earliest expiry. Changing periods by repositioning timers avoids stopping and recreating timers, which would be costly and error-prone. Alternatives like separate threads per timer would waste resources and complicate synchronization.
┌───────────────────────────────┐
│ FreeRTOS Timer Service Task    │
│                               │
│  ┌───────────────┐            │
│  │ Sorted Timer  │◄─Remove &──┤
│  │ List by Expiry│  Reinsert  │
│  └───────────────┘            │
│          ▲                    │
│          │                    │
│  Change Period API             │
│  (xTimerChangePeriod)         │
└───────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does xTimerChangePeriod() require stopping the timer first? Commit yes or no.
Common Belief:You must stop a timer before changing its period.
Tap to reveal reality
Reality:xTimerChangePeriod() changes the period and restarts the countdown without stopping the timer.
Why it matters:Stopping and restarting unnecessarily can cause timing glitches and complexity.
Quick: If you call xTimerChangePeriod() with a longer period, does the callback happen immediately? Commit yes or no.
Common Belief:Changing to a longer period triggers the callback immediately.
Tap to reveal reality
Reality:The timer resets countdown to the new longer period, delaying the callback accordingly.
Why it matters:Misunderstanding this leads to wrong assumptions about callback timing.
Quick: Can you safely call xTimerChangePeriod() from an ISR? Commit yes or no.
Common Belief:You can call xTimerChangePeriod() directly inside an interrupt.
Tap to reveal reality
Reality:You must use xTimerChangePeriodFromISR() inside interrupts to avoid kernel corruption.
Why it matters:Calling the wrong API in ISR can crash the system or cause unpredictable behavior.
Quick: Does changing the timer period affect the timer’s ID or callback function? Commit yes or no.
Common Belief:Changing the period also changes the timer’s ID or callback.
Tap to reveal reality
Reality:Only the period changes; the timer’s ID and callback remain the same.
Why it matters:Confusing this can cause bugs when expecting callback changes after period updates.
Expert Zone
1
Changing the timer period resets the countdown from the moment of change, not from the original start time, which can affect timing precision in some applications.
2
If multiple timers have their periods changed frequently, the timer service task’s list management can become a performance consideration in high-frequency systems.
3
Using xTimerChangePeriodFromISR() requires careful handling of the xHigherPriorityTaskWoken flag to ensure correct task scheduling after ISR.
When NOT to use
Avoid changing timer periods frequently in very high-frequency or ultra-low-latency systems where timer jitter must be minimal; consider hardware timers or dedicated timing peripherals instead. Also, do not use xTimerChangePeriod() inside ISRs; use the FromISR variant instead.
Production Patterns
In real embedded systems, changing timer periods at runtime is used for adaptive polling intervals, dynamic timeouts, or power-saving modes where timer frequency adjusts based on system state. Production code often wraps period changes with checks to avoid race conditions and uses FromISR APIs in interrupt contexts.
Connections
Event-driven programming
Builds-on
Understanding dynamic timer periods helps grasp how event-driven systems schedule and reschedule events flexibly.
Hardware timers in microcontrollers
Complementary
Software timers provide flexible timing but rely on hardware timers for tick generation; knowing both clarifies timing layers in embedded systems.
Project management scheduling
Analogy in different domain
Changing timer periods is like rescheduling tasks in project management to adapt to new priorities, showing how dynamic timing applies beyond programming.
Common Pitfalls
#1Calling xTimerChangePeriod() inside an interrupt service routine directly.
Wrong approach:void ISR_Handler() { xTimerChangePeriod(timer, pdMS_TO_TICKS(100), 0); // WRONG: Not ISR safe }
Correct approach:void ISR_Handler() { BaseType_t xHigherPriorityTaskWoken = pdFALSE; xTimerChangePeriodFromISR(timer, pdMS_TO_TICKS(100), &xHigherPriorityTaskWoken); portYIELD_FROM_ISR(xHigherPriorityTaskWoken); }
Root cause:Misunderstanding which FreeRTOS APIs are safe to call from interrupts.
#2Assuming changing the timer period does not restart the countdown.
Wrong approach:xTimerChangePeriod(timer, pdMS_TO_TICKS(200)); // Expect callback after original remaining time, not new period
Correct approach:xTimerChangePeriod(timer, pdMS_TO_TICKS(200)); // Callback will occur after 200 ticks from now
Root cause:Not realizing that changing period resets the timer countdown.
#3Stopping and deleting a timer to change its period instead of using xTimerChangePeriod().
Wrong approach:xTimerStop(timer, 0); xTimerDelete(timer, 0); timer = xTimerCreate("Timer", newPeriod, pdTRUE, NULL, callback); xTimerStart(timer, 0);
Correct approach:xTimerChangePeriod(timer, newPeriod, 0);
Root cause:Lack of knowledge about the API that changes period dynamically.
Key Takeaways
FreeRTOS software timers can have their periods changed at runtime without stopping or deleting them.
xTimerChangePeriod() resets the timer countdown to the new period immediately, affecting when the callback runs next.
Use xTimerChangePeriodFromISR() when changing timer periods inside interrupt service routines to maintain system stability.
Understanding internal timer list management explains why changing periods is efficient and safe.
Avoid unnecessary stopping and recreating timers; use the provided APIs to keep timing smooth and resource-efficient.

Practice

(1/5)
1.

What function is used in FreeRTOS to change the period of a timer while it is running?

easy
A. xTimerStop()
B. xTimerStart()
C. xTimerReset()
D. xTimerChangePeriod()

Solution

  1. Step 1: Understand timer period change in FreeRTOS

    FreeRTOS allows changing a timer's period without stopping it.
  2. Step 2: Identify the correct API function

    The function xTimerChangePeriod() is designed to change the timer period at runtime.
  3. Final Answer:

    xTimerChangePeriod() -> Option D
  4. Quick Check:

    Change timer period = xTimerChangePeriod() [OK]
Hint: Use xTimerChangePeriod() to update timer period on the fly [OK]
Common Mistakes:
  • Confusing xTimerStart() with changing period
  • Trying to stop and restart timer instead
  • Using xTimerReset() which resets but doesn't change period
2.

Which of the following is the correct syntax to change a FreeRTOS timer period to 100 ticks?

?
easy
A. xTimerChangePeriod(timerHandle, 0, 100);
B. xTimerChangePeriod(100, timerHandle, 0);
C. xTimerChangePeriod(timerHandle, 100, 0);
D. xTimerChangePeriod(0, 100, timerHandle);

Solution

  1. Step 1: Recall function parameter order

    The function xTimerChangePeriod() takes parameters as (TimerHandle_t xTimer, TickType_t xNewPeriod, TickType_t xTicksToWait).
  2. Step 2: Match parameters to example

    To set period to 100 ticks, pass timerHandle, 100, and 0 for no wait.
  3. Final Answer:

    xTimerChangePeriod(timerHandle, 100, 0); -> Option C
  4. Quick Check:

    Correct parameter order = xTimerChangePeriod(timerHandle, 100, 0); [OK]
Hint: Remember: timer handle first, then new period, then wait ticks [OK]
Common Mistakes:
  • Swapping timer handle and period parameters
  • Passing wait time before period
  • Using wrong parameter types or order
3.

Given the code snippet below, what will be the output if the timer callback prints the timer period each time it runs?

TimerHandle_t timer = xTimerCreate("MyTimer", pdMS_TO_TICKS(500), pdTRUE, NULL, TimerCallback);
xTimerStart(timer, 0);
xTimerChangePeriod(timer, pdMS_TO_TICKS(1000), 0);
// TimerCallback prints current period in ms
medium
A. The callback prints 500 ms once, then 1000 ms repeatedly
B. The callback prints 1000 ms repeatedly from start
C. The callback prints 500 ms repeatedly without change
D. The callback never runs due to period change

Solution

  1. Step 1: Analyze timer creation and start

    The timer is created with 500 ms period and started, scheduling first callback in 500 ms.
  2. Step 2: Effect of period change

    xTimerChangePeriod() removes the pending expiration, updates the period to 1000 ms, and schedules the next callback in 1000 ms from the change time. Thus, all callbacks print 1000 ms repeatedly.
  3. Final Answer:

    The callback prints 1000 ms repeatedly from start -> Option B
  4. Quick Check:

    Period change cancels pending expiry = prints 1000 ms repeatedly [OK]
Hint: xTimerChangePeriod cancels pending expiry and starts new full period [OK]
Common Mistakes:
  • Thinking first callback uses old 500 ms period
  • Assuming period change preserves pending expiration time
  • Believing the timer prints 500 ms first then switches
4.

Identify the error in the following code that attempts to change a timer period at runtime:

TimerHandle_t timer = xTimerCreate("Timer", pdMS_TO_TICKS(200), pdTRUE, NULL, TimerCallback);
xTimerChangePeriod(200, timer, 0);
medium
A. Parameters to xTimerChangePeriod are in wrong order
B. Timer was not started before changing period
C. Timer callback function is missing
D. pdMS_TO_TICKS() cannot be used in timer period

Solution

  1. Step 1: Check function parameter order

    xTimerChangePeriod() expects (TimerHandle_t, TickType_t, TickType_t), but code passes (TickType_t, TimerHandle_t, TickType_t).
  2. Step 2: Confirm other code parts

    Timer is created correctly and callback is provided; pdMS_TO_TICKS() is valid for period conversion.
  3. Final Answer:

    Parameters to xTimerChangePeriod are in wrong order -> Option A
  4. Quick Check:

    Correct parameter order is timer handle first [OK]
Hint: Timer handle always comes first in xTimerChangePeriod() [OK]
Common Mistakes:
  • Swapping timer handle and period parameters
  • Not starting timer before changing period (not required)
  • Misunderstanding pdMS_TO_TICKS usage
5.

You have a FreeRTOS timer running with a 200 ms period. You want to double the period each time the timer callback runs, up to a maximum of 1600 ms. Which code snippet correctly changes the timer period at runtime inside the callback?

void TimerCallback(TimerHandle_t xTimer) {
    TickType_t currentPeriod = xTimerGetPeriod(xTimer);
    TickType_t newPeriod = currentPeriod * 2;
    if (newPeriod <= pdMS_TO_TICKS(1600)) {
        ?
    }
}
hard
A. xTimerChangePeriod(xTimer, newPeriod, 0);
B. xTimerStart(xTimer, 0);
C. xTimerStop(xTimer, 0); xTimerChangePeriod(xTimer, newPeriod, 0);
D. xTimerReset(xTimer, 0); xTimerChangePeriod(xTimer, newPeriod, 0);

Solution

  1. Step 1: Understand timer period update inside callback

    Inside the callback, you can call xTimerChangePeriod() to update the timer period dynamically.
  2. Step 2: Choose correct function usage

    Calling xTimerChangePeriod(xTimer, newPeriod, 0); changes the period without stopping or restarting the timer.
  3. Final Answer:

    xTimerChangePeriod(xTimer, newPeriod, 0); -> Option A
  4. Quick Check:

    Change period directly inside callback = xTimerChangePeriod(xTimer, newPeriod, 0); [OK]
Hint: Use xTimerChangePeriod inside callback to update period safely [OK]
Common Mistakes:
  • Stopping timer before changing period unnecessarily
  • Starting timer again inside callback
  • Resetting timer which restarts count instead of changing period
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard