Search code examples
luanodemcuesplorer

How to start a Lua program automatically right after NodeMCU comes out after reset


I would like to save a Lua program on NodeMCU memory. When NodeMCU is done booting after reset and ready to receive a command, this script should start executing automatically without NodeMCU attached to any external computer (through ESPlorer etc.). I should still be able to terminate the execution through ESPlorer. A working example would be very much appreciated.


Solution

  • init.lua is your friend. See the full documentation at https://nodemcu.readthedocs.io/en/latest/en/upload/#initlua.

    -- load credentials, 'SSID' and 'PASSWORD' declared and initialize in there
    dofile("credentials.lua")
    
    function startup()
        if file.open("init.lua") == nil then
            print("init.lua deleted or renamed")
        else
            print("Running")
            file.close("init.lua")
            -- the actual application is stored in 'application.lua'
            -- dofile("application.lua")
        end
    end
    
    print("Connecting to WiFi access point...")
    wifi.setmode(wifi.STATION)
    wifi.sta.config(SSID, PASSWORD)
    -- wifi.sta.connect() not necessary because config() uses auto-connect=true by default
    tmr.alarm(1, 1000, 1, function()
        if wifi.sta.getip() == nil then
            print("Waiting for IP address...")
        else
            tmr.stop(1)
            print("WiFi connection established, IP address: " .. wifi.sta.getip())
            print("You have 3 seconds to abort")
            print("Waiting...")
            tmr.alarm(0, 3000, 0, startup)
        end
    end)
    

    Update

    The current syntax for wifi.sta.config is as follows:

    station_cfg={}
    station_cfg.ssid=SSID
    station_cfg.pwd=PASSWORD
    wifi.sta.config(station_cfg)