工具

树莓派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. 【20190405】JavaScript-正则式匹配与替换结果解析

    在正则式的应用中有三个函数使用得最多:exec().test()与字符串的replace(reg, options).其中test()最简单,只要字符串与正则式可以匹配,就返回true,否则返回fal ...

  2. angular路由为空重定向到指定路由

    { path: '', redirectTo: 'home', pathMatch: 'full' }

  3. 键盘上的"整蛊专家",如何防止短信轰炸机

    "短信轰炸机",是别人通过爬虫或者其他抓取手段在网路上收集那些公司平台短信业务接口的一个集成程序,可能只需要输入一个手机号,对方一整天都会收到各大平台的注册或提醒短信,就是手机在那 ...

  4. 从零学习Fluter(三):Flutter的路由跳转以及state的生命周期

    今天继续研究Flutter,我是在flutter1.0发布后,才玩flutter的,发现在此之前,许多人已经先发制人,玩起了flutter,不知不觉中,我已经被别人摔在了起跑线上,玩过flutter后 ...

  5. Android BroadcastReceiver 接收收到短信的广播

    一.知识介绍 1.broadcastReceiver是广播接受者,四大组件之一. 2.Android中内置了很多系统级别的广播,可以在应用程序中得到各种系统的状态信息. 3.使用场景: ①当手机没有电 ...

  6. Cs231n课堂内容记录-Lecture 8 深度学习框架

    Lecture 8  Deep Learning Software 课堂笔记参见:https://blog.csdn.net/u012554092/article/details/78159316 今 ...

  7. python网络进阶篇

    并发编程 进程 操作系统的历史 # 手工操作 —— 穿孔卡片 # 程序员将对应于程序和数据的已穿孔的纸带(或卡片)装入输入机,然后启动输入机把程序和数据输入计算机内存,接着通过控制台开关启动程序针对数 ...

  8. 用微软官方的 HTML Help Workshop制作的CHM文件不显示图片解决办法

    制作CHM文档,方便小巧还易于查看,用处自不必多说了,最近想把这个季度所学习的内容全部制作成CHM格式文档,给自己后续用来温故而知新,同时也可以做为后起之秀避坑法宝.但是在生成CHM文档之后发现有些地 ...

  9. uWSGI、WSGI和uwsgi

    WSGI wsgi server (比如uWSGI) 要和 wsgi application(比如django )交互,uwsgi需要将过来的请求转给django 处理,那么uWSGI 和 djang ...

  10. 将List按照指定大小等分的几种实现方式和效率对比及优化

    今天碰到一个需求,定时任务,批量从表里取数据并做一些其他操作然后再存表,每次取1000条,由于计算过程比较耗时所以要起多个线程同时跑,需要将List按照指定大小等分,如每100条数据起一个线程,若最后 ...