如何在重置后NodeMCU出来后立即自动启动Lua程序

sm5*_*535 0 lua nodemcu esplorer

我想在NodeMCU内存上保存一个Lua程序.当NodeMCU在复位后完成启动并准备接收命令时,该脚本应该自动开始执行而不将NodeMCU连接到任何外部计算机(通过ESPlorer等).我仍然可以通过ESPlorer终止执行.非常感谢一个工作的例子.

Mar*_*tör 5

init.lua是你的朋友.请参阅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)
Run Code Online (Sandbox Code Playgroud)

更新

目前的语法wifi.sta.config如下:

station_cfg={}
station_cfg.ssid=SSID
station_cfg.pwd=PASSWORD
wifi.sta.config(station_cfg)
Run Code Online (Sandbox Code Playgroud)