pwm-fan-control.py

Xerxes Pi 2026 Carrier Board for Raspberry Pi CM4/CM5 Modules · File : pwm-fan-control.py · Language : python · Use case : Contrôler dynamiquement la vitesse du ventilateur de refroidissement via le connecteur PWM dédié de la Xerxes Pi.

Thermal control of the fan connected to the card's PWM connector for active cooling.

Uses the RPi.GPIO library to generate a PWM signal. GPIO 18 is an example; check the Xerxes Pi KiCad schematic for the exact pinout of the cooling connector. Adjust temperature thresholds according to your enclosure.

pwm-fan-control.py

#!/usr/bin/env python3
import RPi.GPIO as GPIO
import time
import os

FAN_PIN = 18  # Vérifiez le schéma pour le GPIO PWM exact

GPIO.setmode(GPIO.BCM)
GPIO.setup(FAN_PIN, GPIO.OUT)
pwm = GPIO.PWM(FAN_PIN, 100)  # 100 Hz
pwm.start(0)

def get_cpu_temp():
    temp_file = "/sys/class/thermal/thermal_zone0/temp"
    if os.path.exists(temp_file):
        with open(temp_file, "r") as f:
            return float(f.read()) / 1000.0
    return 0.0

def set_fan_speed(duty_cycle):
    pwm.ChangeDutyCycle(duty_cycle)

try:
    while True:
        temp = get_cpu_temp()
        
        # Courbe de refroidissement simple
        if temp < 40:
            speed = 0
        elif temp < 50:
            speed = 25
        elif temp < 60:
            speed = 50
        elif temp < 70:
            speed = 75
        else:
            speed = 100
            
        set_fan_speed(speed)
        print(f"Temp: {temp:.1f}°C | Fan: {speed}%")
        time.sleep(2)
        
except KeyboardInterrupt:
    pwm.stop()
    GPIO.cleanup()
    print("\nVentilateur arrêté.")

← Back to the board