Files
RPI-GPIO-fan-temp-control-o…/fan_temp_sensor.py

55 lines
1.9 KiB
Python

import glob
import time
import subprocess
# Base directory for the 1-Wire devices for the temperature sensor
base_dir = '/sys/bus/w1/devices/'
# Device folder for the specific sensor
device_folder = glob.glob(base_dir + '28-1f38831e64ff')[0]
# Path to the w1_slave file containing the actual temperature reading
device_file = device_folder + '/w1_slave'
def read_temp_raw():
"""Read the raw temperature data from the sensor."""
with open(device_file, 'r') as f:
lines = f.readlines()
return lines
def read_temp():
"""Parse the raw temperature data and return the temperature in Celsius."""
lines = read_temp_raw()
# Keep checking until the sensor says its reading is valid (ends with 'YES')
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = read_temp_raw()
# Find the temperature value in the second line 't='
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos + 2:]
# The sensor gives temp in thousandths of a degree, so divide by 1000
temp_c = float(temp_string) / 1000.0
return temp_c
def execute_command(command):
"""Execute a shell command."""
subprocess.run(command, shell=True)
# Main loop to read and print the temperature
if __name__ == "__main__":
# Set up pin 18 to control the fan relay
execute_command('pinctrl set 18 op')
while True:
# Get the current temperature
temp_c = read_temp()
print(f"Temperature: {temp_c:.2f} °C")
# Turn fan ON if temperature is 46°C or higher by setting pin to low
if temp_c >= 46:
execute_command('pinctrl set 18 dl')
# Turn fan OFF if temperature drops to 40°C or lower by setting pin to high
elif temp_c <= 40:
execute_command('pinctrl set 18 dh')
# Wait 1 second before checking temperature again
time.sleep(1)