VisualHMI supports32 software timers(indexed from 0 to 31). Upon startup, timeout triggers theon_timer(timer_id)callback, performing periodic tasks, delayed operations, and status polling. ⚠️ This is theapplication-level software timer, whose accuracy is affected by system load.is not suitable for hard real-time control.
. 1. API Summary Table
| Function | Parameter | Description |
|---|---|---|
start_timer(timer_id, timeout, countdown, repeat) | timeout (milliseconds) (minimum approximately 10~20ms); countdown 0=upward timing/1=downward timing; repeat 0=infinite repetition/N=automatically stops after triggering N times | Start timer |
stop_timer(timer_id) | Timer ID | Stop immediately |
on_timer(timer_id) | Unified entry for timeout callback | Use timer_id to distinguish concurrent timers |
get_timer_value(timer_id) | Timer ID | Get the current timing value (ms), supports sequential/countdown timing |
countdown parameterOnly affects internal timing display/debugging, does not change the triggering behavior of on_timer - sequential timing triggers when timeout is reached, countdown timing triggers when timeout is reduced to 0, and the callback is the same for both.
2. Basic usage
function on_init()
start_timer(0, 1000, 0, 0) -- 1秒周期,无限重复
start_timer(1, 5000, 1, 1) -- 5秒倒计时,只触发1次
end
function on_timer(timer_id)
if timer_id == 0 then
-- 每秒做一次:状态轮询
elseif timer_id == 1 then
-- 5秒后执行一次
end
end3. Application: Send instructions to PLC after countdown is completed
Requirement: Set a countdown timer for hours and minutes, with a reset button at the end of the countdown to send instructions to the mainboard. Control layout: Bit status indicator LW1002 (toggle switch) controls start and stop; scroll wheel control LW1000 (hours, 0~23) and LW1001 (minutes) set the duration; text control LW1010 displays the countdown timer.
_TIMER_REPEAT_ = 0 -- 总时长(秒)
_TIMER_CNT_ = 0 -- 已触发次数
function on_update(slave, vtype, addr)
if vtype == VT_LW and addr == 0x1002 then
if get_uint16(VT_LW, 0x1002) == 1 and _TIMER_REPEAT_ > 0 then
stop_timer(0)
start_timer(0, 1000, 0, _TIMER_REPEAT_) -- 每秒一次,共 repeat 次
else
stop_timer(0)
end
end
end
function on_timer(timer_id)
if timer_id == 0 then
_TIMER_CNT_ = _TIMER_CNT_ + 1
local remain = _TIMER_REPEAT_ - _TIMER_CNT_
-- 显示剩余时间 mm:ss
set_string(VT_LW, 0x1010,
string.format("%02d:%02d", math.floor(remain / 60), remain % 60))
if remain == 0 then
set_uint16(VT_LW, 0x1002, 0x00) -- 复位启停按钮
set_uint16(VT_LW, 0x1003, 0x01) -- 发指令给主板
end
end
endKey points: _TIMER_REPEAT_ is calculated when the user sets the duration (hour*3600 + min*60); start_timer passes the total number of repeats, and on_timer increments _TIMER_CNT_ each time, ending when they are equal. set_notify(0/1) controls whether to send notification instructions during the timer period, set to 1 when needed.
Compiled from Guangzhou Dacai Technology VisualHMI development documentation (hmi-doc.gz-dc.com) LUA tutorial "Timer", copyright owned by Dacai Technology.
Leave a Reply