【发布时间】:2019-06-12 21:46:56
【问题描述】:
我正在用 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 -- if led is off for more than 1 second, reset counter = 0
counter1 = counter1 + 1
elseif ((ledStatus ==0 and ((os.difftime(os.time(),t2)/100000) > 1000))) then -- increment counter when led is on
counter1 = 0
end
end
print (counter1)
结束 我确定间隔的逻辑是错误的,因为 os.time 返回一个巨大的数字(我假设它在 psecond 而不是秒)。
欢迎提出任何建议或解决方案。在此之前我尝试过 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 -- if led is off for less than 1 second
ledCounter = ledCounter + 1
elseif ((ledValue < OnThreshHold) and (dt > 1)) then-- if led is off for more than 1 second
ledCounter = 0;
else
ledCounter = ledCounter
end
print (ledCounter)
end
end
最终,它将返回 ledCounter 而不是打印计数器,因为我会将计数器的值插入另一个函数,该函数将打印与计数器数量相对应的消息
【问题讨论】:
标签: lua