美文网首页
nodemcu采样DS18B20数据通过UDP发送json数据到

nodemcu采样DS18B20数据通过UDP发送json数据到

作者: 0学习 | 来源:发表于2018-03-17 17:52 被阅读0次

    直接上源码
    你也可以使用我的服务器,连接上传数据,然后通过http浏览历史数据,我目前免费提供数据库服务器。亲们不要做坏事就行了。
    源码中有我的服务器直接使用就可以了。
    上我的网页可以查看历史数据,历史数据用开源的echarts绘图。
    点击查看 老沈物联.

    init.lua文件源码

    wifi.setmode(wifi.STATIONAP)
    
     station_cfg={}
    station_cfg.ssid="自己的ap"
    station_cfg.pwd="自己的密码"
    wifi.sta.config(station_cfg)
    tmr.alarm(1, 2000, tmr.ALARM_AUTO, function()
        if wifi.sta.getip() == nil then
            print('Waiting for IP ...')
    
        else
            print('IP is ' .. wifi.sta.getip())
            espmac=wifi.sta.getmac()
            espchipid=node.chipid()
            net.dns.resolve("www.5iot.top", function(sk, ip)
             if (ip == nil) then print("DNS fail!") else 
                serverip=ip
                print(ip) end
             end)
            print(espmac)
            print(espchipid)
            tmr.stop(1)
            dofile("senddata.lua")
        end
    end)
    

    senddata.lua文件源码
    其实这最基础的,但是路已经通了,各位可以实现其他的数据上传,比如:PM2.5的数据上传,甲醛数据的上传,家里电压的数据,家里用电功率的数据,只需要稍加修改即可。

    local ow_pin = 3  --ds18接到D3
    ds18b20.setup(ow_pin) --设置DS18
    local testjson={}
    
    udpSocket = net.createUDPSocket()
    tmr.alarm(0, 5000, tmr.ALARM_AUTO, function() --每5秒发送一次数据
        ds18b20.read(
        function(ind,rom,res,temp,tdec,par)
           tempre=string.format("%0.2f",temp)--获取浮点两位温度
    --print(tempre)
        end,{});
        if tempre~=nil then
        testjson={name="wendu",value=tempre,mac=espmac,chipid=espchipid} --数组定义:温度,value,本机mac,chipid
    
    local ok, json = pcall(sjson.encode,testjson) --json编码
    if ok then
    print(json)
    else
      print("failed to encode!")
    end
    udpSocket:send(10000,serverip,json) --发送到服务器
    print("The data already send to: "..serverip)
    --print(json)
    end
    end
    )
    udpSocket:listen(10000)
    udpSocket:on("receive", function(s, data, serverport, serverip)
    print(data)
    print(string.format("The server is: %s:%d",serverip, serverport)) --接收到服务器返回数据并打印
    end)
    

    相关文章

      网友评论

          本文标题:nodemcu采样DS18B20数据通过UDP发送json数据到

          本文链接:https://www.haomeiwen.com/subject/qobjqftx.html