原理上一篇基本上也讲的差不多了,这次可以直接上代码了。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_spi_flash.h"
#include "esp_netif.h"
#include "esp_event.h"
#include "driver/uart.h"
#include "esp_wifi.h"
#include "nvs.h"
#include "nvs_flash.h"
static EventGroupHandle_t s_wifi_event_group;
static int s_retry_num = 0;
#define WIFI_CONNECTED_BIT BIT0
#define WIFI_FAIL_BIT BIT1
static void event_handler(void* arg, esp_event_base_t event_base,
int32_t event_id, void* event_data)
{
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
esp_wifi_connect();
} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
if (s_retry_num < 3) {
esp_wifi_connect();
s_retry_num++;
printf("Retry to connect to the AP!\n");
fflush(stdout);
} else {
xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT);
}
printf("Connect to the AP fail!\n");
fflush(stdout);
} else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
printf("got ip:%s\n", ip4addr_ntoa(&event->ip_info.ip));
fflush(stdout);
s_retry_num = 0;
xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
}
}
void app_main()
{
uart_set_baudrate(0, 74880);
printf("Esp8266 Hello world!\n");
nvs_flash_init();
s_wifi_event_group = xEventGroupCreate();
tcpip_adapter_init();
esp_event_loop_create_default();
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
esp_wifi_init(&cfg);
esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler, NULL);
esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler, NULL);
wifi_config_t wifi_config = {
.sta = {
.ssid = "zcxj",
.password = "1234567890",
},
};
if (strlen((char *)wifi_config.sta.password)) {
wifi_config.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK;
}
esp_wifi_set_storage(WIFI_STORAGE_RAM);
esp_wifi_set_mode(WIFI_MODE_STA);
esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config);
esp_wifi_start();
EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group, WIFI_CONNECTED_BIT | WIFI_FAIL_BIT,
pdFALSE, pdFALSE, portMAX_DELAY);
if (bits & WIFI_CONNECTED_BIT) {
printf("Connected to AP!\n");
fflush(stdout);
} else if (bits & WIFI_FAIL_BIT) {
printf("Failed to connect to AP!\n");
fflush(stdout);
} else {
printf("UNEXPECTED EVENT\n");
fflush(stdout);
}
esp_event_handler_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler);
esp_event_handler_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler);
vEventGroupDelete(s_wifi_event_group);
while(true) {
vTaskDelay(10000 / portTICK_PERIOD_MS);
}
fflush(stdout);
esp_restart();
}
成功运行后的截图,可以看到上面半部分是连接失败后的场景,下面是成功连接后的场景,可以看到已经获取到的IP地址,并输出成功连接的提示!
但是,在实际使用的过程中,我们可能并不会采用将WIFI的SSID和密码写死在代码当中的方式,所以,下次我们尝试使用ESP提供的Smart Config的方式来连接WIFI!
|