1 #define EXAMPLE_ESP_WIFI_SSID "111" 2 #define EXAMPLE_ESP_WIFI_PASS "19890813" 3 #define EXAMPLE_ESP_MAXIMUM_RETRY 5
需要设置的宏定义,wifi名称,wifi密码,最大尝试次数,在后续程序中会用到。
1 /* FreeRTOS event group to signal when we are connected*/ 2 static EventGroupHandle_t s_wifi_event_group;//事件标志位 3 4 /* The event group allows multiple bits for each event, but we only care about two events: 5 * - we are connected to the AP with an IP 6 * - we failed to connect after the maximum amount of retries */ 7 #define WIFI_CONNECTED_BIT BIT0 8 #define WIFI_FAIL_BIT BIT1
创建一个自定义事件标志位组,并定义我们需要的事件位。
1 /* Waiting until either the connection is established (WIFI_CONNECTED_BIT) or connection failed for the maximum 2 * number of re-tries (WIFI_FAIL_BIT). The bits are set by event_handler() (see above) */ 3 EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group, 4 WIFI_CONNECTED_BIT | WIFI_FAIL_BIT, 5 pdFALSE, 6 pdFALSE, 7 portMAX_DELAY); 8 9 /* xEventGroupWaitBits() returns the bits before the call returned, hence we can test which event actually 10 * happened. */ 11 if (bits & WIFI_CONNECTED_BIT) 12 { 13 ESP_LOGI(TAG, "connected to ap SSID:%s password:%s", 14 EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS); 15 } else if (bits & WIFI_FAIL_BIT) 16 { 17 ESP_LOGI(TAG, "Failed to connect to SSID:%s, password:%s", 18 EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS); 19 } else { 20 ESP_LOGE(TAG, "UNEXPECTED EVENT"); 21 }
在初始化STA时,调用等待事件函数,接着判断事件标志位,判断STA是否连接成功。
1esp_event_handler_instance_t instance_any_id; esp_event_handler_instance_t instance_got_ip;
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, 2 ESP_EVENT_ANY_ID, 3 &event_handler, 4 NULL, 5 &instance_any_id)); 6 ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, 7 IP_EVENT_STA_GOT_IP, 8 &event_handler, 9 NULL, 10 &instance_got_ip));
这里是给特定的系统事件来绑定到event_handler,接着就可以在event_handle中写我们的事件处理函数,在中断中判断事件类型和id可以判断出具体的事件类型,
1 ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) ); 2 ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config) ); 3 ESP_ERROR_CHECK(esp_wifi_start() );
STA配置完成后,调用这三个函数,就可以启动STA。
1 /* The event will not be processed after unregister */ 2 ESP_ERROR_CHECK(esp_event_handler_instance_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, instance_got_ip)); 3 ESP_ERROR_CHECK(esp_event_handler_instance_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, instance_any_id)); 4 vEventGroupDelete(s_wifi_event_group);
当系统事件和自定义事件已经用完,需要将内存释放,事件解绑。