I want to start the LED gradually with dimming by using PWM.

And then once at a ChangeDutyCycle(100) I want it to remain on GPIO.output(led, GPIO.HIGH).

import RPi.GPIO as GPIO
import time

led = 17

GPIO.setup(led, GPIO.OUT)

def dim():
    green = GPIO.PWM(led, 100)
    pause_time = 0.010

    for i in range(0, 100+1):
    GPIO.output(led, GPIO.HIGH)


But with the script below it just turns off.

Is this possible?

  • This not a Raspberry related question. You'll have more luck on the electronics board. Since LED's are current-driven and PWM only turns the power to the LED on and off, it seems to me that PWM is not the best way to dim LED's. You should control the current to dim a LED. But I'm no electronics engineer. – Joep Jan 17 at 15:52
  • @Joep: If this is not a "Raspberry related question", I wonder why there is a tag here for [led]? And FWIW: PWM is widely used as a method to control LED output. You can confirm that on the electronics board if you'd like. – Seamus Jan 17 at 18:28
  • it turns off because your program ends. to prove that add time.sleep(10) after GPIO.output(led, GPIO.HIGH). the LED will stay on for 10 seconds r=then turn off. – Steve Robillard Jan 17 at 18:59
  • @SteveRobillard I want it to stay on indefinitely, untill I turn it off. This is not an answer for my question. – Nikk Jan 17 at 20:43
  • @Joep How is this not a raspberry question? I'm trying to accomplish my goal with the Raspberry Pi Python module on the Pi itself. – Nikk Jan 17 at 20:44

This is kind of a python question, but is dependent on the Pi specific RPi.GPIO.

The GPIO.PWM creates a thread which is responsible for the PWM operation.
This stores data in a structure, which is (eventually) destroyed when you call PWM.stop().
You don't do this, but it will happen when the variables are garbage collected on function exit.

Effectively the Pi loses all knowledge of the pin.

You would think that explicitly calling GPIO.output(led, GPIO.HIGH) SHOULD work - you really need to dig down into the c code to see how it works.

Adding the following to the end makes it work. If you omit the delay it doesn't - presumably because this is called before the stack is cleaned up.

GPIO.output(led, GPIO.HIGH)

NOTE you could put the delay in the function, rather than after the function call but you would need to call green.stop(). It is cleaner code to do it elsewhere.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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