ESP32——WIFI静态IP设置方法(非官方)

参考:ESP32 Station 模式,如何设置静态 IP

测试参考程序:WebSocket Echo Server官方例程的改写

设置方法

停止默认开启的DHCP服务。

    esp_netif_dhcpc_stop(netif);

修改IP地址、网关和子网掩码

    esp_netif_ip_info_t info_t = {0};

    info_t.ip.addr = ESP_IP4TOADDR(192,168,1,109);

    info_t.gw.addr = ESP_IP4TOADDR(192,168,1,1);

    info_t.netmask.addr = ESP_IP4TOADDR(255,255,255,0);

    esp_netif_set_ip_info(netif,&info_t); 

完整代码

以上信息官网都有,但却未告知添加在哪里,下面是一个添加示例

static esp_netif_t *wifi_start(void)
{
    char *desc;
    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));

    esp_netif_inherent_config_t esp_netif_config = ESP_NETIF_INHERENT_DEFAULT_WIFI_STA();
    // Prefix the interface description with the module TAG
    // Warning: the interface desc is used in tests to capture actual connection details (IP, gw, mask)
    asprintf(&desc, "%s: %s", TAG, esp_netif_config.if_desc);
    esp_netif_config.if_desc = desc;
    esp_netif_config.route_prio = 128;  

    esp_netif_t *netif = esp_netif_create_wifi(WIFI_IF_STA, &esp_netif_config);
    free(desc);
    esp_wifi_set_default_wifi_sta_handlers();
    //--------------Add IP Set---------------
    esp_netif_dhcpc_stop(netif);

    esp_netif_ip_info_t info_t = {0};
    info_t.ip.addr = ESP_IP4TOADDR(192,168,1,109);
    info_t.gw.addr = ESP_IP4TOADDR(192,168,1,1);
    info_t.netmask.addr = ESP_IP4TOADDR(255,255,255,0);
    esp_netif_set_ip_info(netif,&info_t); 
    //----------------------------------------
    ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED, &on_wifi_disconnect, NULL));
    ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &on_got_ip, NULL));
#ifdef CONFIG_EXAMPLE_CONNECT_IPV6
    ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, WIFI_EVENT_STA_CONNECTED, &on_wifi_connect, netif));
    ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_GOT_IP6, &on_got_ipv6, NULL));
#endif

    ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
    //WIFI配置
    wifi_config_t wifi_config;
    bzero(&wifi_config, sizeof(wifi_config_t)); 
    memcpy(wifi_config.sta.ssid,wifi_ssid, sizeof(wifi_config.sta.ssid));
    memcpy(wifi_config.sta.password,wifi_password, sizeof(wifi_config.sta.password)); 
    wifi_config.sta.scan_method = WIFI_ALL_CHANNEL_SCAN;  

    ESP_LOGI(TAG, "Connecting to %s...", wifi_config.sta.ssid);
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
    ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config));
    ESP_ERROR_CHECK(esp_wifi_start());
    esp_wifi_connect();
    return netif;
}

猜你喜欢

转载自blog.csdn.net/tsliuch/article/details/126134904