k_msleep, k_wakeup time accuracy

Hi.

I use 5340 + ncs 2.0.2

I used k_sleep and k_wake up periodly do something. but something is wired

under below example

//==== Thread A ========
done = false
k_wakeup(thread_B);
k_msleep(2000);
done = true
LOG_INF("Count : %d",count);

// ==== Thread B ======
//init something...
k_sleep(K_FOREVER);
int count = 0;
while(true)
{
    count++;
    k_msleep(1);
    if(done)
    {
        LOG_INF("Count : %d", count);
        count = 0;
        k_sleep(K_FOREVER);
    }
}

in this example I though count value is 2000. but it is less than 2000. about 1830

if I changed thread B k_msleep(10), it is correct count 200.

the sleep time is more smaller, accuracy is not good.

1 . could you help what reason?

2. how to fix that?

thank you

Best Regard

Ben

  • Hello,

    The time to execute the while() loop in thread B will take longer than 1ms (since there is a k_msleep(1) + MCU execution to run the loop), so that explain partially why it's not able to count all the way to 2000 when comparing to a different thread that is using simply a k_msleep(2000).

    There may also be some other threads or tasks occuring here, that can interrupt the executing of thread B in between calling k_msleep() that have an effect. Also note that the exact timing of the k_msleep() will depend on an RTC tick (30.52us) that is not exactly 1ms (it will likely be a 0-30us error for every sleep).

    Best regards,
    Kenneth

Related