Raspberry Pi Fan

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.

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.