如何在lua中定时事件

我正在lua中编写一个简单的脚本。如果LED亮着,它将把计数器递增1。如果LED熄灭超过1秒钟,则重置计数器。

那么我们如何在lua中计时事件呢?

这是我已经尝试多种方法测试过的内容:

function ReadADC1()
    local adc_voltage_value = 0
    adc_voltage_value = tonumber(adc.readadc()) * 2 -- 0.10 --get dec number out of this -- need to know where package adc come from
    --convert to voltage
    adc_voltage_value = adc_voltage_value *0.000537109375 --get V
    adc_voltage_value = math.floor(adc_voltage_value *1000 +0.5) --since number is base off resolution

    --print (adc_voltage_value)
    return adc_voltage_value

end
-- end of readADC1() TESTED

function interval()
local counter1 =0
ledValue = ReadADC1()
if (ledValue >= OnThreshHold) then
    ledStatus = 1
    t1=os.time()
else
    ledStatus = 0
    t2 = os.time()
end

--counter1 =0
for i=1,20 do
if (ledStatus == 1) then -- 如果LED关闭超过1秒,将计数器重置为0
counter1 = counter1 + 1
elseif ((ledStatus ==0 and ((os.difftime(os.time(),t2)/100000) > 1000))) then -- 当LED处于开启状态时递增计数器
counter1 = 0

end
end
print (counter1)

end 我知道计时器的逻辑是错误的,因为os.time返回一个巨大的数字(我假设这是以psecond而不是以 second为单位的)。

任何建议或解决方案都欢迎。我之前尝试过vmstarttimer和vmstoptimmer,但不确定它的工作原理。

编辑:

function counter()

    local ledValue = ReadADC1()
        local t1 = os.clock()
        while true do
            local t2 = os.clock()
            local dt = t2 - t1
            t1 = t2

            if ((ledValue < OnThreshHold) and (dt < 1)) then -- 如果LED关闭时间小于1秒钟,则递增计数器
                ledCounter = ledCounter + 1
            elseif ((ledValue < OnThreshHold) and (dt > 1)) then-- 如果LED关闭时间大于1秒,则将计数器重置为0
                ledCounter = 0;
            else
                ledCounter = ledCounter
            end
            print (ledCounter)
        end

end

最终,将返回ledCounter而不是打印counter,因为我将将计数器的值插入到另一个函数中,该函数将根据计数器的数量打印相应的消息

点赞
用户9185797
用户9185797

你可以使用 os.clock 函数来返回程序运行时间(以秒为单位)。

返回程序使用 CPU 时间的近似量(以秒为单位)。 源代码

以下是该函数的使用方法。

``` local t1 = os.clock() -- 开始 local t2 = os.clock() -- 结束 local dt = t2 - t1 -- 计算时间差

-- 也可以循环使用

local t1 = os.clock() -- 开始 while true do local t2 = os.clock() -- 结束 local dt = t2 - t1 -- 计算时间差 t1 = t2 -- 重置 t1

-- 使用 dt ...

end

-- 或者等待一段时间后再执行 -- 直到经过 1 秒钟

local t1 = os.clock() while (os.clock() - t1) < 1 do -- 在 dt 小于 1 的时候做事情

-- 甚至可以重置计时器(t1)来
-- 重复等待
-- t1 = os.clock() | ...

end

-- 你的例子的逻辑

function counter() local time = os.clock() local lastLedOn = false local counter = 0

while true do
    if os.clock() - time > 1.0 then
        break
    end

    if getLedValue() == on then -- 替换
        time = os.clock()

        if not lastLedOn then
            lastLedOn = true
            counter = counter + 1

            -- 如果需要反复打印的话,可以在这里打印
            -- print(counter) | 
        end
    end
end

print(counter)

end -- 无法测试

2019-01-18 16:55:08