WiFi


Connecting as a STATION

Your NodeMcu may work as a station or as an access point (AP). In case you don't know, your computer or cellphone are stations, you wifi router is an access point. As a station your NodeMcu can access the internet, as an AP it creates it's own little wifi "intranet".

First, we check if NodeMcu is already connected to wifi:

print (wifi.sta.getip())
nil

if nil or "0.0.0.0" then it's not connected.

Then we tell NodeMcu to work as a station:

wifi.setmode(wifi.STATION)

Then we create a Lua table with our WiFi router's ID (SSID) and password:

station_cfg={}
station_cfg.ssid="dlink-2213"
station_cfg.pwd="xyz676614"

I have seen many examples where the configuration is made with something like "wifi.sta.config(ssid, password)" I believe that could work on previous versions of NodeMcu, but it doesn't anymore! You must create a Lua table to configure it.

Then we connect:

wifi.sta.config(station_cfg)

Yes, we are connected:

print (wifi.sta.getip())
192.168.0.21    255.255.255.0    192.168.0.1

A startup program:

So a nice start for any connection of an NodeMcu module would have the following code:

-- Setup

wifi.setmode(wifi.STATION) 
station_cfg={}
station_cfg.ssid="dlink-2213"
station_cfg.pwd="madya47256"
wifi.sta.config(station_cfg)

-- Connect 

tmr.alarm(0, 1000, 1, function()       -- Keeps checking if connection is made every second
   if wifi.sta.getip() == nil then     -- Not connected
      print("Connecting to AP...\n")
   else                                -- Connected!
      ip, nm, gw=wifi.sta.getip()      
      print("IP Address: ",ip)
      print("Netmask: ",nm)
      print("Gateway Addr: ",gw,'\n')
      tmr.stop(0)                      -- Finishes timed check
   end
end)

After a few "Connecting to AP..." attempts, you will get:

results matching ""

    No results matching ""