2

I am trying to connect to my wifi network on my NodeMCU board. Not sure if it's a hardware or software problem, but I could not find any help on the issue.

I am trying to use this code for connecting to the 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())

But on console I can read following:

CONNECTING
nil

I tried to put the wrong data - a WiFi SSID that does not exist, a wrong `password, but no matter what I am still getting the same output: "CONNECTING" and "nil".

I used this code to check for available networks:

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)

And this worked perfectly fine. I got on the console:

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

So it looks like the wifi module is fine and it's a software problem. I wrote the code according to the documentation. At this point I have no idea what's wrong. Any suggestions?

1 Answer 1

4

wifi.sta.connect() is not synchronous, so there'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()'s auto value is set false.

You could, however, add a callback to .config() like this:

function showip(params)
    print("Connected to Wifi.  Got IP: " .. params.IP)
end

...
station_cfg.got_ip_cb = showip
wifi.sta.config(station_cfg)

Keep in mind that wifi can go up and down all the time. If you need to pounce on connect (one-time or every connect), you really want to register a callback rather than assuming that there will be one constant connection.

The callback will have access to all your globals, so you can store software state there, just make sure you're OK with any possible race conditions you may conjure up (locking/sync is a discussion for another thread).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.