AI摘要
用AI修改fan_control.py脚本,使猫头鹰4cm 5V PWM风扇正常调速:温度≥46°C启动(20%起),<44°C停转(需最小运行600秒),解决原脚本仅100%才转的问题。
原装的风扇是5V,转起来有声音,买了猫头鹰4cm 5V PWM,用AI改了下fan_control.py;
用原来的fan_control.py脚本,猫头鹰风扇不会转,只有100%的时候才会转;用AI只是改了脚本;
fan_control.py 脚本代码
#!/usr/bin/env python3
"""
fan_control.py - 5V 风扇 PWM 调速控制
迟滞 + 最小运行时间,每 3 秒打印温度
- 温度 >= 46°C -> 风扇启动(20% 起步,按温度曲线调速)
- 温度 < 44°C -> 风扇停转(需满足最小运行时间)
- 44~46°C 之间保持当前状态
- 每 3 秒打印温度到 journal
"""
import time
import os
PWM_CHIP = '/sys/class/pwm/pwmchip0'
PWM_PATH = f'{PWM_CHIP}/pwm1'
PERIOD = 40000
TEMP_CURVE = [(46, 45), (50, 55), (55, 70), (60, 85), (65, 100)]
FAN_ON_TEMP = 46
FAN_OFF_TEMP = 44
MIN_RUN_SECONDS = 600
def setup_pwm():
if os.path.exists(PWM_PATH):
try:
with open(f'{PWM_CHIP}/unexport', 'w') as f:
f.write('1')
time.sleep(0.1)
except Exception as e:
print(f'unexport warn: {e}')
try:
with open(f'{PWM_CHIP}/export', 'w') as f:
f.write('1')
time.sleep(0.3)
except Exception as e:
print(f'export err: {e}')
return False
for _ in range(20):
if os.path.exists(f'{PWM_PATH}/period'):
break
time.sleep(0.1)
if not os.path.exists(f'{PWM_PATH}/period'):
print('PWM init failed')
return False
try:
with open(f'{PWM_PATH}/period', 'w') as f:
f.write(str(PERIOD))
with open(f'{PWM_PATH}/enable', 'w') as f:
f.write('1')
return True
except Exception as e:
print(f'PWM cfg err: {e}')
return False
def get_temp():
try:
with open('/sys/class/thermal/thermal_zone0/temp') as f:
return float(f.read().strip()) / 1000.0
except:
return 50
def set_duty(pct):
try:
with open(f'{PWM_PATH}/duty_cycle', 'w') as f:
f.write(str(int(PERIOD * pct / 100)))
except Exception as e:
print(f'duty err: {e}')
if not setup_pwm():
time.sleep(3)
if not setup_pwm():
print('FATAL: PWM init failed')
import sys; sys.exit(1)
fan_on = False
fan_start_time = 0
cur_duty = -1
print('fan-control started 5V PWM on>=46C off<44C min_run=600s')
while True:
t = get_temp()
if not fan_on and t >= FAN_ON_TEMP:
fan_on = True
fan_start_time = time.time()
print(f'{t:.1f}C -> Fan ON (started, min run {MIN_RUN_SECONDS}s)')
elif fan_on and t < FAN_OFF_TEMP:
elapsed = time.time() - fan_start_time
if elapsed >= MIN_RUN_SECONDS:
fan_on = False
print(f'{t:.1f}C -> Fan OFF (ran {elapsed:.0f}s)')
if fan_on:
d = 45
for tt, dd in TEMP_CURVE:
if t >= tt:
d = dd
else:
d = 0
if d != cur_duty:
set_duty(d)
cur_duty = d
print(f'{t:.1f}C -> Fan {d}% [{"ON" if fan_on else "OFF"}]')
state = 'ON' if fan_on else 'OFF'
elapsed = time.time() - fan_start_time if fan_on else 0
print(f'{t:.1f}C Fan={state}' + (f' run={elapsed:.0f}s' if fan_on else ''))
time.sleep(3)
暂无评论
要发表评论,您必须先 登录