0

I am making this code to control leds by internet but also I like to add an switch to turn it on and off in case I dont have access to internet. So my problem is that it works normally when I upload the code but when the ESP8266 get restarted the code doesnt work any longer. Every part of the code works fine independently but when I put them together it doesnot work

 wifi.setmode(wifi.STATION)
 wifi.sta.config("BELL", "BLACKST")
 print(wifi.sta.getip())
 led1 = 3
 led2 = 4

 gpio.mode(led2, gpio.OUTPUT)

  srv=net.createServer(net.TCP)
   srv:listen(80,function(conn)
   conn:on("receive", function(client,request)
    local buf = "";
    local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?     (.+) HTTP");
    if(method == nil)then
        _, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP");
    end
    local _GET = {}
    if (vars ~= nil)then
        for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do
            _GET[k] = v
        end
    end


     buf = buf.."<h1> LIGHTS CONTROL </h1>";
     buf = buf.."<p>Aldo's Room <a href=\"?pin=ON1\"><button>ON</button> </a>&nbsp;<a href=\"?pin=OFF1\"><button>OFF</button></a></p>";
      local _on,_off = "",""


    if(_GET.pin == "ON1")then
          gpio.write(led2, gpio.HIGH) ; 

    elseif(_GET.pin == "OFF1")then
          gpio.write(led2, gpio.LOW) ;


    end
    client:send(buf);
    client:close();
    collectgarbage();
     end)
     end)

     gpio.mode(led1, gpio.INT)
    gpio.trig(led1, "both", function(level)

    gpio.write(led2, level)
    end)
Marcel Stör
  • 22,695
  • 19
  • 92
  • 198
  • Hopefully a silly question, but did you put this in init.lua? – bluemind Jul 20 '16 at 07:48
  • Also, I recommend using a recent NodeMCU firmware, not 0.9.6. And you might try waiting for the WIFI to be connected, a bit like: http://stackoverflow.com/questions/33288026/the-wifi-sta-module-connects-if-a-loop-is-running/33309872#33309872 – bluemind Jul 20 '16 at 07:54
  • yes I did it, I suspect there is a bug in my init.lua but I can't find it – Aldo Castro Freire Jul 24 '16 at 01:42

1 Answers1

0

Your code needs to be put into a file called init.lua.

http://nodemcu.readthedocs.io/en/latest/en/upload/#initlua

You will see "lua: cannot open init.lua" printed to the serial console when the device boots after it's been freshly flashed. If NodeMCU finds a init.lua in the root of the file system it will execute it as part of the boot sequence (standard Lua feature). Hence, your application is initialized and triggered from init.lua. Usually you first set up the WiFi connection and only continue once that has been successful.

With ESPlorer one way to achieve this would be to store the file locally on your file system as init.lua and then hit the 'Save to ESP' button.

Marcel Stör
  • 22,695
  • 19
  • 92
  • 198