Post your best Lua script examples here

User avatar
By WilliamMcC
#12130 I have written the following code using an interrupt to capture pulse width and duration from a small inexpensive wind sensor which makes and breaks a circuit connected to gpio2 twice per revolution. The code basically works for a range of wind speed up to about 30 mph. I am reading 20 transitions on the sensor and getting the elapsed time. The program also runs for a period of time but then crashes. I suspect I need to do some forced garbage collection. Any help on this would be appreciated.

Code is here:
-- Written by WHMcClintic for Wind Speed using esp8266 with lua 5.1.4
-- use pin 4 as the input pulse width counter
cnt=0
rp=0
pin=4
du=0
st=0
gpio.mode(pin,gpio.INPUT)
function onStart()
if cnt == 0 then st=tmr.now()
end
rp=gpio.read(pin)
--print(rp)
cnt=cnt+1
if cnt == 10 then et=tmr.now()
du=et-st
ws=(60-(du/30000))
ws=ws/2
if ws<1 then ws=0
end
print("Wind Speed mph is "..ws)
cnt=0
end
end
gpio.mode(pin,gpio.INT)
gpio.trig(pin, 'both', onStart)
User avatar
By Vitoa
#12222 Hi dont know for sure what is causing that beacuse didnt test code, but instead of gpio.trig(pin, 'both', onStart) try
gpio.trig(pin, 'down', onStart)

Using 'both' means that interrupt function is called on ascendent and descendent transitions, this makes the function be called many times making code unpredictable at high switching speed..
Instead try 'down' This means falling edge or 'up' is rasing edge interrupt

Other problem could be debounce needed for that input, the anemometer should use a magnetic switch, this causes spikes during transition 0->1 and 1->0
If this is happening u must use some delay to read input after interrupt, otherwise the code will be unstable because of this spkies after transition.

Also for interrupts u have 'low' level or 'high' level instead of transition , u can also try this to have some conclusions. gpio.trig(pin, 'low', onStart)

Regards,Vito
User avatar
By WilliamMcC
#12296 Thanks.
I seem to not any more crashes. Not sure what that was. I will try software debounce and also a falling interrupt. The problem seems to be at higher rates. I am adding 10 pulse durations and then taking the average. Changing from both to falling will double the time between interrupts.
I will post back to see if this fixes the problem.
User avatar
By GerryKeely
#12314 Hi

I think the reason for the crashes is that Lua( being a interpreted language) just can't keep up. I tried your program using a frequency generator which produces a clean square wave and it still eventually crashes.Perhaps one way around the problem is to have an init.lua file which will restart your program.

init.lua file:
Code: Select alltmr.alarm(0,1000,0, function() dofile("windSpeed.lua") end)


regards
Gerry