3

Im busy working on a dimming light which my ESP-03 will control. But what I have read up on, I have a problem. Please see my code below then I will explain:

device_id = "553CDA2DEAC90"
query_id = ""
dim = 120

wifi.setmode(wifi.STATION)
wifi.sta.config("SSID","PASSWORD")
wifi.sta.connect()
wifi.sta.setip({ip="10.0.0.122",netmask="255.255.255.0",gateway="10.0.0.2"})

outpin = 7 --GPIO13 
gpio.mode(outpin,gpio.OUTPUT)
gpio.write(outpin,gpio.LOW)
inpin = 6 --GPIO12
gpio.mode(inpin,gpio.INT,gpio.PULLUP)

function zero_cross()
    dt = 75*dim
    tmr.delay(dt)
    gpio.write(outpin,gpio.HIGH)
    tmr.delay(1)
    gpio.write(outpin,gpio.LOW)
    tmr.wdclr()
end

gpio.trig(inpin,"up",zero_cross)

function sendData()
    if(wifi.sta.status() == 5)then
        conn=net.createConnection(net.TCP, 0)
        conn:connect(PORT,'IP')
        if(firstStart == 0)then
            conn:send(device_id)
            conn:send("|0|")
        else
            if(query_id == nil)then
                conn:send(device_id)
                conn:send("|0|")
                conn:send(dim)
            else
                conn:send(device_id)
                conn:send("|")
                conn:send(query_id)
                conn:send("|")
                conn:send(dim)
                query_id = nil
            end
        end
        conn:on("receive", function(conn, payload)
            payload = string.gsub(payload, " ", "")
            dim = string.sub(payload, 0, string.find(payload, "|")-1)
            payload = string.gsub(payload, dim.."|", "")
            query_id = payload
            conn:close()
        end)
    else
        wifi.sta.connect()
    end
end
tmr.alarm(6, 1000, 1, sendData )

The problem that I am facing is that when at the bottom of the script I start tmr.alarm()... But the under the function zero_cross() its uses tmr.delay and that seems to make tmr.alarm() not function anymore. All that happens is the ESP just keeps on restarting. If I run the above code seperate (just the dimming function or just the sendData function then everything works perfect). Does anyone have any suggestions?

PHP Noob
  • 413
  • 1
  • 6
  • 19

1 Answers1

0

Nodemcu call lua callback directly from hardware interrupt, while the need to use luahook, (As Lua doesn’t have direct support for interrupts, they have to be emulated). It is probably dangerous.

Solution: use only 1 interrupt same time:

local send_time, last_gpio
last_gpio = gpio.read(6)
send_time = 0

tmr.trigger(1, 10, 1, function()
    if (gpio.read(6) == 1 and last_gpio == 0) then
        last_gpio = 1
        zero_cross()
    else if (gpio.read(6) == 0 and last_gpio == 1)
        last_gpio = 0
    end

    send_time = send_time + 1

    if (send_time > 100) then
        send_data()
    end
end)
TuanPM
  • 35
  • 6