LED dimming with PWM / Wake-up Light, 1

One way to control the brightness of a led can be by controlling the current in the circuit. A raspberry pi (rpi) is not able to control the current, and the final power source will anyway not be a rpi.

Another one is PWM, which stands for pulse-width modulation.1 PWM basically switches the current on and off very fast, so that the average is as desired. And this should also work with an external power supply.

The external power goes through an MOSFET, which en/disables the current. the MOSFET is controlled by the PWM from the rpi. But not directly, because the MOSFET needs more voltage than the rpi can supply … therefore we need a sub-circuit. This sub-circuit consists of the rpi, which controls a NPN transistor, which in turn switches current from the external power supply on/off (PWM) to finally control the MOSFET.

The code is very simple at the moment. Just enable the GPIO stuff, and then vary the PWM signal from 0 to 100 and back again. I have to checkout wiringpi — it seems RPi.GPIO can only support software PWM, while wiringpi can support hardware PWM.

import RPi.GPIO as IO
import time

IO.setmode (IO.BCM)
IO.setup(16,IO.OUT)

p = IO.PWM(16, 100)
p.start(0)

try:
  while(1):
    for x in range(100):
      p.ChangeDutyCycle(x)
      time.sleep(0.1)

    for x in range(100):
      p.ChangeDutyCycle(100-x)
      time.sleep(0.1)
except KeyboardInterrupt:
  p.stop()
  IO.cleanup()

Seems to work ๐Ÿ™‚

  1. https://en.wikipedia.org/wiki/Pulse-width_modulation