Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1966432
  • 博文数量: 356
  • 博客积分: 8284
  • 博客等级: 中将
  • 技术积分: 4580
  • 用 户 组: 普通用户
  • 注册时间: 2009-05-15 20:25
个人简介

天行健,君子以自强不息

文章分类

全部博文(356)

文章存档

2018年(1)

2016年(4)

2015年(13)

2014年(14)

2013年(2)

2012年(25)

2011年(43)

2010年(65)

2009年(189)

分类: Python/Ruby

2014-12-18 21:16:58

1、ds18b20管脚

1-3管脚依次为GND DQ VCC,DQ接树莓派的GPIO4

2、编写脚本

cd   /home/pi/ds18b.py

  1. # -*- coding:utf-8 -*-
  2. #没有上面一行代码就不能使用中文注释,否则就会报错
  3. import RPi.GPIO as GPIO
  4. import time
  5. import requests
  6. import json
  7. #从DS18B20读取温度值
  8. def readtemperature():
  9.         file=open("/sys/bus/w1/devices/28-0000024a8c0b/w1_slave")
  10.         #read temprature
  11.         text=file.read()
  12.         #close file
  13.         file.close()
  14.         secondline = text.split("\n")[1]
  15.         temperaturedata = secondline.split(" ")[9]
  16.         temperature = float(temperaturedata[2:])
  17.         temperature = temperature / 1000
  18.         return temperature
  19. #将温度值上传到yeelink
  20. try:
  21.         while True:
  22.                 # 设备URI
  23.                 apiurl = 'http://api.yeelink.net/v1.1/device/16485/sensor/28543/datapoints'
  24.                 # 用户密码, 指定上传编码为JSON格式
  25.                 apiheaders = {'U-ApiKey': '9908e3876669432610e9a3ac2fb0xxxx', 'content-type': 'application/json'}
  26.                 #获ds18b20 温度
  27.                 temp=readtemperature()
  28.                 print 'ds18b20 temperature is %0.1f c' %temp
  29.                 payload = {'value': temp}
  30.                 #发送请求,10s的频率
  31.                 r = requests.post(apiurl, headers=apiheaders, data=json.dumps(payload))
  32.                 time.sleep(10)
  33. except KeyboardInterrupt:
  34.         GPIO.cleanup()

代码截图如下:

3、加载驱动

modprobe w1-gpio

modprobe w1-therm

4、运行脚本

python ds18b.py

效果如下:


5、yeelink效果如下:

6、因为重启后ds18b20的驱动会失效,将

modprobe w1-gpio

modprobe w1-therm

加入rc.local

nano /etc/rc.local

效果如下:


7、获取ds18b20序列号的方法

modprobe w1-gpio

modprobe w1-therm

cd  /sys/bus/w1/devices/

ls

显示出的28-xxxxxx就是ds18b20的序列号

阅读(6662) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~