NodeMCU error connecting to WiFi

只愿长相守 提交于 2019-12-12 05:43:16

问题


I have tried a blink on the NodeMCU working ok, but when doing basic connection to WiFi I get this error:

init.lua:4: attempt to concatenate global 'gw' (a nil value)

this is the connection

wifi.setmode(wifi.STATION)
wifi.sta.config("wifi-name","password") 
ip, nm, gw=wifi.sta.getip()
print("\nIP Info:\nIP Address: "..ip.." \nNetmask: "..nm.." \nGateway Addr: "..gw.."\n")

回答1:


With NodeMCU many functions are asynchronous (assume this to be the default). Hence, calling wifi.sta.config isn't blocking your main thread and consequently your device most likely isn't connected to WiFi by the time you invoke wifi.sta.getip.

If you have a firmware from the dev branch you can use the WiFi event monitor to fix that:

wifi.sta.eventMonReg(wifi.STA_GOTIP, function() 
  ip, nm, gw=wifi.sta.getip()
  print("\nIP Info:\nIP Address: "..ip.." \nNetmask: "..nm.." \nGateway Addr: "..gw.."\n")
end)

I documented a more basic timer-callback driven approach in a Gist:

wifiReady = 0

function configureWiFi()
    wifi.setmode(wifi.STATION)
    wifi.sta.config(WIFI_SSID, WIFI_PASS)
    wifi.sta.connect()
    tmr.alarm(WIFI_ALARM_ID, 1000, 1, wifi_watch)
end
-- while NOT connected to WiFi you blink a LED, see below
function wifi_watch()
    -- 0: STATION_IDLE,
    -- 1: STATION_CONNECTING,
    -- 2: STATION_WRONG_PASSWORD,
    -- 3: STATION_NO_AP_FOUND,
    -- 4: STATION_CONNECT_FAIL,
    -- 5: STATION_GOT_IP.
    status = wifi.sta.status()
    if status == 5 then
        -- only do something if the status actually changed
        -- you could of course combine these two 'if's but it's more explicit for this gist
        if wifiReady == 0 then
            wifiReady = 1
            print("WiFi: connected")
            turnWiFiLedOn()
            -- do something
        end
    else
        wifiReady = 0
        print("WiFi: (re-)connecting")
        turnWiFiLedOnOff()
        wifi.sta.connect()
    end
end


来源:https://stackoverflow.com/questions/37495036/nodemcu-error-connecting-to-wifi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!