Chat freely about anything...

User avatar
By amadeus84
#33734 I'm using an esp8266-03 to make a light switch with a web interface and a motion sensor. I have nodeMCU running on the esp8266 and I modified the

nodemcu_firmware/lua_examples/http_server.lua

file to serve a page that turns 4 pins (each connected to a separate relay) on and off. So I have

wifi.setmode(wifi.STATION);
wifi.sta.config(SSID, SSID_PASSWORD);
wifi.sta.autoconnect(1);

wait_for_wifi_conn();
svr=net.createServer(net.TCP,30);
svr:listen(80,connect);

and a callback function that gets called when a client connects to the esp module, reads the state of the pins and serves the web page. That part is working beautifully.

Now I want to add a motion sensor (with a photo cell) to the whole thing. So I'll be using a new pin to read input from the motion sensor. How do I actually do that? Read the pin in an infinite loop, and sleep for e.g. 100 ms between reads? How would this interfere with srv:listen()? On a real computer, with an operating system, these two (the web server and the motion sensor loop) should be in different threads. But on the esp, what's the right way to do this?

Thanks!
User avatar
By lbeckm3
#33739 Honestly I'm totally new to this so keep that in mind with this bit of advice;

I have an ESP-03 module that serves up a webpage like you do (only mine reads a temperature sensor). Anyway, I also set a timer loop that also reads the temp and then posts it up to thinkspeak. Those loops are pretty cool in that it is coded in milliseconds and you can set up up to 7 of them to run at different times. Example;

Code: Select allfunction displayRain()
print("The rain in spain \n")
end

function displayFun()
print("Isn't LUA fun!!\n")
end

tmr.alarm(0, 900000, 1, function() displayRain() end )
tmr.alarm(1, 60000, 1, function() displayFun() end )

--My webserver code shows up here


Now every 15 minutes (900000 milliseconds) it will print "the rain in spain" and every minute (60000 milliseconds) it will print "Isn't LUA fun..". I'd think you could shorten the time length to check the sensor and do something. Also the webserver responds as normal. Worth a shot anyway...

-Lyle
User avatar
By amadeus84
#33970 Beautiful! I don't know how socket:listen() and tmr:alarm() are interleaved under the hood, but if it works it works! (Haven't had a chance to try it yet).

Now if I could only fit the whole thing (with power supply and all) inside the electrical box in place of my existing dumb switch... Anybody with experience on that, please comment.