bh1750_Example2.lua 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. -- ***************************************************************************
  2. -- BH1750 Example Program for ESP8266 with nodeMCU
  3. -- BH1750 compatible tested 2015-1-30
  4. --
  5. -- Written by xiaohu
  6. --
  7. -- MIT license, http://opensource.org/licenses/MIT
  8. -- ***************************************************************************
  9. --Updata to Lelian
  10. --Ps 需要改动的地方LW_GATEWAY(乐联的设备标示),USERKEY(乐联userkey)
  11. --Ps You nees to rewrite the LW_GATEWAY(Lelian's Device ID),USERKEY(Lelian's userkey)
  12. local bh1750 = require("bh1750")
  13. local sda = 6 -- sda pin, GPIO12
  14. local scl = 5 -- scl pin, GPIO14
  15. local ServerIP
  16. do
  17. bh1750.init(sda, scl)
  18. tmr.create():alarm(60000, tmr.ALARM_AUTO, function()
  19. bh1750.read()
  20. local l = bh1750.getlux()
  21. --定义数据变量格式 Define the veriables formate
  22. local PostData = "[{\"Name\":\"T\",\"Value\":\"" ..(l / 100).."."..(l % 100).."\"}]"
  23. --创建一个TCP连接 Create a TCP Connection
  24. local socket = net.createConnection(net.TCP, 0)
  25. --域名解析IP地址并赋值 DNS...it
  26. socket:dns("www.lewei50.com", function(_, ip)
  27. ServerIP = ip
  28. print("Connection IP:" .. ServerIP)
  29. end)
  30. --开始连接服务器 Connect the sever
  31. socket:connect(80, ServerIP)
  32. socket:on("connection", function() end)
  33. --HTTP请求头定义 HTTP Head
  34. socket:send("POST /api/V1/gateway/UpdateSensors/LW_GATEWAY HTTP/1.1\r\n" ..
  35. "Host: www.lewei50.com\r\n" ..
  36. "Content-Length: " .. string.len(PostData) .. "\r\n" ..
  37. "userkey: USERKEY\r\n\r\n" ..
  38. PostData .. "\r\n")
  39. --HTTP响应内容 Print the HTTP response
  40. socket:on("receive", function(sck, response) -- luacheck: no unused
  41. print(response)
  42. end)
  43. end)
  44. end