As the title says... Chat on...

User avatar
By JeffT
#15483 Hi folks

I'm a c# programmer so sort of spoilt by the easy availability of setting up multiple threads. I'm teaching myself Lua and am stuck on syntax and program structure using tmers.

Basically if someone can point me to some code that shows for example how to switch a led on for X seconds, then off for Y seconds and continues to do so forever. That would be a good start. The next step might be being able to accept an input from another pin so that it jumps out , runs a function - then goes back into the timing loop -

It would be fantastic if there was a site where code snippets like these were freely available but I've been unable to find anything so far.

Any help appreciated.
User avatar
By Felipe Echanique
#15540
Code: Select allgpio.mode(0, gpio.OUTPUT)
status = 'ON'

function changeStatus()
    if status == 'ON' then
        gpio.write(0, gpio.LOW)
        status = 'OFF'
    else
        gpio.write(1, gpio.HIGH)
        status = 'ON'
    end
end

tmr.alarm(1,1000,1, function() changeStatus() end)

The first parameter is which timer are you using. You can use 6 timers (from 1 to 6)
The second parameter are milliseconds between calls (1000 = 1 second)
The third parameter sets if is one time timer (0) or infinity timer (1)
Then you can set the code execution when the timer fires. In this case the code execution is a function call.

https://github.com/nodemcu/nodemcu-firm ... mcu_api_en

Regards
User avatar
By TerryE
#15559 One of the most important things to realise about the NodeMCU eLua implementation is that it is event driven (a bit like jQuery in programming inside a client browser). Each event (e.g. a timer alarm or an on "receive") invokes a new event sequence starting with an invocation of the defined routine, which runs to conclusion. Any subsequent events are only fired when the current one concludes.

The best way to organise your code is to use globals to pass context and data between these separate event initiated Lua code sequences. Wherever practical, keep each the processing of each event as simple and short as possible. Ingeneral if you are using tmr.delay() or have long running poll loops, etc. then you are going about it the wrong way.