2016年4月16日 星期六

Raspberry PI 讀取 DS18B20溫度感測器資料

 

使用Raspberry PI2讀取DS18B20溫度感測器傳回來的溫度資料

image

使用零件

PI2控制板
電阻 4.7K
DS18B20 (接腳說明如下)
clip_image002

電路接線圖如下

image

使用putty連線到PI系統,編輯檔案

nano /boot/config.txt

在檔案最後加入一行指令

   dtoverlay=w1-gpio

存檔後重新啟動
reboot

載入模組
modprobe w1-gpio
modprobe w1-therm
clip_image002[7]
(執行完畢,畫面上沒有什麼訊息)

接著切換路徑,查看檔案
cd /sys/bus/w1/devices
ls
clip_image002[9]

螢幕顯示兩個子目錄,其中一個有一堆數字的目錄,我們要切換進去
cd 28-000006b3ed1b
ls
clip_image004

會看到有一個 w1_slave檔案
接著展開 w1_slave檔案內容
clip_image006

第一行顯示 YES,第二行顯示 t=27687 除以1000等於27.687就是攝氏溫度
目前為止,可以確認材料、電路接線都沒有問題。

接下來要寫一個測試程式 thermometer_sensor.py

import os
import glob
import time
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_file = device_folder + '/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
temp_f = temp_c * 9.0 / 5.0 + 32.0
return temp_c, temp_f
while True:
print(read_temp())
time.sleep(1)
view raw gistfile1.txt hosted with ❤ by GitHub
不斷的讀取溫度值。

執行程式
sudo python thermometer_sensor.py
clip_image008

每秒不斷重覆顯示攝氏、華氏溫度。

沒有留言:

張貼留言