0

I have attached a fan to pin #17 (through a transistor of course) and am writing a script to turn the fan on for a specified duration with a specified PWM duty.

#!/usr/bin/env python

import os
import sys
import thread
from time import sleep
import RPi.GPIO as GPIO

fan_pin = 17

def run_fan(pin, freq, duty) :
    global myPWM
    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(fan_pin, GPIO.OUT)
    myPWM=GPIO.PWM(pin,freq)
    myPWM.start(duty)


if len(sys.argv) < 4:
    print "Usage %s <PWM Frequency> <Duty> <Duration Percent>" % sys.argv[0]
else:
    print "Starting fan on Pin: %s, Freq: %s, Duty: %s" % (fan_pin, sys.argv[1], sys.argv[2])

    run_fan(fan_pin, float(sys.argv[1]), float(sys.argv[2]))

    sleep(float(sys.argv[3]))
    print "Done."

    # myPWM.ChangeDutyCycle(0)
    # GPIO.cleanup() 

When the two last lines are commented, and I run it with a frequency less than 100Hz, like this:

./fanOn.py 50 40 1

It generates a PWM signal of 40% duty for 1 second (which is not enough duty to turn my fan on), and then the pin goes high and remains constantly high, which makes the fan start spinning!

This does not happen if I run it with a frequency of 100Hz or higher:

./fanOn.py 100 40 1

Which makes it output a 40% PWM for 1 second and then the pin goes low and stays low.

Why is that? What happens at those lower frequencies?

I am running these in DietPi on a Raspberry Pi 3 and Python version 2.7.16

This does not happen with "gpiozero" library. That correctly shuts down the PWM on program exit.

1 Answer 1

3

I expect in reality the final state of the GPIO is pretty random. As you don't do a cleanup GPIO 17 will be left as an output. Its level will remain at whatever it was when the sleep elapses and RPi.GPIO terminates.

The final level may appear stable over successive runs for a variety of reasons. E.g. in a perfect world the sleep will elapse at exactly the same point in the waveform so it will always end up high or low.

1
  • I tested many times with different frequencies and got the same result: less than 100Hz left the pin high, otherwise low. It does not seem just random. Although I agree with you about the pin should have remained in its last state.
    – Sohail
    Jun 6, 2020 at 20:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.