Raspberry Pi Fan

Hi everyone, i am a Home Automation addict. But this topic is about a different problem. I have Hass.io on raspberry pi 3 and that sits in the kitchen because it makes so much fan noise. So i looked at Andreas Spiess’s article to install an intelligent fan which controls its speed based on cpu temperature. it works pretty well. A python script keeps on checking the temperature and controlling fan speed and i have added a bit of my own modification to have both speed and temp sent to MQTT and shown in HA.

however, i am unable to find a way to call the concerned Python script from HA. i want it called when HA restarts which may be dumb as it should be started when raspberry pi starts but HA is all i use the RPI for. and also i failed at auto loading the script on RPI start. happy to post that python script here if someone is interested. Would highly appreciate if someone can give me a clue about what i am doing wrong. i am trying the following shell command

shell_command:
  fancontrol: 'ssh "[email protected]" "python /home/pi/projects/fancontrol.py &"'

and calling it in automation as

 - action:
  - service: shell_command.fancontrol
  alias: FanControl
  condition: []
  id: '1519036529317'
  trigger:
  - event: start
    platform: homeassistant

(excuse the silly formatting but this is auto generated from the configuration portal)

a hunch i have is that maybe because the Python script calls PAHO MQTT library and the shell command when executed, cannot find that. and hecne the script is failing, but dont know how to pass in the library/module path.

This is a joke right?

Never seen a RPi with a fan before… maybe some special “heavvy duty calculations” version, but really not needed for Hassio.

I guess that depends on perspective, and ones sense of humour :). but no this was not a joke. whats so silly here in your opinion?

Isnt that the reason why we have a CPU temperature component? to monitor the server. i am just trying to do SOMETHING about the temperature if its too high.

1 Like

I have a similar script that runs on boot as system service, and reports via mqtt cpu temp.
I will add in fan control to turn on and off a fan based on temp being > xº.

check out this page it should get you started.

strictly speaking you don’t need a fan on a Pi. i think it starts throttling at at about 80 - 85º…you’d do well to reach them temps. I only installed a fan for fun (nerd alert) as a temp project, but plan to make it permanent with proper circuitry etc, not just a breadboard and jumpers.

1 Like

My RPi 3 is inside the house (average 23°C), closed inside a 30*40cm cabinet with many other heat-generating gadgets (power adapters, ethernet switch, another Pi, IPTV receiver etc.).
I only installed a small aluminum heatsink over the CPU (0,50$ on Aliexpress), completely silent.

Idle temperature around 50°C, gets around 65°C when tinkering with HA, installing plugins, restarting many times in a row.

I have other 3 RPi as media players, none needed a fan even when decoding hours of full-hd video.

Bottom line: check if you really need a fan, it’s easier :grin:

2 Likes

You’ll only need a fan it you are doing some serious overclocking… Are you!?

Mine, like @namadori’s is inside a closed telecoms cabinet with another Rpi, a couple of cellphones, two netbooks, Hubs, switches, patch panels, cables, PSUs, etc with no forced ventilation. The CPU temperature never passes 50 degrees and the cabinet temperature 25 degrees…

1 Like

RP 3 does not need any type of fan to run. Especially with HA.

1 Like

I’m running a fan on my Pi 3B, it’s connected to 3.3V, the cpu temp never gets over 45°C. I never hear the fan.

1 Like

i guess you are right. should have done more research. my RPI cpu never gets any hotter than 60-65. I actually once touched the bare cpu and it almost burnt my finger so thought it needs cooling down.

Thanks alot for the SystemD article. That probably will solve my problem.

BTW, i use this to get cpu temp

  • platform: command_line
    name: CPU Temperature
    command: “cat /sys/class/thermal/thermal_zone0/temp”

2 Likes

Can you share you setting and fancontrol.py to get the rpi fan speed.

Thank you very much.

1 Like

Get one of this and you will be fine

https://m.aliexpress.com/item/32716023912.html?pid=808_0000_0101&spm=a2g0n.search-amp.list.32716023912

1 Like

yes that’s one method to get the temp. Probably much simpler too.
I use a python program for a couple of reasons.
One being I used it as a learning exercise, and another as I report a few other details via mqtt, I also have the same program on other Pis so I can see their info in HA also.

1 Like

Here you go. note that this is actually authored by Andreas Spiess (Variable Speed Cooling Fan for Raspberry Pi using PWM (video#138) – SensorsIOT)
i have only added the code to publish fan speed and temperature to my MQTT broker, from where HA is picking it up. i have also trimmed the code down a bit to exclude the stuff he had for battery monitoring etc.

fancontrol.py

#!/usr/bin/env python3
# Author: Andreas Spiess
import os
import time
from time import sleep
import signal
import sys
import RPi.GPIO as GPIO
import paho.mqtt.publish as publish

fanPin = 17 # The pin ID, edit here to change it
batterySensPin = 18

desiredTemp = 40 # The maximum temperature in Celsius after which we trigger the fan

fanSpeed=100
sum=0
pTemp=15
iTemp=0.4

def Shutdown():  
    fanOFF()
    os.system("sudo shutdown -h 1")
    sleep(100)
def getCPUtemperature():
    res = os.popen('vcgencmd measure_temp').readline()
    temp =(res.replace("temp=","").replace("'C\n",""))
    #print("temp is {0}".format(temp)) #Uncomment here for testing
    return temp
def fanOFF():
    myPWM.ChangeDutyCycle(0)   # switch fan off
    return()
def handleFan():
    global fanSpeed,sum
    actualTemp = float(getCPUtemperature())
    diff=actualTemp-desiredTemp
    sum=sum+diff
    pDiff=diff*pTemp
    iDiff=sum*iTemp
    fanSpeed=pDiff +iDiff
    if fanSpeed>100:
        fanSpeed=100
    if fanSpeed<15:
        fanSpeed=0
    if sum>100:
        sum=100
    if sum<-100:
        sum=-100
    #print("actualTemp %4.2f TempDiff %4.2f pDiff %4.2f iDiff %4.2f fanSpeed %5d" % (actualTemp,diff,pDiff,iDiff,fanSpeed))
    myPWM.ChangeDutyCycle(fanSpeed)
    msgs = [{'topic':"RPI/Temperature", 'payload':actualTemp},
                ("RPI/FanSpeed", fanSpeed, 0, False)]
    publish.multiple(msgs, hostname="[mqtt server]", 
          auth = {'username':"[mqtt server username]", 'password':"[mqtt server password]"})
    return()
def on_disconnect(client, userdata, rc):
    logging.info("disconnecting reason  "  +str(rc))
    client.connected_flag=False
    client.disconnect_flag=True
def handleBattery():
    #print (GPIO.input(batterySensPin))
    if GPIO.input(batterySensPin)==0:
        ("Shutdown()")
        sleep(5)
        Shutdown()
    return()
def setPin(mode): # A little redundant function but useful if you want to add logging
    GPIO.output(fanPin, mode)
    return()
try:
    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(fanPin, GPIO.OUT)
    myPWM=GPIO.PWM(fanPin,50)
    myPWM.start(50)
    #GPIO.setup(batterySensPin, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
    GPIO.setwarnings(False)
    fanOFF()
    while True:
        handleFan()
        #handleBattery()
        sleep(5) # Read the temperature every 5 sec, increase or decrease this limit if you want 
except KeyboardInterrupt: # trap a CTRL+C keyboard interrupt 
    fanOFF()
    GPIO.cleanup() # resets all GPIO ports used by this program
except:
    print("probably mqtt connection failed")
3 Likes

Thank you very much. I will try and might need further advice.

This comment seems unnecessary.

2 Likes

Could you please show me the way to display fan speed on hass

Scorpion, happy to help but what is your setup? how far are you? have you managed to get the python script running and feeding fan speed via mqtt? or do you need help from scratch?

BTW i switched to a better and easier option if you are using Raspberry Pi: using the HA’s GPIO and Climate components. So basically HA handles when to start or stop the fan based on a low and high limit that you set. Only problem is you dont get to control (or monitor) the speed of fan. see a screenshot below.

RPIFan

steps to follow:

  1. Ready the fan using this link. You basically need to integrate a transistor so the Fan can be turned on or off from GPIO and even has its speed adjusted. This will give you 3 wires, Power, Ground and a Control pin.
    https://www.instructables.com/id/Control-a-Cooling-Fan-on-a-Raspberry-Pi-3/
  2. Plug the fan onto Raspberry Pi. Power to any of the power (making sure the voltage matches i.e. 3v or 5v) and ground to ground. The control pin, plug it onto pin 17.
  3. Add a switch with gpio platform to your configuration.yaml. This is my code for pin 17.
    Capture
  4. Add a climate entity to your configuration.yaml. you can read the official documentation for climate control to fine tune these parameters to adjust to your needs
    Capture
  5. Add the climate and if needed the switch to groups.yaml
    Capture
8 Likes

I already can control pi fan speed but i dont know how to display fan speed on hass overview

sorry just noticed your reply. How are you controlling the speed? from a python script? if so you can publish it at the same time, to an MQTT server. And in HAssio just create an MQTT sensor to subscribe to same topic. let me know if you need details for either side.