The scanning function esp_wifi_scan_start for Wi-Fi APs provided by the SDK for the ESP8266 provides both blocking and non-blocking calling methods, as specified by the second parameter of the function;
If the blocking method is used, it will block the running of the task that calls the function, affecting the real-time effect of the program.
For example, the simple controller we are designing handles AP scanning requests from web clients in the main task. If the esp_wifi_scan_start function is called directly in the main task in a blocking manner, it needs to wait at least a few seconds for scanning the APs, and during this period, it is not possible to carry out other processing, such as sending an answer to the web client, PLC logic execution, etc., which no only affects the customer experience but also cause serious consequences due to control too late.
To avoid this impact, a new task needs to be started to scan the AP as follows:
xTaskCreate(wf_scan_task, “scan task”, 512, NULL, 1, NULL);
Call the task function wf_scan_task in the task function
esp_wifi_scan_start(&scan_config, true), wait for the scan to complete and process the results;
When creating a task, you need to specify the stack size to be allocated to the task, the local variables defined by the task function and its called subfunctions, the context of the function call, the function in- and out-parameters will occupy the stack, and if the nesting of the called subfunctions is too low, it will consume a lot of stack space.
It is necessary to allocate enough space for the task according to the definition of local variables and the definition of subfunctions when the task is created;
For example, the above statement allocates 512 bytes of stack space for the task, but the printf function is called in the task function to print the scanned AP information;
Running the test, the esp8266 reports “Stack canary watchpoint triggered” error and reboots.
By tracing the backtrace, it is found that printf->nano-vfprintf->flush has at least 5 levels of function calls, and the nested calls consume a large amount of stack, resulting in stack overflow;
xtensa-lx106-elf-addr2line.exe -pfiaC -e build/IOMODULE.elf 0x4022b947:0x3fff3200
Since the ESP8266 has less RAM space available, it is possible to use a non-blocking call combined with an event listener
The scan results are processed in the scan completion callback event;
Thus, there is no need to allocate valuable RAM space to the newly created task, which is also a kind of time-for-space reluctance