这篇文章将为大家详细讲解有关怎么用树莓派搭建传感器物联网应用,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
1. 挂载DS18B20
sudo modprobe w1-gpio sudo modprobe w1-therm
2. 安装Python的库单总线温度计访问库: w1thermsensor
pip install w1thermsensor
3. 新建一个iot.py文件敲入以下代码
#!/usr/bin/env python
#coding=utf8
import httplib, urllib
from w1thermsensor import W1ThermSensor
import time
import socket, serial, time
import httplib
import json
HOST = "open.lewei50.com"
PORT = 80
user_key = '乐为物联的userkey'
def send_data_to_yeelink(temp):
httpClient = None
try:
params = json.dumps({'value': temp})
headers = {"Content-type": "application/json"
, "Accept": "text/plain",'U-ApiKey': 'Yeelink的api key'}
print params
httpClient = httplib.HTTPConnection('api.yeelink.net', 80, timeout=30)
httpClient.request("POST", "/v1.1/device/设备id/sensor/传感器id/datapoints", params, headers)
response = httpClient.getresponse()
print response.status
print response.reason
print response.read()
print response.getheaders() #获取头信息
except Exception, e:
print e
finally:
if httpClient:
httpClient.close()
def send_data(temp):
httpClient = None
try:
params = json.dumps([{'Name': '传感器名称', 'Value': temp}])
headers = {"Content-type": "application/x-www-form-urlencoded"
, "Accept": "text/plain","userkey":user_key}
print params
httpClient = httplib.HTTPConnection(HOST, 80, timeout=30)
httpClient.request("POST", "/api/V1/Gateway/UpdateSensors/01", params, headers)
response = httpClient.getresponse()
print response.status
print response.reason
print response.read()
print response.getheaders() #获取头信息
except Exception, e:
print e
finally:
if httpClient:
httpClient.close()
while True:
for sensor in W1ThermSensor.get_available_sensors([W1ThermSensor.THERM_SENSOR_DS18B20]):
temp=sensor.get_temperature()
print("Sensor %s has temperature %.2f" % (sensor.id,temp ))
send_data(temp)
send_data_to_yeelink(temp)
time.sleep(120)
4. 运行python脚本
python iot.py
5. 如果温度读取成功且上传成功会打印相关消息.
关于“怎么用树莓派搭建传感器物联网应用”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/betayuan/blog/775674