温度センサーDS18B20を防水型に
温度センサーDS 18B20の防水型を購入しました。目的は、液体の温度を測定するためです。センサー部分がステンレスで覆われているので、液体に浸すのに適しているのかなと考えました。いま使っているセンサーを加工しようかとも考えたのですが、防水型のセンサーが比較的安価に販売されていたので、購入することにしました。Amazonの広告にはArduino用と記載されていますが、たぶんラズパイでも使える筈です。

見えにくいのですが、センサーはステンレスで覆われ、ケーブルは、赤:3.3V DC 黒:GND 黄色:DATA(GPIO4に接続)です。

Raspberry Pi ZERO WHにユニバーサル基板を重ねて、温度センサー用のコネクタをつけました。


2つのセンサーから読み取った温度を、指定した時間間隔ごとに表示して、CSVファイルに保存するプログラムです。
-*- coding: utf-8 -*-
import os
import glob
import time
import datetime
import subprocess
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
base_dir = '/sys/bus/w1/devices/'
#device_folder = glob.glob(base_dir + '28*')[0]
device_folder = glob.glob(base_dir + '28*') #センサーが正しく接続されるとできるフォルダの名称をすべて取得(リスト)
ch_length = len(device_folder) #接続されている温度センサーの数を取得
temp= [0.00]*ch_length #
def read_temp_raw(ch):
device_file = device_folder[ch] + '/w1_slave'
catdata = subprocess.Popen(['cat',device_file], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out,err = catdata.communicate()
out_decode = out.decode('utf-8')
lines = out_decode.split('\n')
return lines
def read_temp(ch):
lines = read_temp_raw(ch)
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = read_temp_raw(ch)
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
def file_save(time_str,temp):
dir_path = '/home/pi/DS18B20_data'
today = datetime.datetime.now()
data_str=""
for ch in range(ch_length):
data_str = data_str + "," + "{:.3f}".format(temp[ch])
data_str = data_str + "\n"
filename = today.strftime('%Y%m%d')
if not os.path.exists('/home/pi/DS18B20_data'):
os.makedirs('/home/pi/DS18B20_data')
f = open('/home/pi/DS18B20_data/'+filename+'.csv','a')
f.write(time_str + data_str)
f.close()
try:
time_span = input("測定間隔を秒単位で入力してください(3秒以上の整数値):")
while True:
for ch in range(ch_length):
temp[ch] = read_temp(ch)
time_str = datetime.datetime.today().strftime("%Y/%m/%d %H:%M:%S")
print('日付時刻:{0:} センサー0: {1:.3f}℃ センサー1: {2:.3f}℃'.format(time_str,temp[0],temp[1]))
file_save(time_str,temp)
time.sleep(int(time_span)-2)
except KeyboardInterrupt:
pass
実行画面です。5秒ごとに表示しています。これを使って、ちょっと実験したいと考えています。



