作者:zong209 | 更新时间:2016-04-08 | 浏览量:9049
刚学esp8266不久,经过各种碰壁,总算将DHT11数据传到贝壳上了.
第一次发帖,不足之处还请指正!
准备:
1. esp8266
2. DHT11传感器
3. 含(DHT,CJSON)的固件(自己定制)http://nodemcu-build.com/(DHT模块可以很方便的读出传感器的数据,开始不知道,花了好多时间在读数据,还总出错)
4. NodeMCU Studio 2015_beta0.3工具NodeMcu Studio 2015_beta0.3.rar
5. 果云ESP8266辅助工具果云ESP8266调试助手V1.1.zip
(可用于调试,先不上传至贝壳,可以先尝试将命令发送到本机服务器上,看命令是否符合贝壳通讯协议)
接线蛮简单(AOSONG面朝上,从左至右分别是GND,NC,OUT,VCC)
Pin | 名称 | 注释 |
1 | VDD | 供电 3-5.5VDC |
2 | DATA | 串行数据,单总线,接I/O口,上拉电阻 |
3 | NC | 空脚,请悬空 |
4 | GND | 接地,电源负极 |
代码:
local temp=0
local humi=0
pin=2
--wifi station configured
wifi.setmode(wifi.STATION)
wifi.sta.config("ssid","password ")
wifi.sta.connect()
cnt = 0
--connect
tmr.alarm(1, 1000, 1, function()
if (wifi.sta.getip() == nil) and (cnt < 20) then
print("IP unavaiable, Waiting...")
cnt = cnt + 1
else
tmr.stop(1)
if (cnt < 20) then
print("Config done, IP is "..wifi.sta.getip())
--please input your deceive parameters
DEVICEID = "设备ID"
APIKEY = "设备APIKEY"
INPUTID1 = "数据口1ID"
INPUTID2 = "数据口2ID"
host=host or "www.bigiot.net"
port=port or 8181
cu = net.createConnection(net.TCP)
cu:connect(port, host)
ok, s = pcall(cjson.encode, {M="checkin",ID=DEVICEID,K=APIKEY})
if ok then
print(s)
else
print("failed to encode!")
end
cu:send(s.."\n" )
--keeping the on-line state
tmr.alarm(1, 60000, 1, function()
cu:send(s.."\n" )
end)
--update the data and output
tmr.alarm(2, 5000, 1, function()
status, temp, humi, temp_dec, humi_dec = dht.read(pin)
if status == dht.OK then
print("DHT Temperature:"..temp..";".."Humidity:"..humi.."%")
elseif status == dht.ERROR_CHECKSUM then
print( "DHT Checksum error." )
elseif status == dht.ERROR_TIMEOUT then
print( "DHT timed out." )
end
--uploading command
str="{\"M\":\"update\",\"ID\":\""..DEVICEID.."\",\"V\":{\""..INPUTID1.."\":"..temp..",\""..INPUTID2.."\":"..humi.."}}\n"
cu:send(str)
end)
else print("Wifi setup time more than 20s, Please verify wifi.sta.config() function. Then re-download the file.")
end
end
end)
注意:1.数据获取和上传命令放在同一个定时器下(
status, temp, humi, temp_dec, humi_dec = dht.read(pin)
str="{\"M\":\"update\",\"ID\":\""..DEVICEID.."\",\"V\":{\""..INPUTID1.."\":"..temp..",\""..INPUTID2.."\":"..humi.."}}\n"
cu:send(str)
)
2.没有返回“welcome to www.bigiot.net”,但设备是可以上线的,需要等会。
加上
cu:on("receive", function(cu, c)
print(c)
end)就有返回了