1、ds18b20管脚
1-3管脚依次为GND DQ VCC,DQ接树莓派的GPIO4
2、编写脚本
cd /home/pi/ds18b.py
-
# -*- coding:utf-8 -*-
-
#没有上面一行代码就不能使用中文注释,否则就会报错
-
import RPi.GPIO as GPIO
-
import time
-
import requests
-
import json
-
#从DS18B20读取温度值
-
def readtemperature():
-
file=open("/sys/bus/w1/devices/28-0000024a8c0b/w1_slave")
-
#read temprature
-
text=file.read()
-
#close file
-
file.close()
-
secondline = text.split("\n")[1]
-
temperaturedata = secondline.split(" ")[9]
-
temperature = float(temperaturedata[2:])
-
temperature = temperature / 1000
-
return temperature
-
#将温度值上传到yeelink
-
try:
-
while True:
-
# 设备URI
-
apiurl = 'http://api.yeelink.net/v1.1/device/16485/sensor/28543/datapoints'
-
# 用户密码, 指定上传编码为JSON格式
-
apiheaders = {'U-ApiKey': '9908e3876669432610e9a3ac2fb0xxxx', 'content-type': 'application/json'}
-
#获ds18b20 温度
-
temp=readtemperature()
-
print 'ds18b20 temperature is %0.1f c' %temp
-
payload = {'value': temp}
-
#发送请求,10s的频率
-
r = requests.post(apiurl, headers=apiheaders, data=json.dumps(payload))
-
time.sleep(10)
-
except KeyboardInterrupt:
-
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的序列号
阅读(6744) | 评论(0) | 转发(0) |