【问题标题】:NodeMCU error connecting to WiFiNodeMCU 连接到 WiFi 时出错
【发布时间】:2016-09-26 11:24:51
【问题描述】:

我尝试在 NodeMCU 上闪烁一下工作正常,但是在与 WiFi 进行基本连接时出现此错误:

init.lua:4: 尝试连接全局 'gw'(一个 nil 值)

这是连接

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")

【问题讨论】:

    标签: lua nodemcu


    【解决方案1】:

    NodeMCU 的许多功能都是异步的(假设这是默认设置)。因此,调用wifi.sta.config 不会阻塞您的主线程,因此您的设备很可能在您调用wifi.sta.getip 时还没有连接到WiFi。

    如果你有来自dev 分支的固件,你可以使用WiFi event monitor 来解决这个问题:

    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)
    

    我记录了一个更基本的计时器回调驱动方法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
    

    【讨论】:

      猜你喜欢
      • 2016-05-11
      • 2017-02-15
      • 2017-05-21
      • 1970-01-01
      • 1970-01-01
      • 2017-06-09
      • 2019-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多