From 5e4bf4a8f9483e69dc653624e8a47a5d2e708155 Mon Sep 17 00:00:00 2001 From: Jayatilaka Date: Sun, 16 Nov 2025 17:14:25 +0100 Subject: [PATCH] revised comments to be more comprehensive --- fan_temp_sensor.py | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/fan_temp_sensor.py b/fan_temp_sensor.py index 136b96e..fd75119 100644 --- a/fan_temp_sensor.py +++ b/fan_temp_sensor.py @@ -2,11 +2,11 @@ import glob import time import subprocess -# Base directory for the 1-Wire devices +# Base directory for the 1-Wire devices for the temperature sensor base_dir = '/sys/bus/w1/devices/' -# Device folder for your specific sensor +# Device folder for the specific sensor device_folder = glob.glob(base_dir + '28-1f38831e64ff')[0] -# Path to the w1_slave file +# Path to the w1_slave file containing the actual temperature reading device_file = device_folder + '/w1_slave' def read_temp_raw(): @@ -18,14 +18,15 @@ def read_temp_raw(): def read_temp(): """Parse the raw temperature data and return the temperature in Celsius.""" lines = read_temp_raw() - # Wait until the sensor output is valid + # 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 + # 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 @@ -35,14 +36,19 @@ def execute_command(command): # Main loop to read and print the temperature if __name__ == "__main__": - execute_command('pinctrl set 18 op') # First, set it as output + # 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)