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

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

我想在 NodeMCU 内存上保存一个 Lua 程序。当 NodeMCU 在重置后完成启动并准备好接收命令时,此脚本应自动开始执行,而无需将 NodeMCU 连接到任何外部计算机(通过 ESPlorer 等)。我应该仍然能够通过 ESPlorer 终止执行。非常感谢一个工作示例。

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)

更新

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

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