Using the idle hook

I wanted to see the idle hook in action.

I used the rtos::Kernel::attach_idle_hook(fptr) function in program below.Nothing happens though.

#include <mbed.h>

DigitalOut led2(LED2);
Thread thread;

void new_idle_loop()
{
led2=!led2;
// do nothing
}

int main()
{

void (*fptr)();

// Assign lambda function to the function pointer
fptr = []() {
    new_idle_loop();
};

while(1){
rtos::Kernel::attach_idle_hook(fptr);
}

}

I have not looked into this deeply, but it seems to me that there is nothing in your code that makes the OS go to idle.

Try to change main to this:

rtos::Kernel::attach_idle_hook( fptr );

while( 1 )
{
    rtos::this_thread::yield();
}

Hmm, I think that even yield() won’t work as expected. This is because the main thread runs with normal priority, so it will never yield to the idle thread – yield() can only yield to threads with the same or higher priority.

Assuming you only have the one main thread running, the idle hook will run only when the main thread is blocked (e.g. waiting for a network packet) or is sleeping. So, try something like ThisThread::sleep_for(1s), and then you should see the idle hook execute.

Thanks for your reply.

I put the main thread to sleep and I can see the idle hook in action.
Can I see the sleep related trace in the terminal.
I have put some override in the mbed_app.json file but no trace is visible.
The mbed_app.json file has the following:

{
“target_overrides”: {
“*”: {

        "mbed-trace.enable": true,
        "platform.stdio-buffered-serial": 1 ,
        "target.features_add": ["MBED_SLEEP_TRACING_ENABLED=1"]           
                 
    }
}

}
Kindly let me know where is this going wrong as I cannot see the sleep trace as mentioned in the documentation.

Thanks
Govind

Hello,

I do not have any experiences with this, but are you sure this is correct format?

So should look like this maybe

{
	"target_overrides": {
		"*": {
          "mbed-trace.enable": true,
          "platform.stdio-buffered-serial": 1 ,
          "platform.deepsleep-stats-enabled":1           
		}
	}
}

Maybe alternative can be

{
    "macros": [
        "MBED_SLEEP_TRACING_ENABLED=1"
    ]
}

BR, Jan

Thanks ,

Its working now.

Does the attach_idle_hook() function puts the processor in sleep.Is there a way to see that in MBED.

Thanks
Govind