Raspberry Pi Fan

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.

I followed your guide and can control fan now, but do you know how to control pi fan speed?
Tks,

for controlling the speed you should follow this article http://www.sensorsiot.org/variable-speed-cooling-fan-for-raspberry-pi-using-pwm-video138/

Hey, which lovelace card is this that shows the Server Stats?

icon - name - value
icon - name - value

Just the default thermostat lovelace card. :slight_smile:

1 Like

Thanks! exactly what I was looking for!!

Hay, Can you share how did you make the mqtt sensor.
Thanks.

Hi, I dont have these sensors anymore as i switched from RPI to a proper intel pc. But try the following

  - platform: mqtt
    name: "CPU Temperature"
    state_topic: "RPI/Temperature"
    unit_of_measurement: "°C"
    value_template: '{{ value | round(2)  }}'

Good afternoon to everyone and happy new year.
Sorry if I do not express myself properly, but I do not have enough knowledge to write directly in English, so I use “Google translator”.
I am new in Hass.io and I need your help. I am trying to make the CPU fan on my Raspberry Pi 4 work (Home Assistant 0.103 and System, HassOS 3.7) following the design and indications of the Andreas Spiess blog (videos # 131 and # 138), the contributions of “umerfraz” and rest of that thread.
I have got nothing at all. I have the file “fancontrol.py”, but I don’t know neither where to place it, from where nor how to execute it. I would like to know how to make it runs at start the system and keeps it running and what should be added in “configuration.yaml” or in another file.
I’ve been testing for a couple of weeks and I haven’t been able to make it works. The hardware is OK, but the fan does not spin.
Thanks for listening and I hope someone can guide me.

Happy to help ropda, but can you make sure you have setup the hardware properly. i.e. your fan has one ground, one positive and a control/signal wire? Exactly as per Andreas Spiess’s blog? Thats the tricky part.

For the software part I would suggest you go with Home Assistant only option instead of python script as that is much simpler and already explained above. It basically involves setting up a sensor to sense Raspbrery Pi’s CPU temperature. Setting up a GPIO pin as switch in HA where you have connected your Fan’s control pin and finally using both of these in a generic thermostat component of HA. You can even change the temperature threshold dynamically. Let me know which step you are stuck on.

Hello again, thanks for your quick response umerfraz, in principle the hardware is ok. Following your instructions I have been able to operate the gpio17 depending on the temperature, the fan does not work because with the 3.3V output of the gpio17 you cannot activate the transistor I use (IRF510A, the other components R1 = 2.2k Ohms , R2 = 100 Ohms and D = 1N4007) but with 5V if it works. I will be testing, I will appreciate if you have any suggestions.
With this programming done with Home Assistant I do not see that it regulates the speed of the fan (gpio17 PWM), like in the first option you gave (based on the Andreas Spiess file) written in Python. Would it be possible to do so with the option of Home Assistant?
Thanks again and regards

Ropda, i am no good in electronics but I believe this would be a problem as Pi’s GPIOs are 3.3volts. But if you really followed Andreas’ post then you would have Pi compatible setup. The Pi’s btw do have atleast two 5v pins to POWER stuff.
Once you have the hardware ready, Homeassistant has the ability to directly monitor/control GPIOs of host Raspberry Pi using the GPIO component. All i have done is to use that for controlling the pin connected to Fan’s control. See the 3 liner config for that in my post above.
Next step is to setup CPU tempreature sensor and finally setting up a generic thermostat to link both of these things.

Thanks umerfraz, about the hardware, I’m working on it.
About programming, I am sorry for expressing myself incorrectly. I made the correct integration following your instructionsControl Temperatura CPU
, but I understand that with this method we are not regulating the fan speed. My question was about being able to regulate the fan speed to achieve the following effect, for example.
Reference temperature 45º

  • The fan turns on at 50º working at 80% speed
  • When the temperature drops to 47º the fan speed drops to 60%
  • When the temperature drops to 43º the fan speed drops to 40%
  • When the temperature drops to 40º, the fan turns off.
    I understand that it is not necessary, but I think it would be an interesting exercise.
    Thanks again and regards
2 Likes