How to automatically control the Raspberry Pi fan with Home Assistant
Sponsored by
unolia.comAll your domains in one place. Helps you find problems, gives you performance and security insights!
Want to sponsor this blog ?
Contact me or use
Github sponsor
I've set up a Raspberry Pi 4 with Home Assistant in my van. To manage its cooling, I want to programmatically control the fan through Home Assistant, triggering it only when the CPU temperature exceeds a specific threshold.
Hardware Setup
I used a 5V fan connected to the Raspberry Pi's GPIO pins.
The little fan has three cables:
- Red: Power (5V)
- Black: Ground (GND)
- Blue: Control signal
I connected the blue cable to GPIO 14, which is not a PWM-capable pin on the Raspberry Pi, but it works fine for simple on/off control.
Software Requirements
To control the GPIOs from Home Assistant, you need to install the following component in this order:
- HACS - the Home Assistant Community Store
- HA RPi GPIO - a plugin to control the GPIO pins of the Raspberry Pi
I let you read the documentation of these components to install them correctly.
Once you installed HACS, you can install the RPi GPIO plugin from the HACS dashboard on your Home Assistant instance.
Configuration
In your configuration.yaml
file, add the following lines to configure the GPIO pin for the fan:
switch: - platform: rpi_gpio switches: - port: 14 name: "RPI Cooling Fan" unique_id: "rpi_cooling_fan" climate: - platform: generic_thermostat name: RPI Cooling Fan Controller unique_id: rpi_cooling_fan_controller heater: switch.rpi_cooling_fan target_sensor: sensor.system_monitor_processor_temperature min_temp: 45 max_temp: 80 ac_mode: true target_temp: 55 cold_tolerance: 0.5 hot_tolerance: 0.5 min_cycle_duration: seconds: 60 # Minimum time the fan should run before turning off keep_alive: minutes: 5 initial_hvac_mode: "cool"
This configuration does the following:
- Defines a switch for the fan connected to GPIO 14.
- Sets up a generic thermostat that uses the fan as a heater.
- Monitors the CPU temperature using the
sensor.system_monitor_processor_temperature
sensor. - Sets the target temperature to 55°C, with a minimum and maximum temperature range of 45°C and 80°C, respectively.
- Configures the thermostat to run the fan for at least 60 seconds before turning it off, and keeps it alive for 5 minutes after the last activation.
Result
Syntax highlighting provided by torchlight.dev