Post your best Lua script examples here

User avatar
By MisterBennie
#38711 Hi,

As timers are scarce (only 7), I wondered if I could exceed this number.
So I wrote my first lua code to do this.

The following timer will use one nodeMCU timer and from that moment on, you can start as many timers as you like.
It is especially useful for long timers as it is a bit too heavy for short times.
But if you have many tasks which need to run every second, minute, hour or longer, it is very useful.

Timers are identified by a key (Removal of a timer is planned, but not implemented yet)
It is also possible to start a task which will run X times with a delay of Y mSec.

In the video, 10 timers are started which will toggle the leds from D1 - D10.

Feedback is appreciated
Ben

Updated on Jan 16th 2016

Usage:
Code: Select alllocal luaTimerId = 6
timer = Timer:new(luaTimerId)
-- When nrOfTimes is 0, the timer will run forever
-- callBack is called with two paramers (key, eventNr)
-- key is the given key for this timer, eventNr is the numer of times this callback has been called for this timer.
timer:addTimeEvent("aTimerKey", delayInMilliSeconds, nrOfTimes, callBack)

-- Show all currently running timers
time:print()

Example (Timers started in 510, 500, 490 and 480 mSec):
Code: Select allGPIO05 = 1
GPIO04 = 2
GPIO00 = 3
GPIO02 = 4

gpio.mode(GPIO05 , gpio.OUTPUT)
gpio.mode(GPIO04 , gpio.OUTPUT)
gpio.mode(GPIO00 , gpio.OUTPUT)
gpio.mode(GPIO02 , gpio.OUTPUT)

function toggle(port)
    local level = gpio.read(port)
    if (level == 0) then
        level = 1
    else
        level = 0
    end
    gpio.write(port, level)
end

gpio.write(GPIO05, 1)
gpio.write(GPIO04, 1)
gpio.write(GPIO00, 1)
gpio.write(GPIO02, 1)

function startTimers()
    timer = Timer:new(1)
    timer:addTimeEvent("GPIO05", 510, 0, function(key, eventNr) toggle(GPIO05) end)
    timer:addTimeEvent("GPIO04", 500, 0, function(key, eventNr) toggle(GPIO04) end)
    timer:addTimeEvent("GPIO00", 490, 0, function(key, eventNr) toggle(GPIO00) end)
    timer:addTimeEvent("GPIO02", 480, 0, function(key, eventNr) toggle(GPIO02) end)
end

startTimers()

Timer.lua: https://github.com/MisterBennie/NodeMCU