Android 控制pwm风扇

准备

  • 正点原子atoxxx主板。
  • Android12系统

软件定义

设备树定义

fan0: pwm-fan {
		compatible = "pwm-fan";
		cooling-min-state = <0>;
		cooling-max-state = <22>;
		#cooling-cells = <2>;
		pwms = <&pwm0 0 25000 0>;
		cooling-levels = <
			0 50 100 120 150 170 180 200
			205 210 215 220 225 230 235 240
			245 250 251 252 253 254 255
		>;
		status = "okay";
};

通过 sysfs 操作冷却状态

首先,我们找到风扇的控制指令。pwm-fan驱动会被注册为 Linux thermal 子系统的 “冷却设备”,通过 sysfs 文件暴露控制接口。步骤如下:

  1. 找到风扇对应的冷却设备

风扇作为冷却设备会被挂载到/sys/class/thermal/cooling_deviceX/(X 为数字,如cooling_device3)。通过以下命令确认:

# 确认有几个设备
rk3568_s_atompi_ca1:/ # ls /sys/class/thermal/cooling_de* -l
lrwxrwxrwx 1 root root 0 2025-10-19 20:24 /sys/class/thermal/cooling_device0 -> ../../devices/virtual/thermal/cooling_device0
lrwxrwxrwx 1 root root 0 2025-10-19 20:24 /sys/class/thermal/cooling_device1 -> ../../devices/virtual/thermal/cooling_device1
lrwxrwxrwx 1 root root 0 2025-10-19 20:24 /sys/class/thermal/cooling_device2 -> ../../devices/virtual/thermal/cooling_device2
# 分别确认每一个设备的类型名称
rk3568_s_atompi_ca1:/ # cat /sys/class/thermal/cooling_device0/type
pwm-fan
rk3568_s_atompi_ca1:/ # cat /sys/class/thermal/cooling_device1/type
thermal-cpufreq-0
rk3568_s_atompi_ca1:/ # cat /sys/class/thermal/cooling_device2/type
thermal-devfreq-0

其中cooling_device0就是我们要的设备,

  1. 确认设备状态范围

此处在设备树上已经知道了,也可以在 sysfs 文件中查看

# 最小状态(应输出0)
cat /sys/class/thermal/cooling_device0/min_state
# 最大状态(应输出22)
cat /sys/class/thermal/cooling_device0/max_state
# 当前状态(初始可能为0)
cat /sys/class/thermal/cooling_device0/cur_state
  1. 控制 PWM 占空比(通过设置冷却状态)

cooling-levels数组中,状态 N 对应索引 N 的数值(即占空比)。例如:

状态 0 → 占空比 0(停止)
状态 1 → 占空比 50
状态 22 → 占空比 255(全速)

通过写入cur_state文件设置状态,即可控制占空比:

# 示例:设置状态5(对应cooling-levels中第5个值170)
echo 5 > /sys/class/thermal/cooling_device0/cur_state
# 验证:读取当前状态
cat /sys/class/thermal/cooling_device0/cur_state  # 应输出5
posted @ 2025-12-20 17:54  moqi_smile  阅读(0)  评论(0)    收藏  举报