2
3

More than 3 years have passed since last update.

DS18B20 で温度を読む

Last updated at Posted at 2019-12-03

Raspberry Pi に接続した温度計 (DS18B20) で温度を読む方法です。
GPIO4,GND,3.3V に接続します。
インターフェースは、one-wire です。
結線後、raspi-config で one-wire を有効にします。

確認

$ ls /sys/bus/w1/devices/
28-021317fe3eaa  w1_bus_master1
$ ls /sys/bus/w1/devices/28-021317fe3eaa
driver  hwmon  id  name  power  subsystem  uevent  w1_slave
$ cat /sys/bus/w1/devices/28-021317fe3eaa/w1_slave 
6a 01 4b 46 7f ff 0c 10 b8 : crc=b8 YES
6a 01 4b 46 7f ff 0c 10 b8 t=22625

上記の場合の温度は、22.6度です。

プログラム

get_temperature.py
! /usr/bin/python3
#
#       get_temperature.py
#
#                                               Dec/03/2019
#
#
# --------------------------------------------------------------------
import  sys
#
# --------------------------------------------------------------------
def device_read_proc(device):
        str_out = ""
        try:
                fp_in = open(device,encoding='utf-8')
                lines = fp_in.readlines()
                fp_in.close()
        except Exception as ee:
                sys.stderr.write("*** error *** file_to_str_proc ***\n")
                sys.stderr.write(str (ee))
#
        return lines
# --------------------------------------------------------------------
def get_temperature_proc():
        tstring = ""
        device = '/sys/bus/w1/devices/28-021317fe3eaa/w1_slave'
        lines = device_read_proc(device)
        for line in lines:
                pp = line.find("t=")
                if (0<= pp):
                        print(line)
                        tstring = line[pp+2:]
#
        itemp = int(tstring)
        temperature = float(itemp) / 1000.0
#
        return temperature
# --------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
temperature = get_temperature_proc()
print(temperature)
#
sys.stderr.write("*** 終了 ***\n")
# --------------------------------------------------------------------

実行結果

$ ./get_temperature.py 
*** 開始 ***
6a 01 4b 46 7f ff 0c 10 b8 t=22625

22.625
*** 終了 ***
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3