nodeMCU-esp8266 lua---DHT11采集温湿度上报阿里云

引脚接的是PD5

wifitab={}
wifitab.ssid = "WIFI"
wifitab.pwd = "WIFIPassword"
wifi.setmode(wifi.STATION)
wifi.sta.config(wifitab)
wifi.sta.connect()

timer1 = tmr.create()
timer2 = tmr.create()


ProductKey = "a1BDink4Et"
DeviceName = "demo_voice"
DeviceSecret = "KaFwa5x4AjHdsFQ2HFluIjOZkUg0ZE"
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)



  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值