
I replaced the fan with a Noctua fan to get better airflow and quality. But if the fan does not even spin, it makes no difference. For the fan to work, a PWM signal must be sent out on GPIO13 (pin 33) on the Raspberry Pi 4.

OK, good documentation and good with finished code as well.
But…
I installed Home Assistant OS and I do not know how to run a python script in Home Assistant.
This script should be running all the time, so the best solution might be to have it as an add-on. But I feel that it’s a bit over my head, for now 🙂 Instead, it will be Google again that gets the question “Home Assistant fan regulating with raspberry pi PWM pin” and I find this page. Somewhere I also found this page which was the basis for me being able to figure out how to measure the CPU temperature.
The result was the following code in configuration.yaml:
sensor:
- platform: command_line
name: CPU Temperature
command: "cat /sys/class/thermal/thermal_zone0/temp"
# If errors occur, make sure configuration file is encoded as UTF-8
unit_of_measurement: "°C"
value_template: "{{ value | multiply(0.001) | round(1) }}"
switch:
- platform: rpi_gpio
ports:
13: RPI Cooling Fan # PWM fan control
climate:
- platform: generic_thermostat
name: RPI Cooling Fan Controller
heater: switch.rpi_cooling_fan
target_sensor: sensor.cpu_temperature
min_temp: 0
max_temp: 85
ac_mode: true
target_temp: 45
cold_tolerance: 0.1
hot_tolerance: 0.1
min_cycle_duration:
seconds: 30
keep_alive:
minutes: 5
initial_hvac_mode: "cool"
The sensor part is a command line readout from the system to be able to get the current temperature on the CPU.
The switch part is specific to the Raspberry Pi in being able to set the GPIO pins to the desired values.
Climate creates a virtual thermostat that takes in the temperature and sets GPIO 13 (switch) ON if the temperature becomes too high, i.e. above “target_temp”. This solution actually works really well. But…
The fan only has ON (max speed) and OFF (off), which makes it sound quite a lot from the chassis when the fan starts. I want it to start at a lower speed and then increase if the temperature increases. But it is not possible with switch, only ON and OFF. But it is easy to change target_temp with a climate control in the Lovelace panel.

To be continued…