使用Raspberry PI2讀取DS18B20溫度感測器傳回來的溫度資料
使用零件
電路接線圖如下
使用putty連線到PI系統,編輯檔案
nano /boot/config.txt
在檔案最後加入一行指令
dtoverlay=w1-gpio |
存檔後重新啟動
reboot
載入模組
modprobe w1-gpio
modprobe w1-therm
(執行完畢,畫面上沒有什麼訊息)
接著切換路徑,查看檔案
cd /sys/bus/w1/devices
ls
螢幕顯示兩個子目錄,其中一個有一堆數字的目錄,我們要切換進去
cd 28-000006b3ed1b
ls
會看到有一個 w1_slave檔案
接著展開 w1_slave檔案內容
第一行顯示 YES,第二行顯示 t=27687 除以1000等於27.687就是攝氏溫度
目前為止,可以確認材料、電路接線都沒有問題。
接下來要寫一個測試程式 thermometer_sensor.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
執行程式
sudo python thermometer_sensor.py
每秒不斷重覆顯示攝氏、華氏溫度。
沒有留言:
張貼留言