树莓派使用DS18B20模块测量温度

参考:
http://shumeipai.nxez.com/2013/10/03/raspberry-pi-temperature-sensor-monitors.html

第一步,允许单总线接口

sudo raspi-config
进入interfacingoptions
enable one-wire interface

第二步,接线
树莓派使用DS18B20模块测量温度_第1张图片

接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-00000xxxxxx w1_bus_master1

第四步,查看当前温度

cd 28-00000xxxxxx
cat w1_slave
显示:
46 01 4b 46 7f ff 0c 10 2f : crc=2f YES
46 01 4b 46 7f ff 0c 10 2f t=20375
第二行的t=20375就是当前的温度值,要换算成摄氏度,除以1000,即当前温度为20375/1000=20.375摄氏度。

python

#!/usr/bin/python3
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)

打印结果:

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

你可能感兴趣的:(树莓派)