Post your best Lua script examples here

User avatar
By Aldo Castro
#50823 HI, I am trying to create a light control system, that has an emergengy turn off and on. It is controlled by internet using a webserver which send signals on and off. Also, I want to integrate an emergency switch to turn off and on. So I used gpio2 as an input if it is 1 is on and 0 is off. However I have a problem because the esp8266 doesnt read my signal right away, I have to send a command trough the webserver to make it work, I dont know what I did wrong. It read my signal but not when I applied but when I submit other command with the server

this is my script


wifi.setmode(wifi.STATION)
wifi.sta.config("ssid", "password")
print(wifi.sta.getip())
led1 = 3
pin = 4
orstate=0
gpio.mode(led1, gpio.OUTPUT)
gpio.mode(pin, gpio.INPUT)
print( gpio.read(pin))


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> LIGHT1 <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" and orstate==0 ))then
gpio.write(led1, gpio.HIGH) orstate=1;

elseif((_GET.pin == "OFF1" and orstate==1))then
gpio.write(led1, gpio.LOW) orstate=0;

elseif ((gpio.read(pin)==1 and orstate==0) )then
gpio.write(led1,gpio.HIGH) orstate=1 ;

elseif ((gpio.read(pin)==0 and orstate==1))then
gpio.write(led1,gpio.LOW) orstate=0 ;


end
client:send(buf);
client:close();
collectgarbage();
end)
end)
User avatar
By temporarytuesday
#51918 You have a logic error in your if block. _GET.pin will always either be ON1 or OFF1 so it will not fall into your elses. You should try dropping the second elseif for just an if.

if((_GET.pin == "ON1" and orstate==0 ))then
gpio.write(led1, gpio.HIGH) orstate=1;

elseif((_GET.pin == "OFF1" and orstate==1))then
gpio.write(led1, gpio.LOW) orstate=0;

elseif ((gpio.read(pin)==1 and orstate==0) )then
gpio.write(led1,gpio.HIGH) orstate=1 ;

elseif ((gpio.read(pin)==0 and orstate==1))then
gpio.write(led1,gpio.LOW) orstate=0 - See more at: viewtopic.php?f=19&t=10837#sthash.nNSfH07J.dpuf