ESP32-IDF的WiFi STA配网

两种ESP32-IDF的WiFi运行后任意时候重新配网的写法,第1种写法代码相对简单,但是感觉在配网的时候有可能WIFI_EVENT_STA_START事件不一定会被触发,这样会导致无法连接到路由器,虽然我在测试的时候没出现这个问题,但是我在前面的项目种做了类似的写法,这个事件就是部会触发,触发配置信息为空,所以个人觉得第2种比较稳定一些,只是代码相对较复杂一点:
1、在执行重新配网的时候先停止WiFi运行,然后配置新的WiFi信息后重新运行WiFi,运行事件触发后执行连接函数连接,完整代码如下:

#include "esp_wifi.h"
#include "esp_mac.h"
#include "esp_event.h"
#include "esp_log.h"
#include <string.h>
#include "bit.h"

#define TAG  "wifi_config"

static uint8_t s_retry_num=0;   //WiFi重连计数器

typedef enum{
   
	BIT_WIFI_INIT,               /* WiFi初始化标志位 */
	BIT_MESH_INIT,               /* Mesh初始化标志 bit 1初始化,0 未初始化*/
	BIT_MESH_CONNECTED ,         /* Mesh 连接状态标志位 bit 1 连接,0 未连接*/
	BIT_CONFIG_DISCONNECT,       /* 配置WiFi断开连接标志位(仅用于处理断开后释放重复连接几次的逻辑) */
	BIT_WIFI_CONNECT,            /* WiFi连接状态标志位 */
	BIT_WIFI_RUNNING,            /* WiFi 运行状态标志位 */
	BIT_CONFIG_NETWORK,          /* 配网状态标志位 */
	BIT_MESH_MQTT_TASK,          /* Mesh Mqtt 运行任务标志位 */
}state_flag_bit;

static uint8_t state_flag=0;            /*存放state_flag_bit枚举的各个位状态标志 */

void ip_event_handler(void* arg, esp_event_base_t event_base,int32_t event_id, void* event_data){
   
    if(event_base==WIFI_EVENT){
   
    	switch(event_id){
   
    	case WIFI_EVENT_STA_START:
			if(esp_wifi_connect()==ESP_OK){
   
				ESP_LOGI(TAG, "Success start connecting to WiFi");
			}else{
   
				ESP_LOGE(TAG, "Failed to start connecting to WiFi");
			}
			break;
    	case WIFI_EVENT_STA_CONNECTED:
           //在这里可以进行DNS域名解析,获取IP地址这些信息
            wifi_event_sta_connected_t *connect_event=(wifi_event_sta_connected_t *)event_data;
           ESP_LOGI(TAG, "Connect to WiFi。SSID:%s,aid:%d,Channel:%d,BSSID:"MACSTR"",
        		   connect_event->ssid,connect_event->aid,connect_event->channel,MAC2STR(connect_event->bssid));
           break;
    	case WIFI_EVENT_STA_DISCONNECTED:
    		if(!bitRead(state_flag,BIT_CONFIG_DISCONNECT)){
   
	        if (s_retry_num < 10) {
   
		            esp_wifi_connect();
		            s_retry_num++;
		            ESP_LOGE(TAG, "Retrying connection to WiFi %d times",s_retry_num);
		        }else{
   
		        	ESP_LOGE(TAG,"Connection to WiFi failed");
		        	ESP_ERROR_CHECK(esp_event_handler_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, &ip_event_handler));
		        }
    		}else{
   
    			bitClear(state_flag,BIT_CONFIG_DISCONNECT);    //清除配网断开标志
    		}
    		break;
    	default:
    		ESP_LOGI(TAG, "Unknown event ID:%ld", event_id);
    	}
    }else if (event_base == IP_EVENT){
   
        ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data;
        ESP_LOGI(TAG, "IP Address:" IPSTR, IP2STR(&event->ip_info.ip));
        s_retry_num = 0;          //清除重连计数
    
### ESP32 IDF WiFi Configuration and Troubleshooting For configuring Wi-Fi on the ESP32 using ESP-IDF, one must first ensure that all necessary development tools are installed as part of setting up the environment. This includes not only installing ESP-IDF but also ensuring various required utilities such as compilers, debuggers, Python packages among others are present within your system by executing commands like `cd ~/esp/esp-idf` followed by running `./install.sh esp32` to set everything up properly[^1]. Once this setup phase is complete, attention turns towards actually establishing a connection with an access point (AP). The process involves initializing both TCP/IP stack alongside Wi-Fi driver through calls made from application code written specifically for these purposes. #### Initializing Wi-Fi Connection Code Example To establish connectivity between device and AP: ```c #include "esp_wifi.h" #include "nvs_flash.h" void wifi_init_sta(void){ // Initialize NVS. esp_err_t ret = nvs_flash_init(); if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { ESP_ERROR_CHECK(nvs_flash_erase()); ret = nvs_flash_init(); } static wifi_config_t cfg = { .sta = { .ssid = CONFIG_ESP_WIFI_SSID, .password = CONFIG_ESP_WIFI_PASSWORD, }, }; // Start Wi-Fi in station mode. ESP_ERROR_CHECK( esp_wifi_start() ); ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_STA) ); ESP_ERROR_CHECK( esp_wifi_set_config(WIFI_IF_STA, &cfg) ); printf("Connecting...\n"); } // Call function during initialization or at appropriate place in user's program logic wifi_init_sta(); ``` In cases where issues arise while attempting connections—such as failure messages indicating inability to connect—it becomes important to verify several factors including SSID/password correctness, signal strength near router/access-point location, interference levels caused possibly due nearby electronic devices operating similar frequencies bands used here etcetera. Additionally, checking whether JTAG debugging has been enabled via sdkconfig can sometimes help diagnose problems more effectively since certain configurations might interfere unintentionally when trying achieve stable wireless network links[^2]. --related questions-- 1. What steps should be taken after encountering persistent Wi-Fi connection failures? 2. How does enabling/disabling specific features in sdkconfig impact overall performance? 3. Can you provide examples demonstrating how environmental variables influence successful establishment of Wi-Fi sessions? 4. Are there any particular settings related to power management which could affect Wi-Fi stability?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值