【问题标题】:lua: init.lua:15: attempt to call method 'alarm' (a nil value)lua: init.lua:15: 尝试调用方法 'alarm' (一个 nil 值)
【发布时间】:2020-03-27 13:35:12
【问题描述】:

我正在尝试修复我在网上找到的一段代码。 (是的,我知道....) 但如果你们能帮助我解决这个错误,那就太棒了:

错误:lua: init.lua:15: 尝试调用方法 'alarm'(一个 nil 值)

代码(来自这里:https://github.com/Christoph-D/esp8266-wakelight

dofile("globals.lc")

wifi.setmode(wifi.STATION)
wifi.sta.config(WIFI_SSID, WIFI_PASSWORD)
wifi.sta.sethostname(MY_HOSTNAME)
if WIFI_STATIC_IP then
  wifi.sta.setip({ip = WIFI_STATIC_IP, netmask = WIFI_NETMASK, gateway = WIFI_GATEWAY})
end
wifi.sta.connect()

-- Initialize the LED_PIN to the reset state.
gpio.mode(LED_PIN, gpio.OUTPUT)
gpio.write(LED_PIN, gpio.LOW)

tmr.alarm(
  MAIN_TIMER_ID, 2000, tmr.ALARM_AUTO, function ()
    if wifi.sta.getip() then
      tmr.unregister(MAIN_TIMER_ID)
      print("Config done, IP is " .. wifi.sta.getip())
      dofile("ledserver.lc")
    end
  end)

我可以在那里做什么?怎么了?

干杯,谢谢!!!

【问题讨论】:

标签: lua esp8266


【解决方案1】:

这一切都在手册中。你只需要阅读它。

有一个例子说明如何使用定时器对象的闹钟方法。

if not tmr.create():alarm(5000, tmr.ALARM_SINGLE, function()
  print("hey there")
end)
then
  print("whoopsie")
end

您试图拨打tmr.alarm,但它是tobj:alarm。手册没有提到tmr.alarm。该功能已于 2019 年 1 月从 NodeMCU 中移除。

您正在使用您在网上找到的基于旧 NodeMCU 版本的代码。它正在使用现在已弃用的功能。

https://github.com/nodemcu/nodemcu-firmware/pull/2603#issuecomment-453235401

https://github.com/nodemcu/nodemcu-firmware/compare/5b22e1f9aee77095ab99dd6240ebd9dddd1cc5a0..c6444ecb6088d20e95197d808d8303c8093faab5

所以你必须先创建一个计时器对象,然后才能使用它的任何方法。 alarm 不再是 tmr 模块的方法。


编辑

首先你要创建一个定时器对象https://nodemcu.readthedocs.io/en/latest/modules/tmr/#tobjcreate

local tObj = tmr.create()

然后你必须register 一个回调和start 计时器。有一个方便的函数alarm 可以为我们做这两件事。

当我们不再需要计时器时,我们必须通过调用来释放资源

tObj:unregister()

试试类似的东西

-- create a timer object
local tObj = tmr.create()
-- register an alarm
tObj:alarm(2000, tmr.ALARM_AUTO, function ()
    if wifi.sta.getip() then
      tObj:unregister()
      print("Config done, IP is " .. wifi.sta.getip())
      dofile("ledserver.lc")
    end
  end)

【讨论】:

  • 非常感谢您的回答!由于我对nodemcu知之甚少,这对我来说似乎有点太难了......有没有办法找到带有我想要的组件的旧nodemcu固件?谢谢!!
  • 或者您能否提供一个示例,我如何将这样的行转换为当前版本的 NodeMCU?然后我可以尝试了解我必须做什么;) " tmr.alarm(MAIN_TIMER_ID, 300, tmr.ALARM_AUTO, function ()"
猜你喜欢
  • 2017-04-03
  • 2019-09-15
  • 1970-01-01
  • 2018-07-11
  • 2014-05-06
  • 1970-01-01
  • 2011-07-31
  • 2014-11-05
  • 1970-01-01
相关资源
最近更新 更多