Close

nodeMCU Lua code

A project log for IoT power strip using ESP8266

IoT power strip controlled by ESP8266 and SSR.

Pedro MinatelPedro Minatel 07/28/2015 at 19:040 Comments
srv=net.createServer(net.TCP)
pin=6
led_1=8
led_2=5
led_3=4
status=true
gpio.mode(pin,gpio.OUTPUT)
gpio.mode(led_1,gpio.OUTPUT)
gpio.mode(led_2,gpio.OUTPUT)
gpio.mode(led_3,gpio.OUTPUT)
gpio.write(pin,1)
gpio.write(led_1,0)
gpio.write(led_2,0)
gpio.write(led_3,1)
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> ESP8266 IoT Power Strip Web Server</h1>";
        buf = buf.."<p>Lampada <a href=\"?pin=ON1\"><button>ON</button></a>&nbsp;<a href=\"?pin=OFF1\"><button>OFF</button></a></p>";
        buf = buf.."<br><br>";
        buf = buf.."<h2>Developed by Pedro Minatel</h2>";
        local _on,_off = "",""
        if(_GET.pin == "ON1")then
              gpio.write(pin,1)
              gpio.write(led_1,0)
              gpio.write(led_2,1)
              gpio.write(led_3,0)
              status = true
        elseif(_GET.pin == "OFF1")then
              gpio.write(pin,0)
              gpio.write(led_1,1)
              gpio.write(led_2,0)
              gpio.write(led_3,0)
              status = false
        elseif(_GET.pin == "TG1")then
              if(status == true)then
                    gpio.write(pin,0)
                    status = false
              else
                    gpio.write(pin,1)
                    status = true
              end
        end
        client:send(buf);
        client:close();
        collectgarbage();
    end)
end)

Discussions