作者:zong209 | 更新時間:2016-04-08 | 瀏覽量:8347
剛學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.eqytg.org"
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.eqytg.org”,但設備是可以上線的,需要等會。
加上
cu:on("receive", function(cu, c)
print(c)
end)就有返回了