工具
树莓派3 modelB 一个
dht11温湿度传感器一个
onenet平台
安装好requests库的python(一定要安装好不然代码不能正确运行,可以参考我的另一篇博文点击打开链接)
树莓派连接温度传感器
将树莓派连接好温度传感器,并且得到数据,首先要运行代码,将传感器测得的温湿度数据分别用两个文件夹保存起来,代码一共分为两部分,一部分是测得传感器数据并将数据显示出来,第二部分是将数据以一定的格式储存起来,为后面上传做准备,废话不说直接上代码,博主比较懒,代码没什么注释,请见谅
- #!/usr/bin/python
- 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('/home/pi/pi/test/dht11/tmp_data.txt', 'w')
- hud_output = open('/home/pi/pi/test/dht11/hum_data.txt', 'w')
- tmp_output.write(mytemp)
- hud_output.write(myhumi)
- tmp_output.close
- hud_output.close
- GPIO.cleanup()
#!/usr/bin/python
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('/home/pi/pi/test/dht11/tmp_data.txt', 'w')
hud_output = open('/home/pi/pi/test/dht11/hum_data.txt', 'w') tmp_output.write(mytemp)
hud_output.write(myhumi) tmp_output.close
hud_output.close
GPIO.cleanup()
运行代码后会出现两个文件分别来保存温度和湿度,如下图:
这样一来温湿度的数据就保存下来了,然后就是读取并上传了
上传数据至云端
上传之前,首先要将云物联网平台,现在的免费的云物联网平台有很多onenet、机智云、ubidots、yeelink,我选择的是onenet平台。首先你要注册好onenet平台账号,然后建立一个产品,如图所示
创建好之后有两个东西比较重要,一个是你的APIKey,还有一个是你的设备ID,设备ID可以在你的设备管理中看见,如图:
有了这两个东西后你还可以创建你的应用,这个应用可以接收到上传的数据并进行处理,使得数据更加直观,在你的应用管理里面可以创建,创建好的应用如图:
通过代码上传数据
上传温度数据代码
- <span style="font-size: 18px;">import urllib2
- import json
- import time
- import datetime
- APIKEY = '你的APIKey'
- def http_put():
- file = open("/home/pi/pi/test/dht11/tmp_data.txt")
- temperature= float(file.read())
- CurTime = datetime.datetime.now()
- url='http://api.heclouds.com/devices/你的设备ID/datapoints'
- values={'datastreams':[{"id":"temp","datapoints":[{"at":CurTime.isoformat(),"value":temperature}]}]}
- print "the time is: %s" %CurTime.isoformat()
- print "The upload temperature value is: %.3f" %temperature
- 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()
- while True:
- time.sleep(5)
- resp = http_put()
- print "OneNET result:\n %s" %resp
- time.sleep(5)</span>
import urllib2
import json
import time
import datetime APIKEY = '你的APIKey' def http_put():
file = open("/home/pi/pi/test/dht11/tmp_data.txt")
temperature= float(file.read())
CurTime = datetime.datetime.now()
url='http://api.heclouds.com/devices/你的设备ID/datapoints'
values={'datastreams':[{"id":"temp","datapoints":[{"at":CurTime.isoformat(),"value":temperature}]}]} print "the time is: %s" %CurTime.isoformat()
print "The upload temperature value is: %.3f" %temperature 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() while True:
time.sleep(5)
resp = http_put()
print "OneNET result:\n %s" %resp
time.sleep(5)
上传湿度数据代码:
- import urllib2
- import json
- import time
- import datetime
- APIKEY = '你的APIKey'
- def http_put():
- file = open("/home/pi/pi/test/dht11/hum_data.txt")
- humidity= float(file.read())
- CurTime = datetime.datetime.now()
- url='http://api.heclouds.com/devices/11302038/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.closes
import urllib2
import json
import time
import datetime APIKEY = '你的APIKey' def http_put():
file = open("/home/pi/pi/test/dht11/hum_data.txt")
humidity= float(file.read())
CurTime = datetime.datetime.now()
url='http://api.heclouds.com/devices/11302038/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.closes
数据流问题
上传之后我们一定要注意的是数据流的问题,就是我们有两种数据,一种是humidity,一种是temperature,你在编辑应用的时候就要注意数据流的选择如图
这个选择之前要在数据流管理那里创建温度和湿度数据流,你的代码的相应的数据那里也要改成和数据流名称一样的,湿度数据流t同理,一定要保证名字一样,不然就不会自动识别了,如图:
自动执行代码并上传数据
要实现代码的自动上传和运行,需要用到crontab命令,打开树莓派命令行界面输入:
- sudo crontab -e
sudo crontab -e
选择nano,也就是2,然后在最后几行添加这么几句话
- */1 * * * * python /home/pi/pi/test/dht11/transfer_tmp.py
- */1 * * * * python /home/pi/pi/test/dht11/transfer_hum.py
- */1 * * * * python /home/pi/pi/test/dht11/cpdht11.py
*/1 * * * * python /home/pi/pi/test/dht11/transfer_tmp.py
*/1 * * * * python /home/pi/pi/test/dht11/transfer_hum.py
*/1 * * * * python /home/pi/pi/test/dht11/cpdht11.py
如图:
添加之后保存,然后代码就能每隔一分钟运行一次,实现了自动上传功能,最后注意的的是在创建产品的过程中,传输协议一定要选HTTP协议,连接是移动蜂窝网,还有就是一定要安装好requests库模块,APIKey 和设备ID一定要准确。