Post your best Lua script examples here

User avatar
By Defozo
#32825 Hello, I'm using ESP-01 and this code:
Code: Select allConnStatus = nil
function ConnStatus(n)
   status = wifi.sta.status()
   local x = n+1
   if (x < 500) and ( status < 5 ) then
      tmr.alarm(0,100,0,function() ConnStatus(x) end)
   else
      if status == 5 then
         uart.setup(0,9600,8,0,1)
         -- when 'a' is received.
         uart.on("data", "a",
            function(data)
               if data=="quit" then
                  uart.on("data")
               end
               conn=net.createConnection(net.TCP, 0)
               conn:on("receive", function(conn, payload) print(payload) end)
               -- api.thingspeak.com 184.106.153.149
               conn:connect(80,'184.106.153.149')
               conn:send("GET /update?key=MYKEY&field1="..data.." HTTP/1.1\r\n")
               conn:send("Host: api.thingspeak.com\r\n")
               conn:send("Accept: */*\r\n")
               conn:send("User-Agent: Mozilla/4.0 (compatible; esp8266 Lua; Windows NT 5.1)\r\n")
               conn:send("\r\n")
               conn:on("sent",function(conn)
                  conn:close()
                  gpio.write(4, gpio.LOW)
               end)
         end, 0)
         gpio.write(4, gpio.HIGH)
      else
         -- error connecting to AP
         ConnStatus(0)
      end
   end
end

gpio.mode(4, gpio.OUTPUT)
gpio.write(4, gpio.LOW)
wifi.setmode(wifi.STATION)
wifi.sta.config("SSID","password")
ConnStatus(0)


I want my ESP8266 to turn on GPIO(2 - IO INDEX: 4) when it's successfully connected to AP and then I want it to turn off GPIO(2) when it successfully sent the data.

However, my ESP8266 always sets GPIO(2) on and off and on and off just after startup (and after that works as intended). Nevertheless, this behavior is undesirable. Why is this happening? Is there a way to eliminate that?

Sorry for my English errors,
Please help,
Defozo