Close

More play with nodemcu

A project log for Fiddling with the esp8266

A place to scribble down my notes when playing with the esp8266 wifi chip. Might be helpfull to others as well...

androidersAndroiders 03/02/2015 at 15:510 Comments

Got some time today to play more with nodemcu. I thought i would try the gpio module to, you know, turn on a led :)

I hooked up a led directly to gpio2 pin. And issued the commands (in a connected terminal)

gpio.mode(2,gpio.OUTPUT)

gpio.write(2,gpio.HIGH)

Nothing happened. This is supposed to set gpio2 to output and set it to a high evel, turning the led on. Or so i thought. I tried with gpio0 as well but to no avail. I didnt really believe my gpio pins were broken so I looked a little bit more at the documentation. And lo and behold, there was a gpio mapping table there :) It turns out gpio2 is mapped to index 4. So:

gpio.mode(4,gpio.OUTPUT)

gpio.write(4,gpio.HIGH)

did the trick :)

With nodemcu there is an example .lua script called webap_toggle_pin.lua. It starts a webserver and lets you toggle the logic level of a pin. Awesome!

A few tweeks of the code:

wifi.setmode(wifi.STATION);
wifi.ap.config({ssid="YOURNETWORKHERE",pwd="YOURPASSWORDHERE"});
pin = 4;
gpio.mode(pin, 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> Hello, NodeMcu.</h1><form src=\"/\">Turn PIN <select name=\"pin\" onchange=\"form.submit()\">";
        local _on,_off = "",""
        if(_GET.pin == "ON")then
              _on = " selected=true";
              gpio.write(pin, gpio.HIGH);
        elseif(_GET.pin == "OFF")then
              _off = " selected=\"true\"";
              gpio.write(pin, gpio.LOW);
        end
        buf = buf.."<option".._on..">ON</opton><option".._off..">OFF</option></select></form>";
        client:send(buf);
        client:close();
        collectgarbage();
    end)
end)
Upload this to the esp and issue restart and dofile. I had som problems at first with running it. It seems that you cant update the same file that is running. So if you want to upload this to main.lua make sure it is not currently running that script. Now, this information might not be 100% correct but making sure of this works for me.

Now you can get the ip by typing print(wifi.sta.getip()). Then you can just take that ip and put in your browser and control your led :)

Discussions