Search code examples
arduinoesp8266arduino-idearduino-esp8266

How to clear static IP configuration and start DHCP


I'm using a sketch like this:

WiFi.config(IP, Gate, Subnet);
WiFi.begin (ssid, pass);

//-- somewhere below I want to drop the static IP configuration and obtain IP with DHCP.

WiFi.disconnect ();
WiFi.begin (ssid, pass). //ssid and pass are the same as above.

But IP is not changing. It seems that WiFi hasn't been reconnected. How to drop static IP configuration without restart? I'm using nodemcu v3 with esp8266 -12e.


Solution

  • You are right. There is a DHCP issue at Arduino firmware. When I did checked from the WiFiSTA firmware implementation, I saw that staticIP flag get set once when you call config() function and never get cleared. This flag guards the DHCP start/stop operations. So, here is a solution for you. Just add the ESP SDK header to your code like:

    extern "C" {
      #include "user_interface.h"
    }
    

    Now you are able to call dhcp start function from firmware which was previously blocking by the flag. But, notice that you have to call it after WiFi.begin() with some delay. Use the code block below:

    WiFi.disconnect(true);
    delay(1000);
    WiFi.begin(ssid, pass);
    (void)wifi_station_dhcpc_start();