NodeMCU WiFi setup

Connecting a NodeMCU to WiFi

NodeMCU devices have WiFi built in, and it’s easy to configure using Lua.

One of the easiest examples of setting this up was on Limpkin’s blog. I took this and tweaked it slightly so it works with the more recent Lua wifi module.

station_cfg={}
station_cfg.ssid="Rob's iPhone"
station_cfg.pwd="secret password"
wifi.setmode(wifi.STATION)
wifi.sta.config(station_cfg)
wifi.sta.connect()
tmr.alarm(1, 1000, 1, function()
    if wifi.sta.getip() == nil then
        print("IP unavailable, Waiting...")
    else
        tmr.stop(1)
        print("ESP8266 mode is: " .. wifi.getmode())
        print("The module MAC address is: " .. wifi.ap.getmac())
        print("Config done, IP is "..wifi.sta.getip())
    end
end)

Upload this using luatool or similar as the init.lua file that runs when the NodeMCU powers up.

In this example, the script tries to connect to my iPhone hotspot. We use tmr.alarm to check once a second if we have an IP address. If we don’t, we let the user know. If we do, we stop the timer from continually executing, and print out some of our wifi configuration details.

It’s at this point we could start using the connection to talk to the internet if we needed to.