The esp8266 run loop and messaging

The basic esp8266 examples have the following basic format:

//Main code function
static void ICACHE_FLASH_ATTR loop(os_event_t *events) {

  // DO STUFF

  os_delay_us(100);
  system_os_post(user_procTaskPrio, 0, 0 );
}

//Init function
void ICACHE_FLASH_ATTR user_init() {

  // init system

  //Start os task
  system_os_task(loop, user_procTaskPrio,user_procTaskQueue, user_procTaskQueueLen);
  system_os_post(user_procTaskPrio, 0, 0 );
}

The support libraries appear to manage a message queuing system, system_os_task adds a new task type, with a given priority and sets it’s callback function. Tasks are then fired by sending them messages with system_os_post. I would guess that they have scheduler which waits for messages to be posted and schedules them appropriately. The basic examples provided create a single task, with the call back of “loop”. “loop” then sends itself a message at exit, insuring it is queued to be called again at some point in the future.

I would guess they also use the same system to schedule various internal processes, and that if “loop” never returns your going to have a bad time.

You can also use the messaging system for your own purposes, for example in my previous uart example, rather than busy waiting for input you can post a message for the uart ISR directly i.e.:

user_main.c:
//Main code function
static void ICACHE_FLASH_ATTR loop(os_event_t *events) {

  int c = uart0_rx_one_char();

  if(c != -1) {
   uart_tx_one_char(c);
  }
}

uart.c:
LOCAL void uart0_rx_intr_handler(void *para) {

...

   system_os_post(user_procTaskPrio, 0, 0 );
}

And loop will still regularly get called when there’s new data. I’d be slightly careful here, as the documentation is incomplete and there may be issues I’m unaware of. A modified version of that UART example I previously posted using modified to use this messaging method can be downloaded here:uart_test_messaging.tar

This is a continuation of my notes on the esp8266 microcontroller, you can find a complete list of my esp8266 posts here