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

User avatar
By BlueAnt
#12535 Hi,
Can anybody provide an explanation why I have to do as described below:

I count pulses on GPIO12 using PulseCount.lua called from init.lua shown below. When the ESP is restarted it appears as if the GPIO initialization does not happen correctly as no pulses is registered and reported except if I manually execute dofile('PulseCount.lua') again. The pulse counting then starts as shown.

My work around is to modify the init.lua file and execute the dofile('PulseCount.lua') twice as follows:

Code: Select all--modified init.lua

print("Pulsecounter")
dofile('PulseCount.lua')
dofile('PulseCount.lua')


The original init.lua not working is as follows:

Code: Select all--original init.lua

print("Pulsecounter")
dofile('PulseCount.lua')


Code: Select all--PulseCount.lua

kWhPulses = 0
TotalPulses = 0
Sample = 120000

gpio.mode(6, gpio.INT,gpio.PULLUP)
gpio.trig(6, "down", kWhPulseInterrupt)

function kWhPulseInterrupt()
     kWhPulses = kWhPulses+1
end

function Report()
     kWh = 3600 / Sample * kWhPulses
     TotalPulses = kWhPulses + TotalPulses
     print("kWh: "..kWh .."")
     print("Total Pulses: "..TotalPulses .."")
     print(" ")
     kWhPulses = 0
end

tmr.alarm(1, Sample, 1, function() Report() end)


Data.png
Data.png (9.28 KiB) Viewed 5017 times
User avatar
By draco
#12551 I think your problem is here:

Code: Select allgpio.trig(6, "down", kWhPulseInterrupt)


you are telling gpio.trig to call the kWhPulseInterrupt function every time it pulses. But at that point in the program, you haven't defined the kWhPulseInterrupt function yet, so it doesn't exist. try moving this line down to the end of the file.

When you're re-running the file, that function does already exist, so gpio.trig knows what to do.