樹莓派溫控風扇

樹莓派溫控風扇

  1. 三極管方式 J13009三極管(做開關用),管腳說明,面對有文字說明的一面,從左到右:B C E,1k電容(下拉電阻,保護用),杜邦線若干 接線順序一定要正確:
  • B(基極)-下拉1K電阻-GPIO 40(可以任選其他控制口);
  • E(發射極)-GND;
  • C(集電極)-風扇黑線;
  • 風扇紅線-5V
  1. 繼電器版(JDQ)方式:
  • +5V-JDQ輸入正極
  • JDQ輸出-風扇紅線
  • GND-JDQ控制線負極-風扇黑線
  • GPIO40-JDQ控制線圈正極線

代碼:

#每2秒讀取一次CPU內部的溫度傳感器溫度並顯示CPU溫度
#超過45°C時打開風扇
#低於38°C時關閉風扇

import sys
import time
try:
	import RPi.GPIO as GPIO
except RuntimeError:
    print("Error importing RPi.GPIO!  This is probably because you need superuser privileges.  You can achieve this by using 'sudo' to run your script")
def cpu_temp():
    with open("/sys/class/thermal/thermal_zone0/temp", 'r') as f:
        return float(f.read())/1000
def main():
    channel = 40 #最右下腳針腳

    GPIO.setmode(GPIO.BOARD)   
   #GPIO.setmode(GPIO.BCM)  #建議以GPIO.BOARD模式(板載針腳),適應不同版本的樹莓派。
    GPIO.setwarnings(False)
   #close air fan first
    GPIO.setup(channel, GPIO.OUT, initial=GPIO.HIGH)
    is_close = True
    while True:
        temp = cpu_temp()
        if is_close:
            if temp > 45.0:
                print(time.ctime(), temp, 'open air fan')
                GPIO.output(channel, 1)
                is_close = False
        else:
            if temp < 38.0:
                print(time.ctime(), temp, 'close air fan')
                GPIO.output(channel, 0)
                is_close = True
        time.sleep(2.0)
        print(time.ctime(), temp)
		
if __name__ == '__main__':
    main()
	

樹莓派開機運行Python腳本方法

在 /home/pi/.config 下創建一個文件夾,名稱爲 autostart,並在該文件夾下創建一個xxx.desktop文件(文件名以.desktop結尾,前面可以自定義),文件內容如下:

[Desktop Entry] 
Name=example 
Comment=My Python Program 
Exec=python /home/pi/example.py 
Icon=/home/pi/example.png 
Terminal=false 
MultipleArgs=false 
Type=Application 
Categories=Application;Development; 
StartupNotify=true

上面的 Name、Comment、Icon 可以自定,分別表示這個啓動項目的名稱、備註以及顯示的圖標。Exec 表示調用的指令,和在終端輸入運行腳本的指令格式一致,Linux也可參考此代碼。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章