http://shumeipai.nxez.com/2013/10/03/raspberry-pi-temperature-sensor-monitors.html
第一步,允许单总线接口
sudo raspi-config
进入interfacingoptions
enable one-wire interface
第二步,接线
接BCM编码为4即图上物理引脚7
第三步,升级内核
sudo apt-get update
sudo apt-get upgrade
pi@raspberrypi :~ $ cd /sys/bus/w1/devices/
pi@raspberrypi :/sys/bus/w1/devices $ ls
28 -00000 xxxxxx w1_bus_master1
第四步,查看当前温度
cd 28 -00000 xxxxxx
cat w1_slave
显示:
46 01 4 b 46 7f ff 0 c 10 2f : crc=2f YES
46 01 4 b 46 7f ff 0 c 10 2f t=20375
第二行的t=20375 就是当前的温度值,要换算成摄氏度,除以1000 ,即当前温度为20375 /1000 =20.375 摄氏度。
Python
import os,time
device_file ='/sys/bus/w1/devices/28-031681e171ff/w1_slave'
def read_temp_raw () :
f = open(device_file,'r' )
lines = f.readlines()
f.close()
return lines
def read_temp () :
lines = read_temp_raw()
while lines[0 ].strip()[-3 :] != 'YES' :
time.sleep(0.2 )
lines = read_temp_raw()
equals_pos = lines[1 ].find('t=' )
if equals_pos != -1 :
temp_string = lines[1 ][equals_pos+2 :]
temp_c = float(temp_string)/1000.0
return temp_c
while True :
print('temp C = %f' %read_temp())
time.sleep(1 )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
打印结果:
pi@raspberrypi:~/myPython $ ./temp_ds18b20.py
temp C = 20.687000
temp C = 20.687000
temp C = 20.687000
temp C = 20.750000
temp C = 20.750000
temp C = 20.750000