树梅派学习 20. 温度传感器实验

版权声明:(谢厂节的博客)博主文章绝大部分非原创,转载望留链接。 https://blog.csdn.net/xundh/article/details/82120205

温度传感器原理图

这里写图片描述

接线图

这里写图片描述

设置

vi /boot/config.txt

添加:

dtoverlay=w1-gpio
sudo reboot
sudo modprobe w1-gpio
sudo modprobe w1-therm
cd /sys/bus/w1/devices/
pi@raspberrypi:/sys/bus/w1/devices $ ls
28-020b924589d4  w1_bus_master1
pi@raspberrypi:/sys/bus/w1/devices $ cd 28-020b924589d4
pi@raspberrypi:/sys/bus/w1/devices/28-020b924589d4 $ ls
driver  id  name  power  subsystem  uevent  w1_slave
pi@raspberrypi:/sys/bus/w1/devices/28-020b924589d4 $ cat w1_slave 

c2 01 55 05 7f 7e 81 66 0d : crc=0d YES
c2 01 55 05 7f 7e 81 66 0d t=28125

这里显示的28125即 28.125摄氏度

程序代码

#!/usr/bin/env python
#----------------------------------------------------------------
#   Note:
#       ds18b20's data pin must be connected to pin7.
#       replace the 28-XXXXXXXXX as yours.
#----------------------------------------------------------------
import os

ds18b20 = '28-020b924589d4'

def setup():
    global ds18b20
    for i in os.listdir('/sys/bus/w1/devices'):
        if i != 'w1_bus_master1':
            ds18b20 = i

def read():
#   global ds18b20
    location = '/sys/bus/w1/devices/' + ds18b20 + '/w1_slave'
    tfile = open(location)
    text = tfile.read()
    tfile.close()
    secondline = text.split("\n")[1]
    temperaturedata = secondline.split(" ")[9]
    temperature = float(temperaturedata[2:])
    temperature = temperature / 1000
    return temperature

def loop():
    while True:
        if read() != None:
            print "Current temperature : %0.3f C" % read()

def destroy():
    pass

if __name__ == '__main__':
    try:
        setup()
        loop()
    except KeyboardInterrupt:
        destroy()

运行结果

pi@raspberrypi:~/study/11 $ python ds18b20.py 
Current temperature : 27.875 C
Current temperature : 27.812 C
Current temperature : 27.812 C

猜你喜欢

转载自blog.csdn.net/xundh/article/details/82120205