用树莓派搭建简单的传感器物联网应用
博客专区 > BetaYuan 的博客 > 博客详情
用树莓派搭建简单的传感器物联网应用
BetaYuan 发表于1年前
用树莓派搭建简单的传感器物联网应用
  • 发表于 1年前
  • 阅读 122
  • 收藏 2
  • 点赞 0
  • 评论 0

标题:腾讯云 新注册用户域名抢购1元起>>>   

这里选取DS18B20作为温度传感器,该传感器使用单总线连接至树莓派。本例将采集到的温度数据同时上传乐为物联Yeelink两个IoT云端平台.

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. 如果温度读取成功且上传成功会打印相关消息.

标签: 物联网 IoT 树莓派
共有 人打赏支持
粉丝 0
博文 44
码字总数 5150
×
BetaYuan
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: