3

With NodeMCU in station mode with the following snippet of code in init.lua it still takes on average about 6 iterations of the loop before an IP address is reported (or IP stack ready state is achieved)

wifi.sta.disconnect()
--settings.lua
SSID    = "xxxx"
APPWD   = "yyyy"

cfg =
  {
    ip="192.168.0.85",
    netmask="255.255.255.0",
    gateway="192.168.0.1"
  }
wifi.sta.setip(cfg)
wifi.sta.config(SSID,APPWD)
wifi.sta.autoconnect(1)

-- wait for WIFI ----
function checkWIFI() 
    print("Waiting for WIFI...")
    ipAddr = wifi.sta.getip()
    if ( ( ipAddr ~= nil ) and  ( ipAddr ~= "0.0.0.0" ) )then
        print("IP Address: " ..ipAddr)

    else
      -- schedule try again 
      tmr.alarm( 0 , 1000 , 0 , checkWIFI)
    end  
end
tmr.alarm( 0 , 1000 , 0 , checkWIFI)

Tried with and without static IP configuration, seems no different Is this normal? Is there a way to make faster? Am I just doing it wrong?

Andy Joiner
  • 5,932
  • 3
  • 45
  • 72

2 Answers2

0

The following is my practical experience, which may be out of date now. I need to retest these...

I do a similar thing and it works well. However, while WiFi is not available quickly after a "reset", it is available very quickly on wakeup from deep sleep.

After first use (settings are saved automatically) I later simply do this lua wifi.sta.setip(cfg) wifi.sta.status() -- this used to speed things up

I also set wifi.sta.autoconnect(0) to avoid dhcp delays.

BTW, to check for a connection it is best to wait for wifi.sta.status() == 5.

HTH

Eyal
  • 61
  • 4
0

Based on @Eyal's answer, I was able to get an IP address typically in 415-470ms from deep sleep (based on the timer), or 3.25 seconds from cold power on.

NOTE: There is no DNS resolution with this solution

Save your network config to flash

wifi.sta.clearconfig()
wifi.setmode(wifi.STATION)
station_cfg={}
station_cfg.ssid="MyWiFiNetwork"
station_cfg.pwd="MyWiFiPassword"
station_cfg.save=true
station_cfg.auto=false
wifi.sta.config(station_cfg)

On every boot

cfg =
  {
    ip="192.168.0.99",
    netmask="255.255.255.0",
    gateway="192.168.0.1"
  }
wifi.sta.setip(cfg)
wifi.sta.connect()

Test it with

function checkWIFI() 
    ipAddr = wifi.sta.getip()
    
    if ( wifi.sta.status() == wifi.STA_GOTIP )then
        --LED On
        gpio.write(4, gpio.LOW)
        gpio.mode(4, gpio.OUTPUT)
        print("Time " .. tmr.now()/1000 .. "ms")           
        print("IP Address: " ..ipAddr)

    else
      -- schedule try again 
      tmr.create():alarm(50, tmr.ALARM_SINGLE, checkWIFI)
    end  
    print("WiFi Status "  ..  wifi.sta.status())
end
tmr.create():alarm(50, tmr.ALARM_SINGLE, checkWIFI)
Andy Joiner
  • 5,932
  • 3
  • 45
  • 72