树莓派3 B、dht11温湿度传感器、onenet平台
1、进入官网,点击开发者中心
2、添加产品
3、点击上一步创建的产品,进入界面如下,记录Mastr-APIkey(后面会用到)
4、添加设备,记录设备ID(后面会用到)
5、添加数据流模板
6、添加应用
1、工程文件
2、读取DHT11数据
#! /usr/bin/python3
# coding: utf-8
'''
+ 连 1
out 连 7
- 连 GND ,9
'''
import RPi.GPIO as GPIO
import time
channel =4
data = []
j = 0
GPIO.setmode(GPIO.BCM)
time.sleep(1)
GPIO.setup(channel, GPIO.OUT)
GPIO.output(channel, GPIO.LOW)
time.sleep(0.02)
GPIO.output(channel, GPIO.HIGH)
GPIO.setup(channel, GPIO.IN)
while GPIO.input(channel) == GPIO.LOW:
continue
while GPIO.input(channel) == GPIO.HIGH:
continue
while j < 40:
k = 0
while GPIO.input(channel) == GPIO.LOW:
continue
while GPIO.input(channel) == GPIO.HIGH:
k += 1
if k > 100:
break
if k < 8:
data.append(0)
else:
data.append(1)
j += 1
print "sensor is working."
print data
humidity_bit = data[0:8]
humidity_point_bit = data[8:16]
temperature_bit = data[16:24]
temperature_point_bit = data[24:32]
check_bit = data[32:40]
humidity = 0
humidity_point = 0
temperature = 0
temperature_point = 0
check = 0
for i in range(8):
humidity += humidity_bit[i] * 2 ** (7-i)
humidity_point += humidity_point_bit[i] * 2 ** (7-i)
temperature += temperature_bit[i] * 2 ** (7-i)
temperature_point += temperature_point_bit[i] * 2 ** (7-i)
check += check_bit[i] * 2 ** (7-i)
tmp = humidity + humidity_point + temperature + temperature_point
if check == tmp:
print "temperature :", temperature, "*C, humidity :", humidity, "%"
else:
print "wrong"
print "temperature :", temperature, "*C, humidity :", humidity, "% check :", check, ", tmp :", tmp
#从这里开始是第二部分
mytemp = '%f' %temperature
myhumi = '%f' %humidity
tmp_output = open('./tmp_data.txt', 'w')
hud_output = open('./hum_data.txt', 'w')
tmp_output.write(mytemp)
hud_output.write(myhumi)
tmp_output.close
hud_output.close
GPIO.cleanup()
3、上传云平台
修改成自己的APIKEY和设备ID,上传温度、湿度代码大致相同,不同的设备对应不同的设备ID
import urllib2
import json
import time
import datetime
APIKEY = 'svW1hKD4c1MM=CRb6tMZhJRy5Lf='
def http_put():
file = open("/home/pi/Desktop/chuanganqi/hum_data.txt")
humidity= float(file.read())
CurTime = datetime.datetime.now()
url='http://api.heclouds.com/devices/526113859/datapoints'
values={'datastreams':[{"id":"hum","datapoints":[{"at":CurTime.isoformat(),"value":humidity}]}]}
print "the time is: %s" %CurTime.isoformat()
print "The upload humidity value is: %.3f" %humidity
jdata = json.dumps(values)
print jdata
request = urllib2.Request(url, jdata)
request.add_header('api-key', APIKEY)
request.get_method = lambda:'POST'
request = urllib2.urlopen(request)
return request.read()
time.sleep(5)
resp = http_put()
print "OneNET result:\n %s" %resp
file.close
4、循环上传
新建一个shell脚本,用vim编辑内容如下
修改权限,运行即可
开始循环执行
问题咨询请联系-》群名:IT项目交流群 群号:245022761