xTimerStop() doesn't work

I created a timer with a 5s period. But I want to stop it within less than that period. I tried the below code but it seems xTimerStop() doesn’t work as I expected. I moved it into callback function and it works well.
So how can I fix this problem?
Here my code:

#include <Arduino_FreeRTOS.h>
#include <timers.h>
TimerHandle_t myTimer;
BaseType_t xTimerStarted;
BaseType_t xTimerStopped;
int key = 1;
void setup() {
  pinMode(13, OUTPUT);
  pinMode(7, OUTPUT);
  myTimer = xTimerCreate("MyTimer",
  if (myTimer != NULL)
    xTimerStarted = xTimerStart(myTimer, 0);
    if (xTimerStarted == pdPASS)
      if (key == 1)
        xTimerStopped = xTimerStop(myTimer, 0);
        if (xTimerStopped == pdPASS) digitalWrite(7, HIGH);

static void prvTimerCallback(TimerHandle_t myTimer)

  digitalWrite(13, HIGH);

void loop() {}

The problem with this code is that the call to vTaskStartScheduler never returns as tasks start running after that point. As a result, xTimerStop is never called.

Please do not double post the same issue.
And try to verify your code yourself. This will help you a lot to learn and getting more familiar and better :+1:

1 Like

I dont understand. If vTaskStartScheduler is not called, then daemon task cannot be created.

I see. But I dont know why vTaskStartScheduler never returns. I checked the document and it said " vTaskStartScheduler() will only return if there is insufficient RTOS heap available to create the idle or timer daemon tasks.". But the daemon task is created, because callback function is called.

As documented including commented example code
vTaskStartScheduler is not like a simple C-library function - it starts the FreeRTOS application !
The comment clearly tells that ONLY IN CASE OF A FATAL PROBLEM (not enough heap memory) vTaskStartScheduler returns and your FreeRTOS application isn’t started at all.
So don’t add code after the vTaskStartScheduler call and simply assume that it’s executed. It’s not ! In the normal case that there is no fatal problem with not enough heap memory.
That should be easy to find out yourself, isn’t it.