NodeMCU|NodeMCU API开发

【NodeMCU|NodeMCU API开发】摘录: [像Arduino一样简单的开源可编程固件,还有Wifi哦!]
连接到路由器

print(wifi.sta.getip()) --nil wifi.setmode(wifi.STATION) wifi.sta.config("SSID","password") print(wifi.sta.getip()) --192.168.18.110

像Arduino一样操作IO
pin = 1 gpio.mode(pin,gpio.OUTPUT) gpio.write(pin,gpio.HIGH) gpio.mode(pin,gpio.INPUT) print(gpio.read(pin))

简单的HTTP客户端
-- A simple http client conn=net.createConnection(net.TCP, false) conn:on("receive", function(conn, pl) print(pl) end) conn:connect(80,"121.41.33.127") conn:send("GET / HTTP/1.1\r\nHost: www.nodemcu.com\r\n" .."Connection: keep-alive\r\nAccept: */*\r\n\r\n")

更简单的HTTP服务器
-- a simple http server srv=net.createServer(net.TCP) srv:listen(80,function(conn) conn:on("receive",function(conn,payload) print(payload) conn:send(" Hello, NodeMcu.") end) end)

PWM操作
function led(r,g,b) pwm.setduty(1,r) pwm.setduty(2,g) pwm.setduty(3,b) end pwm.setup(1,500,512) pwm.setup(2,500,512) pwm.setup(3,500,512) pwm.start(1) pwm.start(2) pwm.start(3) led(512,0,0) -- red led(0,0,512) -- blue

闪烁LED
lighton=0 tmr.alarm(0,1000,1,function() if lighton==0 then lighton=1 led(512,512,512) -- 512/1024, 50% duty cycle else lighton=0 led(0,0,0) end end)

启动文件
--init.lua will be excuted file.open("init.lua","w") file.writeline([[print("Hello World!")]]) file.close() node.restart()-- this will restart the module.

用定时器来循环执行
tmr.alarm(1,5000,1,function() print("alarm 1") end) tmr.alarm(0,1000,1,function() print("alarm 0") end) tmr.alarm(2,2000,1,function() print("alarm 2") end) -- after sometime tmr.stop(0)

纯Lua写的telnet服务器
-- a simple telnet server s=net.createServer(net.TCP,180) s:listen(2323,function(c) function s_output(str) if(c~=nil) then c:send(str) end end node.output(s_output, 0) -- re-direct output to function s_ouput. c:on("receive",function(c,l) node.input(l) --like pcall(loadstring(l)), support multiple separate lines end) c:on("disconnection",function(c) node.output(nil) --unregist redirect output function, output goes to serial end) print("Welcome to NodeMcu world.") end)

与传感器接口
-- read temperature with DS18B20 t=require("ds18b20") t.setup(9) addrs=t.addrs() -- Total DS18B20 numbers, assume it is 2 print(table.getn(addrs)) -- The first DS18B20 print(t.read(addrs[1],t.C)) print(t.read(addrs[1],t.F)) print(t.read(addrs[1],t.K)) -- The second DS18B20 print(t.read(addrs[2],t.C)) print(t.read(addrs[2],t.F)) print(t.read(addrs[2],t.K)) -- Just read print(t.read()) -- Just read as centigrade print(t.read(nil,t.C)) -- Don't forget to release it after use t = nil ds18b20 = nil package.loaded["ds18b20"]=nil

以上来自国内NodeMCU提供的示例代码
  • 现在是知识分享新崛起的网络平台,笔者在这里建立一个专题,欢迎喜欢NodeMCU的朋友能够投稿,这样方便更多的围观者参与到物联网开发的怀抱中来.
  • 官方的提供API笔者手中有一份软件翻译的中文版,鉴于机器识别度不是那么准确,和笔者三毛的英语级别,暂时不直接发布,待笔者通过一定的代码测试以后,会贴上来与大家一起分享

    推荐阅读