Orange Pi Pulse Width Modulation

09/01/18

Categories: Computers Tags: Orange Pi

~/contents

This is so cool. I had problems with a fan, which was too fast, so I was trying to figure out a way to control the speed.

The Orange Pi Zero and PC2 support PWM on pin PA06 and I found it very easy to use. evergreen-it-dev’s orangepwm library is a fork of pizypwm and is compatible with the pyA20.gpio library. Raspberry Pi Pulse Width Modulation provides a fritzing schematic showing how to test this with the orangepwm LED example script.

This is my updated code. Works like a charm, the fan runs quietly at 50% and the RetrOrangePi Zero idles at 52C and tops out around 60C, which is even lower than when the fan was running at 100%.

#!/usr/bin/python
from pyA20.gpio import gpio
from pyA20.gpio import port
from time import sleep
from orangepwm import *
import sys

FAN = port.PA6
ON_TEMP = 60
OFF_TEMP = 50
monitoring = True
fan_status = False

gpio.init()
pwm = OrangePwm(100, FAN)

def fan_shutdown():
    global monitoring, fan_status
    monitoring = False
    fan_status = True
    pwm.changeDutyCycle(0)
    pwm.stop()

def fan_start():
    global fan_status
    fan_status = True
    pwm.start(50)

def fan_stop():
    global fan_status
    fan_status = False
    pwm.changeDutyCycle(0)

def cpu_temp_check():
    try:
        while monitoring:
            with open( "/sys/devices/virtual/thermal/thermal_zone0/temp" ) as f:
                content = f.readlines()
            temp = int(content[0])
            base_temp = int(str(temp)[:2])

            if base_temp >= ON_TEMP and not fan_status:
                fan_start()

            elif base_temp < OFF_TEMP and fan_status:
                fan_stop()
            sleep(1)

    except:
        print("Fan error.")
        return

if __name__ == '__main__':
   cpu_temp_check()