import os import glob import time import subprocess # Base directory for the 1-Wire devices base_dir = '/sys/bus/w1/devices/' # Device folder for your specific sensor device_folder = glob.glob(base_dir + '28-1f38831e64ff')[0] # Path to the w1_slave file 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() # Wait until the sensor output is valid while lines[0].strip()[-3:] != 'YES': time.sleep(0.2) lines = read_temp_raw() # Find the temperature value in the second line equals_pos = lines[1].find('t=') if equals_pos != -1: temp_string = lines[1][equals_pos + 2:] 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__": execute_command('pinctrl set 18 op') # First, set it as output while True: temp_c = read_temp() print(f"Temperature: {temp_c:.2f} °C") if temp_c >= 46: execute_command('pinctrl set 18 dl') elif temp_c <= 40: execute_command('pinctrl set 18 dh') time.sleep(1)