Monday, September 14, 2015

NodeMCU - Avoid the system hanging from infinite loop and run TCP Server after getting IP

I was trying to develop my NodeMCU as a controller for Home Automation,
Once I found searching for wifi in loop ended in an infinite loop and hence I have to FLASH the firmware, and reload it. To avoid the same in future I did teh following

The best solution i found is create a delay of some seconds before starting the infinite loop, so that when system has to be reset, you will enough time to do it.

Some tutorials is here : http://www.esp8266.com/viewtopic.php?f=18&t=1705

From the above link Setting wifi delay is done as follows.

--Startup file It is trying to connect my mobile Wifi--
SSID =   "AndroidAP"
PWD  =    "csnv6345"
HTTPServerFile = "ServerFile.lua"
    wifi.setmode(wifi.STATION)
    wifi.sta.config(SSID, PWD)
    print("Wait 5 seconds please")
    tmr.alarm(1, 5000, 1, function() -- Infinite Loop for keep checking the wifi status in a 5s delay.
        if(wifi.sta.status() ==5) then  -- Once the IP is set, stoping the timer and executing the file.
            tmr.stop(1)
            dofile(HTTPServerFile)
        end
    end)
print("End of startup")

A Sample Server file, which on the LED on first request and off on next. to test the Wifi Connection

lighton=0
pin=0
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
    conn:on("receive",function(conn,payload)
        print(payload)
         if lighton==0 then
            lighton=1
            gpio.write(pin,gpio.HIGH)
        else
            lighton=0
             gpio.write(pin,gpio.LOW)
        end
    end)
end)



No comments: