工具

树莓派3 modelB 一个
dht11温湿度传感器一个 
onenet平台
安装好requests库的python(一定要安装好不然代码不能正确运行,可以参考我的另一篇博文点击打开链接

树莓派连接温度传感器

将树莓派连接好温度传感器,并且得到数据,首先要运行代码,将传感器测得的温湿度数据分别用两个文件夹保存起来,代码一共分为两部分,一部分是测得传感器数据并将数据显示出来,第二部分是将数据以一定的格式储存起来,为后面上传做准备,废话不说直接上代码,博主比较懒,代码没什么注释,请见谅
  1. #!/usr/bin/python
  2. import RPi.GPIO as GPIO
  3. import time
  4. channel =4
  5. data = []
  6. j = 0
  7. GPIO.setmode(GPIO.BCM)
  8. time.sleep(1)
  9. GPIO.setup(channel, GPIO.OUT)
  10. GPIO.output(channel, GPIO.LOW)
  11. time.sleep(0.02)
  12. GPIO.output(channel, GPIO.HIGH)
  13. GPIO.setup(channel, GPIO.IN)
  14. while GPIO.input(channel) == GPIO.LOW:
  15. continue
  16. while GPIO.input(channel) == GPIO.HIGH:
  17. continue
  18. while j < 40:
  19. k = 0
  20. while GPIO.input(channel) == GPIO.LOW:
  21. continue
  22. while GPIO.input(channel) == GPIO.HIGH:
  23. k += 1
  24. if k > 100:
  25. break
  26. if k < 8:
  27. data.append(0)
  28. else:
  29. data.append(1)
  30. j += 1
  31. print "sensor is working."
  32. print data
  33. humidity_bit = data[0:8]
  34. humidity_point_bit = data[8:16]
  35. temperature_bit = data[16:24]
  36. temperature_point_bit = data[24:32]
  37. check_bit = data[32:40]
  38. humidity = 0
  39. humidity_point = 0
  40. temperature = 0
  41. temperature_point = 0
  42. check = 0
  43. for i in range(8):
  44. humidity += humidity_bit[i] * 2 ** (7-i)
  45. humidity_point += humidity_point_bit[i] * 2 ** (7-i)
  46. temperature += temperature_bit[i] * 2 ** (7-i)
  47. temperature_point += temperature_point_bit[i] * 2 ** (7-i)
  48. check += check_bit[i] * 2 ** (7-i)
  49. tmp = humidity + humidity_point + temperature + temperature_point
  50. if check == tmp:
  51. print "temperature :", temperature, "*C, humidity :", humidity, "%"
  52. else:
  53. print "wrong"
  54. print "temperature :", temperature, "*C, humidity :", humidity, "% check :", check, ", tmp :", tmp
  55. #从这里开始是第二部分
  56. mytemp = '%f' %temperature
  57. myhumi = '%f' %humidity
  58. tmp_output = open('/home/pi/pi/test/dht11/tmp_data.txt', 'w')
  59. hud_output = open('/home/pi/pi/test/dht11/hum_data.txt', 'w')
  60. tmp_output.write(mytemp)
  61. hud_output.write(myhumi)
  62. tmp_output.close
  63. hud_output.close
  64. 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可以在你的设备管理中看见,如图:
有了这两个东西后你还可以创建你的应用,这个应用可以接收到上传的数据并进行处理,使得数据更加直观,在你的应用管理里面可以创建,创建好的应用如图:

通过代码上传数据

上传温度数据代码
  1. <span style="font-size: 18px;">import urllib2
  2. import json
  3. import time
  4. import datetime
  5. APIKEY = '你的APIKey'
  6. def http_put():
  7. file = open("/home/pi/pi/test/dht11/tmp_data.txt")
  8. temperature= float(file.read())
  9. CurTime = datetime.datetime.now()
  10. url='http://api.heclouds.com/devices/你的设备ID/datapoints'
  11. values={'datastreams':[{"id":"temp","datapoints":[{"at":CurTime.isoformat(),"value":temperature}]}]}
  12. print "the time is: %s" %CurTime.isoformat()
  13. print "The upload temperature value is: %.3f" %temperature
  14. jdata = json.dumps(values)
  15. print jdata
  16. request = urllib2.Request(url, jdata)
  17. request.add_header('api-key', APIKEY)
  18. request.get_method = lambda:'POST'
  19. request = urllib2.urlopen(request)
  20. return request.read()
  21. while True:
  22. time.sleep(5)
  23. resp = http_put()
  24. print "OneNET result:\n %s" %resp
  25. 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)

上传湿度数据代码:

  1. import urllib2
  2. import json
  3. import time
  4. import datetime
  5. APIKEY = '你的APIKey'
  6. def http_put():
  7. file = open("/home/pi/pi/test/dht11/hum_data.txt")
  8. humidity= float(file.read())
  9. CurTime = datetime.datetime.now()
  10. url='http://api.heclouds.com/devices/11302038/datapoints'
  11. values={'datastreams':[{"id":"hum","datapoints":[{"at":CurTime.isoformat(),"value":humidity}]}]}
  12. print "the time is: %s" %CurTime.isoformat()
  13. print "The upload humidity value is: %.3f" %humidity
  14. jdata = json.dumps(values)
  15. print jdata
  16. request = urllib2.Request(url, jdata)
  17. request.add_header('api-key', APIKEY)
  18. request.get_method = lambda:'POST'
  19. request = urllib2.urlopen(request)
  20. return request.read()
  21. time.sleep(5)
  22. resp = http_put()
  23. print "OneNET result:\n %s" %resp
  24. 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命令,打开树莓派命令行界面输入:
  1. sudo crontab -e
 sudo crontab -e

选择nano,也就是2,然后在最后几行添加这么几句话

  1. */1 * * * * python /home/pi/pi/test/dht11/transfer_tmp.py
  2. */1 * * * * python /home/pi/pi/test/dht11/transfer_hum.py
  3. */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一定要准确。
 

Raspberry pi connect temperature and humidity to onenet (移动云平台)的更多相关文章

  1. SITP & Raspberry Pi

    系统安装 系统选择树莓派论坛提供的下载地址 Download 我选择了其中的SSH-2017-01-11-raspbian-jessie.zip[良心推荐] 选择一个大于8G的内存卡,利用 Win32 ...

  2. (0)开始 Raspberry Pi 项目前需要知道的 10 件事

    https://www.digikey.cn/zh/articles/techzone/2017/feb/10-things-to-know-before-starting-a-raspberry-p ...

  3. RASPBERRY PI 外设学习资源

    参考: http://www.siongboon.com/projects/2013-07-08_raspberry_pi/index.html Raspberry Pi         Get st ...

  4. 常用Raspberry Pi周边传感器的使用教程

    在Raspberry Pi 的使用和开发过程中,你可能时常需要一些硬件和传感器等来支持你的开发工作,例如,加入一个超声波测距的模块来让你的Raspberry Pi具备测距功能,加入一个测温模块以实现测 ...

  5. 常用Raspberry Pi周边传感器的使用教程(转)

    转:http://bbs.xiaomi.cn/thread-7797152-1-1.html 在Raspberry Pi 的使用和开发过程中,你可能时常需要一些硬件和传感器等来支持你的开发工作,例如, ...

  6. 用Raspberry Pi搭建Azure IOT解决方案

    Raspberry Pi是一款基于Linux的单板机电脑.它由英国的树莓派基金会所开发,目的是以低价硬件及自由软件刺激在学校的基本计算机科学教育.树莓派配备一枚博通(Broadcom)出产的ARM架构 ...

  7. A new comer playing with Raspberry Pi 3B

    there are some things to do for raspberry pi 3b for the first time: 1, connect pi with monitor/KB/mo ...

  8. Raspberry Pi UART with PySerial

    参考:http://programmingadvent.blogspot.hk/2012/12/raspberry-pi-uart-with-pyserial.html Raspberry Pi UA ...

  9. Raspberry Pi Resources-Using the UART

    参考:RPi Serial Connection 本文来自:http://www.raspberry-projects.com/pi/programming-in-c/uart-serial-port ...

随机推荐

  1. CentOS下RabbitMq高可用集群环境搭建

    准备工作 1,准备两台或多台安装有rabbitmq-server服务的服务器 我这里准备了两台,分别如下: 192.168.40.130 rabbitmq01192.168.40.131 rabbit ...

  2. es6 Moduel 默认名与非默认名

    export default default 本质是将后面变量(值)赋给 default,然后以default名称输出. import 在获取default变量时,写在大括号的外面 ,可自定义名称. ...

  3. vue中如何使用mockjs摸拟接口的各种数据

    mockjs的作用 生成模拟数据 模拟 Ajax 请求,返回模拟数据 基于 HTML 模板生成模拟数据(后续更新) 帮助编写单元测试(后续更新) Vue 中使用 mock 有两种使用方式,一种是仅编写 ...

  4. [ArcGIS API for JavaScript 4.8] Sample Code-Get Started-widgets简介

    [官方文档:https://developers.arcgis.com/javascript/latest/sample-code/intro-widgets/index.html] 一.Intro ...

  5. 滑动和animate以及如何停止动画

    又是一天过去了,今天复习了slideDown.slideUp.slideToggle以及animate和stop的用法. <!DOCTYPE html> <html> < ...

  6. python 的with用途(清理资源和异常处理,同时代码精简)

    参考如下博客. https://www.cnblogs.com/DswCnblog/p/6126588.html #!/usr/bin/env python # with_example02.py c ...

  7. [Android framework学习] ViewGroup的addView函数分析

    博客首页:http://www.cnblogs.com/kezhuang/p/ Android中整个的View的组装是采用组合模式. ViewGroup就相当与树根,各种Layout就相当于枝干,各种 ...

  8. json-gson:.isJsonNull()问题-堆栈溢出

    不用管我下面的第一个答案.我读得太快了. 看起来这是一个简单的例子,文件撒谎-或者至少是被误解了.幸运的是,代码并不是那么简单,而且gson是一个开源项目. 这是 JsonObject.get(Str ...

  9. mssql 存储过程调用另一个存储过程中的结果的方法分享

    转自:http://www.maomao365.com/?p=6801 摘要: 下文将分享"一个存储过程"中如何调用"另一个存储过程的返回结果",并应用到自身的 ...

  10. 从0开始的Python学习002python的数据类型

    在创建变量的时候不用声明数据类型 # 创建变量 a = 10 # 打印变量值 print(a) 结果如下: 这种感觉和Java有很大的不同,感觉python很神奇,数据的类型是python自己决定的. ...