恐慌:在调用Lua API时发生了未受保护的错误(stdin:8:尝试调用全局变量“run”(值为nil))

使用来自https://github.com/nodemcu/nodemcu-firmware的NodeMCU运行以下代码:

ssid = "www.mydomain.com"
pass = "234234234432"

gpio.write(0, gpio.LOW)

print("Startup up wifi mode")

wifi.setmode(wifi.STATION)
wifi.sta.config(ssid, pass)

wifi.sta.autoconnect(1)
wifi.sta.connect()

tmr.alarm(3, 1000, 1, function()
    if (wifi.sta.status() < 5) then
        print("Connecting...")
    else
        tmr.stop(3)
        print("Connected having IP "..wifi.sta.getip())
        gpio.write(0, gpio.HIGH)
        run()
    end
end)

gpio.write(0, gpio.HIGH)

function run()
    print("run")

    myhost="www.adafruit.com"
    mypage="testwifi/index.html"
    myip=""

    sk=net.createConnection(net.TCP, 0)
    sk:dns(myhost,function(conn,ip)
    myip=ip
    sk=net.createConnection(net.TCP, 0)
    sk:on("receive", function(sck, c) print(c) end )
    sk:connect(80,myip)
    sk:send("GET / " .. mypage .." HTTP/1.1\r\nHost: " .. myhost .."\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n")
    sk=nil

end

我得到了这个错误:

PANIC: unprotected error in call to Lua API (stdin:8: attempt to call global 'run' (a nil value))
����m������!������!�1���
Waiting answer from ESP - Timeout reached. Command aborted.

我该怎么解决这个问题?

点赞
用户131929
用户131929

请记住,NodeMCU/Lua是完全异步的,函数需要在调用之前定义。

function start()
  tmr.alarm(3, 1000, 1, function()
      if (wifi.sta.status() < 5) then
          print("正在连接...")
      else
          tmr.stop(3)
          print("已连接,IP地址为 "..wifi.sta.getip())
          gpio.write(0, gpio.HIGH)
          run()
      end
  end)

  gpio.write(0, gpio.HIGH)
end

function run()
    print("run")

    myhost="www.adafruit.com"
    mypage="testwifi/index.html"
    myip=""

    sk=net.createConnection(net.TCP, 0)
    sk:dns(myhost,function(conn,ip)
    myip=ip
    sk=net.createConnection(net.TCP, 0)
    sk:on("receive", function(sck, c) print(c) end )
    sk:connect(80,myip)
    sk:send("GET / " .. mypage .." HTTP/1.1\r\nHost: " .. myhost .."\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n")
    sk=nil
end

start()

此外,请考虑一下如果设备成功连接后失去与WiFi的连接会发生什么。您停止了计时器...

2015-11-06 07:39:47