You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NodeMCU Lua创建10秒间隔定时器出现语法错误该如何解决?

错误原因

你的代码存在2处语法/使用错误:

  • 第一处:tmr.create是创建定时器对象的方法,你没有加括号执行调用,直接把函数本身赋值给了mytimer,正确写法需要加括号调用获取定时器实例:mytimer = tmr.create()
  • 第二处:tmr:register()的第三个参数要求传入回调函数对象,你写的my_function() end属于语法错误,如果你要把已经定义好的my_function作为回调,直接传函数名即可;如果需要包裹自定义逻辑,需要补全function关键字。

修正后的代码

-- 写法1:直接传入已经定义的函数作为回调
mytimer = tmr.create()
mytimer:register(10000, tmr.ALARM_AUTO, my_function)
mytimer:start()

-- 写法2:如果需要在回调里加额外逻辑,使用匿名函数包裹
mytimer = tmr.create()
mytimer:register(10000, tmr.ALARM_AUTO, function() 
    -- 可在此处添加其他自定义逻辑
    my_function() 
end)
mytimer:start()

内容的提问来源于stack exchange,提问作者protospheric

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 09:57:00