Page 2
This document provides sample codes based on ESP8266_RTOS_SDK. The document is structured as follows: Chapter Title Subject Chapter 1 Introduction Provides preliminary information on ESP8266EX. Chapter 2 Overview Provides an overview of ESP8266_RTOS_SDK. Chapter 3 Sample Codes Provides sample codes based on ESP8266_RTOS_SDK.
Content 1. Introduction ..........................2. Overview ..........................2.1. RTOS SDK Introduction ......................2.2. Notes on Programming ......................3. Sample Codes ........................3.1. Directory Structure of RTOS SDK ....................3.2. Basic Examples .......................... 3.2.1. Initialization ........................3.2.2. How to Read the ID of the Chip ..................
Page 4
A.2. ESP8266 SoftAP and Station Channel Configuration .............. A.3. ESP8266 Boot Messages ......................
flash. It has an built-in, high-speed cache which improves the performance of the system and optimizes the memory. Alternatively, when the ESP8266EX is used as a Wi-Fi adapter, wireless internet access can be added to any microcontroller-based device through the SPI/SDIO interface or the I2C/UART interface, and thus provide the users with a simple Wi-Fi solution.
2. Overview Overview 2.1. RTOS SDK Introduction The SDK provides its users with a set of interfaces for data reception and transmission. Users do not need to worry about the set-up of the network, including Wi-Fi and TCP/IP stack. Instead, they can focus on the IoT application development. They can do so by receiving and transmitting data through the interfaces.
Page 7
2. Overview - Users can prioritize tasks on a scale of 1 to 9. However, please note that user tasks cannot keep hanging in the "running" state, as this would result in preventing low-priority system tasks from being performed. - Please do not revise FreeRTOSConfig.h. Revision of the head file can only be done by libraries in the SDK. ...
3. Sample Codes Sample Codes 3.1. Directory Structure of RTOS SDK ESP8266 RTOS SDK can be downloaded via the following link: ESP8266 RTOS SDK. Below is the directory structure of the ESP8266 RTOS SDK. bin: boot and initialization firmware. • documents: ESP8266_RTOS_SDK files.
3. Sample Codes How to get the RSSI (Received Signal Strength Indicator) of an AP • • How to read and write information from sectors on a flash memory Examples of RTC • How to port apps from non-OS SDK to RTOS SDK •...
3. Sample Codes UART_SetPrintPort(UART0); UART_intr_handler_register(uart0_rx_intr_handler); ETS_UART_INTR_ENABLE(); 3. ESP8266_RTOS_SDK supports multi-threading, therefore, multiple tasks can be created. The interface xTaskCreate used to create tasks is a self-contained interface owned by freeRTOS. When using xTaskCreate to create a new task, the range of the task stack should be [176, 512].
3. Sample Codes Result: ESP8266 chip ID:0x97f740 3.2.3. Connect to AP When ESP8266 Functions as Station 1. Set the working mode of ESP8266 to Station mode, or Station+SoftAP mode. Wi-Fi_set_opmode(STATION_MODE); 2. Set the SSID and password of the AP. #define DEMO_AP_SSID "DEMO_AP" #define DEMO_AP_PASSWORD "12345678" Wi-Fi_station_set_config is used to set the AP information when ESP8266 functions as Station.
Page 12
3. Sample Codes Wi-Fi_softap_get_config(config); // Get soft-AP config first. sprintf(config->ssid, DEMO_AP_SSID); sprintf(config->password, DEMO_AP_PASSWORD); config->authmode = AUTH_WPA_WPA2_PSK; config->ssid_len = 0; // or its actual SSID length config->max_connection = 4; Wi-Fi_softap_set_config(config); // Set ESP8266 soft-AP config free(config); 3. Get the Station info when ESP8266 functions as SoftAP. struct station_info * station = Wi-Fi_softap_get_station_info(); while(station){ printf(bssid : MACSTR, ip : IPSTR/n, MAC2STR(station->bssid), IP2STR(&station->ip)); station = STAILQ_NEXT(station, next); Wi-Fi_softap_free_station_info(); // Free it by calling functions 4. When ESP8266 functions as SoftAP, its default IP address is 192.168.4.1. The IP address is subject to modification by developers;...
3. Sample Codes 6. Compile the application program, generate firmware and download it into the ESP8266 module. 7. Power off the module, and change it to operation mode; then power on the module and run the program. Connect a PC or other Stations to the ESP8266 SoftAP. Result: ESP8266 works as SoftAP, and the following information will be printed when a Station is connected to it:...
3. Sample Codes IP2STR(&evt->event_info.got_ip.mask), IP2STR(&evt->event_info.got_ip.gw)); printf("\n"); break; case EVENT_SOFTAPMODE_STACONNECTED: printf("station: " MACSTR "join, AID = %d\n", MAC2STR(evt->event_info.sta_connected.mac), evt->event_info.sta_connected.aid); break; case EVENT_SOFTAPMODE_STADISCONNECTED: printf("station: " MACSTR "leave, AID = %d\n", MAC2STR(evt->event_info.sta_disconnected.mac), evt->event_info.sta_disconnected.aid); break; default: break; } void user_init(void) // TODO: add user’s own code here..Wi-Fi_set_event_handler_cb(Wi-Fi_handle_event_cb); 3. Compile the application program, generate firmware and download it into the ESP8266 module. 4. Power off the module, and change it to operation mode; then power on the module and run the program.
3. Sample Codes unique and exclusive. If users want to reset the MAC address, the uniqueness of the MAC address should be assured. 2. Set ESP8266 to Station+SoftAP mode. Wi-Fi_set_opmode(STATIONAP_MODE); 3. Read the MAC addresses of the Station and SoftAP interfaces. Wi-Fi_get_macaddr(SOFTAP_IF, sofap_mac);...
Page 16
3. Sample Codes Callback function when the AP scanning is completed: void scan_done(void *arg, STATUS status) uint8 ssid[33]; char temp[128]; if (status == OK) { struct bss_info *bss_link = (struct bss_info *)arg; while (bss_link != NULL) { memset(ssid, 0, 33); if (strlen(bss_link->ssid) <= 32) memcpy(ssid, bss_link->ssid, strlen(bss_link->ssid)); else memcpy(ssid, bss_link->ssid, 32); printf("(%d,\"%s\",%d,\""MACSTR"\",%d)\r\n", bss_link->authmode, ssid, bss_link->rssi, MAC2STR(bss_link->bssid),bss_link->channel); bss_link = bss_link->next.stqe_next; } } else { printf("scan fail !!!\r\n"); } 3. Compile the application program, generate firmware and download it into the ESP8266 module.
3. Sample Codes 3.2.8. Get RSSI (Received Signal Strength Indicator) of AP 1. If ESP8266 functions as Station and is not connected to an AP, users can obtain the RSSI (Received Signal Strength Indicator) of an AP by scanning the AP with a specified SSID.
3. Sample Codes 3. Compile the application program, generate firmware and download it into the ESP8266 module. 4. Power off the module, and change it to operation mode; then power on the module and run the program. Result: read data from 0x3E000 : 05 00 04 02 3.2.10. How to Use RTC 1.
3. Sample Codes 3. Power off the module, and change it to operation mode; then power on the module and run the program. Result: rtc_time: 1613921 cal: 6.406 3.2.11. How to Port Apps from Non-OS SDK to RTOS SDK 1. Codes for setting the timer do not need to be revised. 2.
Page 20
3. Sample Codes // test_q is the corresponding array of test_task. // (2) is the priority of test_task. // Q_NUM is the queue length of test_task. RTOS SDK: creating a new task #define Q_NUM (10) xQueueHandle test_q; xTaskHandle test_task_hdl; void test_task(void *pvParameters) int *sig; for(;;) { if(pdTRUE == xQueueReceive(test_q, &sig, (portTickType)portMAX_DELAY) ){ vTaskSuspendAll(); switch(*sig) { case 1: func1(); break; case 2: func2(); break; default: break; } free(sig); xTaskResumeAll(); } } void func_send_Sig(void) int *evt = (int *)malloc(sizeif(int)); *evt = 2; if(xQueueSend(test_q,&evt,10/portTick_RATE_MS)!=pdTRUE){ os_printf("test_q is full\n"); } // It is the address of parameter that stored in test_q, so int *evt and int *sig can be other types.
3. Sample Codes test_q = xQueueCreate(Q_NUM,sizeof(void *)); xTaskCreate(test_task,(signed portCHAR *)"test_task", 512, NULL, (1), &test_task_hdl ); // 512 means the heap size of this task, 512 * 4 byte. // NULL is a pointer of parameter to test_task. // (1) is the priority of test_task. // test_task_hdl is the pointer of the task of test_task. 3.3. Networking Protocol Example The networking protocol of ESP8266_RTOS_SDK is the programming of socket, including the following examples: Example of UDP transmission • • Example of TCP connection - ESP8266 functions as TCP client - ESP8266 functions as TCP server 3.3.1.
3. Sample Codes ESP8266 UDP task > bind ok! ESP8266 UDP task > recv data 16 Bytes from 192.168.1.112, Port 57233 UDP communication can be set up at the PC terminal by using network debugging tools; then ESP8266 UDP test will be sent to the ESP8266 UDP port. When the UDP data is received by ESP8266, the same message will be sent to the PC terminal, too. 3.3.2.
3. Sample Codes printf("ESP8266 TCP client task > recv data %d bytes!\nESP8266 TCP client task > %s\n", recbytes, recv_buf); } free(recv_buf); if (recbytes <= 0) { close(sta_socket); printf("ESP8266 TCP client task > read data fail!\n"); } 4. Compile the application program, generate firmware and download it into the ESP8266 module. 5. Power off the module, and change it to operation mode, then power on the module and run the program.
Page 26
3. Sample Codes #define SERVER_PORT 1002 int32 listenfd; int32 ret; struct sockaddr_in server_addr,remote_addr; int stack_counter=0; /* Construct local address structure */ memset(&server_addr, 0, sizeof(server_addr)); /* Zero out structure */ server_addr.sin_family = AF_INET; /* Internet address family */ server_addr.sin_addr.s_addr = INADDR_ANY; /* Any incoming interface */ server_addr.sin_len = sizeof(server_addr); server_addr.sin_port = htons(httpd_server_port); /* Local port */ /* Create socket for incoming connections */ do{ listenfd = socket(AF_INET, SOCK_STREAM, 0); if (listenfd == -1) { printf("ESP8266 TCP server task > socket error\n”); vTaskDelay(1000/portTICK_RATE_MS); } }while(listenfd == -1); printf("ESP8266 TCP server task > create socket: %d\n", server_sock); /* Bind to the local port */ do{ ret = bind(listenfd, (struct sockaddr *)&server_addr, sizeof(server_addr)); if (ret != 0) { printf("ESP8266 TCP server task > bind fail\n”); vTaskDelay(1000/portTICK_RATE_MS); } }while(ret != 0); printf("ESP8266 TCP server task > port:%d\n”,ntohs(server_addr.sin_port)); Establish TCP server interception: do{ /* Listen to the local connection */ ret = listen(listenfd, MAX_CONN); if (ret != 0) { printf("ESP8266 TCP server task > failed to set listen queue!\n");...
Page 27
3. Sample Codes } }while(ret != 0); printf("ESP8266 TCP server task > listen ok\n”); Wait until the TCP client is connected to the server; then start receiving data packets when the TCP communication is established: int32 client_sock; int32 len = sizeof(struct sockaddr_in); for (;;) { printf("ESP8266 TCP server task > wait client\n”); /*block here waiting remote connect request*/ if ((client_sock = accept(listenfd, (struct sockaddr *)&remote_addr, (socklen_t *)&len)) < 0) { printf("ESP8266 TCP server task > accept fail\n"); continue; } printf("ESP8266 TCP server task > Client from %s %d\n", inet_ntoa(remote_addr.sin_addr), htons(remote_addr.sin_port)); char *recv_buf = (char *)zalloc(128); while ((recbytes = read(client_sock , recv_buf, 128)) > 0) { recv_buf[recbytes] = 0;...
3. Sample Codes Result: ip:192.168.1.127,mask:255.255.255.0,gw:192.168.1.1 got ip !!! Hello, welcome to ESP8266 TCP server task! ESP8266 TCP server task > create socket: 0 ESP8266 TCP server task > bind port: 1002 ESP8266 TCP server task > listen ok ESP8266 TCP server task > wait client ESP8266 TCP server task > Client from 192.168.1.108 1001 ESP8266 TCP server task > read data success 17! ESP8266 TCP server task > ESP8266 recv test 3.4. Advanced Example of OTA Firmware Upgrade Advanced examples included in ESP8266_RTOS_SDK are listed below: • Firmware over-the-air (OTA) upgrade Example of forced sleep • SPIFFS file system •...
Page 29
3. Sample Codes ⚠ Notice: Erasing the flash memory is a slow process. Thus it may take longer time to erase a flash memory sector while writing information into other sectors of the flash at the same time. Besides, the stability of the network might also be affected.
Page 30
3. Sample Codes // write the new firmware into flash by spi_flash_write Set a software timer to check the upgrade status of the firmware periodically. If the • timer indicates a time-out, and the firmware has not been updated from the cloud server, it means the upgrade failed. The status of the firmware upgrade will become idle and the upgrade will stop.
Page 31
3. Sample Codes The print information during ESP8266 upgrading process: • connected with Demo_AP, channel 6 dhcp client start... ip:192.168.1.127,mask:255.255.255.0,gw:192.168.1.1 Hello, welcome to client! socket ok! connect ok! GET /user2.bin HTTP/1.0 Host: "192.168.1.114":80 Connection: keep-alive Cache-Control: no-cache User-Agent: Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.36 (KHTML, like Gecko) Chrome/ 30.0.1599.101 Safari/535.36 Accept: */* Accept-Encoding: gzip,deflate,sdch Accept-Language: zh-CN,zh;q=0.8 send success read data success! upgrade file download start. read data success! totallen = 1460 read data success! totallen = 2920 read data success! … … Espressif 27 37 2017.05...
3. Sample Codes 3.4.2. Examples of Forced Sleep The forced-sleep interface can be called, and the RF circuit can be closed mandatorily so as to lower the power. ⚠ Notice: • When forced-sleep interface is called, the chip will not enter sleep mode instantly, it will enter sleep mode when the system is executing the idle task.
Page 33
3. Sample Codes Wi-Fi_set_opmode(STATION_MODE); // set station mode Wi-Fi_station_connect(); // connect to AP #endif Example Two: Light-sleep Mode (RF and CPU Disabled) ESP8266 is forced into Light-sleep mode, and both RF and CPU are disabled. Users need to set a callback so that the program can continue after wakeup. void fpm_wakup_cb_func1(void) Wi-Fi_fpm_close(); // disable force sleep function Wi-Fi_set_opmode(STATION_MODE); // set station mode...
3. Sample Codes #endif 3.4.3. How to Use the SPIFFS File System 1. Initialize the SPIFFS file system by calling esp_spiffs_init. void spiffs_fs1_init(void) struct esp_spiffs_config config; config.phys_size = FS1_FLASH_SIZE; config.phys_addr = FS1_FLASH_ADDR; config.phys_erase_block = SECTOR_SIZE; config.log_block_size = LOG_BLOCK; config.log_page_size = LOG_PAGE; config.fd_buf_size = FD_BUF_SIZE * 2; config.cache_buf_size = CACHE_BUF_SIZE; esp_spiffs_init(&config); 2. Open and create a new file, and write the data in it. char *buf="hello world";...
3. Sample Codes 3.4.4. How to Implement SSL 1. Define the IP address and port that the SSL server will be connected to. #define SSL_SERVER_IP “115.29.202.58” #define SSL_SERVER_PORT 443 esp_test *pTestParamer = (esp_test *)zalloc(sizeof(esp_test)); pTestParamer->ip.addr = ipaddr_addr(SSL_SERVER_IP); pTestParamer->port = server_port; 2. Create a new task when the device functions as an SSL client. xTaskCreate(esp_client, "esp_client", 1024, (void*)pTestParamer, 4, NULL);...
Page 36
3. Sample Codes printf("heap_size %d\n”,system_get_free_heap_size()); 6. When the SSL authentication function is required: If not using SPIFFS file system, please run python script esp_iot_sdk_freertos\tools\ • make_cert.py, generate esp_ca_cert.bin, and write it into the flash. Below is an example showing how to read information about the SSL encryption key and certificate from the flash.
Appendix A Appendix A.1. Sniffer Introduction For more details on sniffer, please refer to ESP8266 Technical Reference. A.2. ESP8266 SoftAP and Station Channel Configuration Even though ESP8266 supports the SoftAP+Station mode, only one hardware channel can be used for communication. In the SoftAP+Station mode, the ESP8266 SoftAP will adjust its channel configuration to be same as that of the ESP8266 Station.
Page 40
Appendix A 4. In cases like this, users can set a timer to call Wi-Fi_station_disconnect in order to stop the ESP8266 Station from continuously trying to connect to the router. Users can also call Wi-Fi_station_set_reconnect_policy or Wi-Fi_station_set_auto_connect to disable the ESP8266 Station from reconnecting to the router. A.3.
Page 41
Disclaimer and Copyright Notice Information in this document, including URL references, is subject to change without notice. THIS DOCUMENT IS PROVIDED AS IS WITH NO WARRANTIES WHATSOEVER, INCLUDING ANY WARRANTY OF MERCHANTABILITY, NON-INFRINGEMENT, FITNESS FOR ANY PARTICULAR PURPOSE, OR ANY WARRANTY OTHERWISE ARISING OUT OF ANY PROPOSAL, SPECIFICATION OR SAMPLE.
Need help?
Do you have a question about the ESP8266EX and is the answer not in the manual?
Questions and answers