Raspberry Pi Fan

Sure, which part are you after. I believe i have already put all the code up there in the post.

Hi @umerfraz, I was not only thinking of the fan speed controller but more generally the page to control the main Raspberry status such as the memory for instance. What we can see in your post in Feb 2018

Ow, got it. Well I simply used the system monitoring component https://www.home-assistant.io/integrations/systemmonitor/. I was using states UI back than which is obselete now but it was automatically assigning the icons and formatting etc. i belive the defacto love lace UI should also pick the correct icons for you. I have btw switched over to a proper PC (i5 linux) now but using the same component for server stats.

Oh wha ok. I will take a look, thank you. Out of curiosity, what made you move to a proper Pc ?

Well, my setup grew too big for raspberry pi. I actually started playing with raspberry pi zero w. Worked fine for hassio with a few sensors here and there. But then had to switch to raspberry pi 3 when had more stuff integrated. That slowed down as well when i had zwave zigbee xiaomi eco system and most effected were automations becoming sluggish. I then
got my hands on a core i5 small form factor desktop pc so moved my setup to that and never had to look back.

Also Raspberry pi has been very unreliable for me. Burnt many sd cards, burnt wifi module, needed to restore every week or even more frequently. But dont let that change your perception of raspberry pi. Maybe i had a bad batch. They are really good for relatively small setups and for beginners with a large support community. Less power consumption too :slight_smile:

1 Like

Hi, did you get to control the fan speed by pwm on GPIO 17?
I have a RPi4 B, have enclosed it with this case from aliexpress.
https://www.aliexpress.com/item/Raspberry-Pi-4-Computer-Model-B-Armor-Aluminum-Alloy-Case-Passive-Cooling-Shell-Metal-Enclosure-Heat/4000001902776.html
I have the latest homeassistant installed. The twin fans are always on. With pwm control it will extend life of the fans and help me gain experience working with my RPi too.
Best regards.

Yes i just connected it to GPIO 17 or raspberry pi 3. I believe you just need to set it to right pin for raspberry pi 4. You can easily find Pin number by googling it.

Thanks for your deliberation umerfraz. I am At the beginning of the learning curve on RPi/Home Assistant. I have a mosfet ready to switch 5v through pwm pin at 3.3v.
Now i need help in detail of what goes in the config.yaml file to configure PI control using PWM (using the LED pwm) listed in this post.
Best Regards.

Cool. Keep us posted.

Hi umerfraz.
How do I add the pwmled as an addon in hassos?

Hi umerfraz.
Can you post the complete entries as I cannot do copy and paste from the post.
Thanks

Hi ropda, I too am trying to do this. I have made the transistor mosfet switch now since you have done it can you share the details with me please?

Hello Karanbir, sorry I did not answer you before, but I have been busy and I have not been able to take a look at the forum in a while.
I have to tell you that I have not managed to regulate the fan speed. I did several tests and failed to get it working.
Sorry I can’t help you, I hope you can get it.
Cheers!

Hi karansoi, sorry for late reply. I will share the code when i can. Problem is i dont use raspberry pi for my main hassio installation anymore but i do have one running with the fan and using rpi gpio component somewhere around the house. Just need to access that rpi when on home network.

Hello ropda.
I have been able to addon the pigpio in my home assistant, and the fans spin with pwm control using pwmled.
I have done it as in this link.
https://community.home-assistant.io/t/how-to-use-the-pwm-led-component-in-hassio/32446/10

hi everyone, I have a script similar to this for managing the cpu fan of my raspberry. I would like to implement the MQTT publishing of the fan speed in the script to be able to keep it under control on lovelace. I installed paho and tried to modify my script but when i start it, the script fails and does not work. Who can help me? Thanks in advance

Can you share the error that you get

Hi umerfraz, thank you for your answer.
I don’t know Phyton so i just try to make some change…
Can you please check if i made some error in the code? The py script is working if i comment the line i have added. I have just added the line where you can see <------ at the end. This is the code:

#!/usr/bin/env python3
import os
import time
import sys  <----------------
sys.path.append('/home/pi/.local/lib/python3.9/site-packages/paho/mqtt') <----------------  
import RPi.GPIO as GPIO
import paho.mqtt.publish as publish <----------------         
import glob

minimum_always_ON=True
minimum_speed=30
target_temp=52

current_speed=0

thermal_zones_temp_dirs=glob.glob("/sys/class/thermal/thermal_zone*/temp")


def getCPUtemperature():
    res = os.popen('vcgencmd measure_temp').readline()
    #vcgencmd measure_temp -> res="temp=NN.N'C\n"
    #temp =(res.replace("temp=","").replace("'C\n",""))
    temp=res[5:9]
    try : 
        temp= float(temp)
    except :
        print("vcgencmd measure_temp failed")
        temp=getCPUTemperature2()
            
    return temp

def getCPUTemperature2():
    temps=[]
    for file_dir in thermal_zones_temp_dirs:
        with open(file_dir, "r") as file:
            try :
                temps.append(float(file.read()))
            except :
                print("Error reading from file {}".format(file_dir))
                continue
    
    if len(temps) == 0:
        print("reading from sys files failed, no CPU temp detected using target_temp")
        temps.append(target_temp * 1000)
    
    return max(temps) / 1000

try:
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(18, GPIO.OUT)
    
    myPWM=GPIO.PWM(18,50)
    myPWM.start(minimum_speed)
    
    current_speed=minimum_speed
    
    while True:
        temp = getCPUtemperature()
        
        if(temp<target_temp and not minimum_always_ON):
            myPWM.ChangeDutyCycle(0)
            current_speed=0
            time.sleep(1)
            continue
        if(temp<target_temp and minimum_always_ON):
            myPWM.ChangeDutyCycle(minimum_speed)
            current_speed=minimum_speed
            time.sleep(1)
            continue
        
        if(temp>target_temp and temp<56):
            myPWM.ChangeDutyCycle(40)
            current_speed=40
            time.sleep(1)
            continue
        if(temp>56 and temp<60):
            myPWM.ChangeDutyCycle(50)
            time.sleep(1)
            continue
        if(temp>60 and temp<65):
            myPWM.ChangeDutyCycle(60)
            current_speed=60
            time.sleep(1)
            continue
        if(temp>65 and temp<70):
            myPWM.ChangeDutyCycle(70)
            current_speed=70
            time.sleep(1)
            continue
        if(temp>70 and temp<74):
            myPWM.ChangeDutyCycle(80)
            current_speed=80
            time.sleep(1)
            continue
        if(temp>74 and temp<76):
            myPWM.ChangeDutyCycle(90)
            current_speed=90
            time.sleep(1)
            continue
        if(temp>76):
           #handleFan(100)
            myPWM.ChangeDutyCycle(100)
            current_speed=100
            time.sleep(1)
            continue
        #try: <----------------
         #   publish.single("RPI/FanSpeed", current_speed, hostname="[X.X.X.X]", auth = {'username':"[MY_mqtt_user]",'password':"[MY_MQTT_PSW]"}) <----------------
        #except: <----------------
            #print("Unexpected error:", sys.exc_info()[0]) <----------------
        #finally: <----------------
        #return() <----------------
   

except KeyboardInterrupt: # trap a CTRL+C keyboard interrupt 
    GPIO.cleanup() # resets all GPIO ports used by this program

/home/pi/.local/lib/python3.9/site-packages/paho/mqtt is the path where i found paho

First error is:


  File "/home/melopero-autostart/scripts/fan_controller.py", line 111
    return()
    ^
SyntaxError: 'return' outside function

If i comment the last part of the script from TRY… to RETURN()
i get another error:

Traceback (most recent call last):
  File "/home/melopero-autostart/scripts/fan_controller.py", line 7, in <module>
    import paho.mqtt.publish as publish
ModuleNotFoundError: No module named 'paho'

It seems that can’t find paho but paho is present:

pip show paho-mqtt
Name: paho-mqtt
Version: 1.5.1
Summary: MQTT version 5.0/3.1.1 client class
Home-page: http://eclipse.org/paho
Author: Roger Light
Author-email: [email protected]
License: Eclipse Public License v1.0 / Eclipse Distribution License v1.0
Location: /home/pi/.local/lib/python3.9/site-packages
Requires:
Required-by:

and i declered path in script in line 5…
Thank for your help

Sorry for slow response. My problem is i dont have an available setup to run python. But i have a feeling the problem is with indentation of your code. In python indentation is very important. are you sure the returun in probalamtic code is indented to right below finally? like


finally:
    return()

lets start by fixing that and any other indentation issues. If i am able to i will run your code to check on my end. The imports were a pain in the neck from what i remember. It took me a long time to figure out and then fix that the path i am running the python file from is what may be used to translate the import path.

thank you for your help. The Return() was wrong. I removed it, anyway i have problem with paho… I have installed it but always sam error ModuleNotFoundError: No module named ‘paho’

I really don’t understand… :frowning: