Post your best Lua script examples here

User avatar
By kadzsol
#84849 Hi,

I would like to read the ADC as fast as possible and transfer the measured data via Wifi. Because the LUA timer is not able to tick faster then 1ms, I have created a while loop, localized variables and adc_read function, pumped up the CPU, and was able to sample with 11.36kHz:

Code:

node.setcpufreq(node.CPU160MHZ)
local mytimer = tmr.create()
mytimer:register(1000, 1, function (t)
if wifi.sta.getip() == nil then
print("Connecting to AP...")
else
t:unregister()
local count1 = 0
local count2 = 0
local adc_read = adc.read
local adc_value
print("\nTime at start: "..tmr.time().."s")
while (count1 < 1000000) do
count1 = count1 + 1
count2 = count2 + 1
adc_value = adc_read(0)
if (count2 == 500) then
tmr.wdclr()
count2 = 0
-- we could wifi-transfer the collected data here
end
end
print("Time at end: "..tmr.time().."s")
print("Counter: "..count1)
end
end)
mytimer:start()

Output: Time at start: 1s
Time at end: 89s
Counter: 1000000

Of course the WIFI is not operational as a result of the long while loop, so I am not able to send the measured data. Is there any way to yield some time for the system in the while loop to keep the SDK/Wifi alive?
User avatar
By Sean Phelan
#87174 Hi kadzsol - it's several months since you asked this question, but I hope this might be helpful for you or others:

The ESP8266's ADC is very, very basic.... no reference voltage, no meaningful '0', and of course no interrupts.

I think you would get better results with less development, and MUCH less frustration, using an external ADC that generates interrupts. Read it over i2c or some other protocol.

For DC voltage and current measurements I like the INA219 and INA260, but there are many, many others.

The INA260 can raise an interrupt as it completes a measurement, and it can generate continuous measurements. I'd expect it to sample at approximately the rate you are achieving - just over 10k per sec - with 9 bit resolution, or up to 12 bit resolution at lower sampling rates. Other devices can go much faster.

Use the ESP8266 to configure the ADC then handle interrupts, buffer the data and send over wifi.

Cheers
Sean