首页 文章

无法从NodeMCU板连接到Wi-Fi网络

提问于
浏览
1

我想在我的NodeMCU板上连接到我的wifi网络 . 不确定这是硬件还是软件问题,但我在这个问题上找不到任何帮助 .

我正在尝试使用此代码连接到WiFi:

wifi.setmode(wifi.STATION)

station_cfg={};
station_cfg.ssid="netia9000";
station_cfg.pwd="mywifipassword";
wifi.sta.config(station_cfg)
wifi.sta.connect()
status_of_wifi = wifi.sta.status()

if status_of_wifi == wifi.STA_IDLE then print("IDLE") end;
if status_of_wifi == wifi.STA_CONNECTING then print("CONNECTING") end;
if status_of_wifi == wifi.STA_WRONGPWD then print("WRONG PS") end;
if status_of_wifi == wifi.STA_APNOTFOUND then print("404") end;
if status_of_wifi == wifi.STA_FAIL then print("500") end;
if status_of_wifi == wifi.STA_GOTIP then print("IP GOT") end;

print(wifi.sta.getip())

但在控制台上我可以阅读以下内容:

CONNECTING
nil

我试图把错误的数据 - 一个不存在的WiFi SSID,一个错误的`密码,但无论我仍然得到相同的输出:“CONNECTING”和“nil” .

我使用此代码检查可用的网络:

wifi.setmode(wifi.STATION)

-- print ap list
function listap(t)
      for ssid,v in pairs(t) do
        authmode, rssi, bssid, channel = 
          string.match(v, "(%d),(-?%d+),(%x%x:%x%x:%x%x:%x%x:%x%x:%x%x),(%d+)")
        print(ssid,authmode,rssi,bssid,channel)
      end
end

wifi.sta.getap(listap)

这非常好 . 我上了控制台:

netia9000       3       -52         e8:11:23:43:bf:a2:8f        10
-- other wi fi networks available nearby --

所以看起来wifi模块很好,这是一个软件问题 . 我根据the documentation编写了代码 . 此时我不知道出了什么问题 . 有什么建议?

1 回答

  • 3

    wifi.sta.connect()不同步,因此's no guarantee that the AP would be done connecting by the time your .status() code runs. Indeed, the docs say it should be unnecessary unless .config()'的自动值设置为false .

    但是,您可以像这样添加回调到.config():

    function showip(params)
        print("Connected to Wifi.  Got IP: " .. params.IP)
    end
    
    ...
    station_cfg.got_ip_cb = showip
    wifi.sta.config(station_cfg)
    

    请记住,wifi可以随时上下 . 如果你需要突然连接(一次或每次连接),你真的想要注册一个回调,而不是假设有一个常量连接 .

    回调可以访问所有的全局变量,因此您可以在那里存储软件状态,只需确保您可以使用任何可能的竞争条件(锁定/同步是另一个线程的讨论) .

相关问题