nodeMCU-esp8266 lua---DHT11采集温湿度上报阿里云
作者:互联网
引脚接的是PD5
wifitab={}
wifitab.ssid = "lei"
wifitab.pwd = "leizhe123"
wifi.setmode(wifi.STATION)
wifi.sta.config(wifitab)
wifi.sta.connect()
timer1 = tmr.create()
timer2 = tmr.create()
ProductKey = "a1BDinky4Et"
DeviceName = "demo_voice"
DeviceSecret = "KaFwazd5x4AjHdsFQ2HFluIjOZkUg0ZE"
RegionId = "cn-shanghai"
ESP8266ClientId = 20200510
SubTopic="/a1BDinky4Et/demo_voice/user/get"
Pubtopic="/sys/a1BDinky4Et/demo_voice/thing/event/property/post"
BrokerAddress = ProductKey..".iot-as-mqtt."..RegionId..".aliyuncs.com"
BrokerPort = 1883
HmacData = "clientId"..ESP8266ClientId.."deviceName"..DeviceName.."productKey"..ProductKey
MQTTClientId = ESP8266ClientId.."|securemode=3,signmethod=hmacsha1|"
MQTTUserName = DeviceName.."&"..ProductKey
MQTTPassword = crypto.toHex(crypto.hmac("sha1",HmacData,DeviceSecret))
function ConnectWifi()
if wifi.sta.getip() == nil then
print("Connecting...")
else
timer1:stop()
print("Connect AP success")
print(wifi.sta.getip())
MQTTClient = mqtt.Client(MQTTClientId, 120, MQTTUserName, MQTTPassword, false)
MQTTClient:connect(BrokerAddress, BrokerPort, 0, function(client)
timer1:stop()
print("MQTT connect success")
MQTTClient:subscribe(SubTopic,0,function(conm)
print("MQTT subscribe success")
MQTTOn()
end)
end,
function(client,reason)
print("MQTT connect fail:"..reason)
end)
end
end
function MQTTOn()
print("MQTT listen...")
timer1:alarm(1000, tmr.ALARM_AUTO, MQTTPublish)
end
function MQTTPublish()
tmr.delay(1000)
tmr.delay(1000)
pin = 5
status, temp, humi, temp_dec, humi_dec = dht.read11(pin)
data = {}
data.voice = 1
data.CurrentTemperature = temp -- DHT_11(temp1)
data.CurrentHumidity = humi --DHT_11(humi1)
-- if data.voice == ture or data.voice ==ture then
ok,json = pcall(sjson.encode, {params=data})
MQTTClient:publish(Pubtopic, json, 0, 0, function(client)
print("Publish weather success")
end)
-- end
end
timer1:alarm(500, tmr.ALARM_AUTO, ConnectWifi)
标签:function,tmr,end,esp8266,..,温湿度,lua,print,data 来源: https://blog.csdn.net/qq_42530422/article/details/106979240