PWM Dimming of an LED with Raspberry Pi

3 Feb

This is Krystal’s dad guest posting again.  Krystal wanted to control some servo motors with her Raspberry Pi because she’s on a robotics team that uses the Lego NXT brick as the controller and it easily controls servos.  She wanted to see how easy it is on the Raspberry Pi.  I wouldn’t call it an easy task, but we accomplished the first step in several hours one night.  I am a complete novice to Raspberry Pi, Linux, PWM, python, and object-oriented programming in general, but I do know a thing or two about electronics and breadboards.

First thing, we read that Occidentalis is the way to go for using Pulse Width Modulation (PWM) to control servos directly from the Raspberry Pi without any controller boards connected.  So, as Krystal described in this other blog post on how to install Linux on a memory card, we used Win32DiskImager to install the Occidentalis image onto a 4 Gb memory card.  It went smoothly as soon as we remembered that we need to run Win32DiskImager as the Administrator on the computer (Right-click and “Run as Administrator”).

We popped in the memory card and started it up.  We went through the raspi-config and did the typical settings to use the whole memory card and such.  We noticed that there were no settings for overclocking in this version of Linux so we planned for tasks to take longer than we were used to with her jazzed up version of Wheezy that we usually use.

To start, we typed sudo apt-get update, but it didn’t work since we hadn’t configured the wifi yet.  So, we looked up the instructions for how to do that on Occidentalis.  We removed the wifi dongle, typed “sudo nano /etc/network/interfaces” and added our SSID and password and saved (CTRL^X, Y, Enter).  We shutdown the Pi (sudo shutdown now), put the wifi dongle back in, and turned the Pi back on.  We’ll skip a few trial and errors that occurred here and just skip to the part where it worked.  When we typed ifconfig, our IP address showed up.  This was actually the easiest time we’ve had connecting to wifi.  You can read about her other adventures with wifi in a past blog post.

So, we did the update and started watching a video about using PWM (but not on the RPi because there’s still no simple method to watch YouTube videos on the Pi).  We figured that we’d start by dimming an LED before running servo motors.  So, we went to and tried to reproduce his results.  Of course, you know what comes next if you’ve been following this blog at all . . . it didn’t work.

We kept getting the message that there was no module named RPi.GPIO.  So, we researched how to install RPi.GPIO and tried it time after time after time and kept getting the same error message.  So, we reinstalled and updated Python then installed Python3.  Still didn’t work.  Updated Python3, still didn’t work.  Typed startx to open Midori and research some more and found where we could download the RPi.GPIO module, unzip it, and install it from the graphical interface.

Didn’t work.  Kept getting an unexpected end of file error when extracting.  So, we tried installing Gzip to extract the files.  Couldn’t get that to work.  Finally, instead of doing a Save As and then extracting, we chose “Open” after clicking the download button and it worked.  (Download the module here:  Then, we just typed “sudo python3 install” (as we read on the website) (and we admit that we failed several more times before coming to this solution) and it seemed to install.  But, it still didn’t work.  Turns out that one of the things that we’d tried in order to fix it earlier was the case of the letters in RPi.GPIO.  We’d changed it to rpi.gpio.  Once we changed it back, it worked (almost, we had to connect it to the right pin on the GPIO and that took several tries.  Why aren’t Pin 7 and GPIO7 the same thing?????).

Here’s the code that we used (Krystal was in bed by now and hasn’t seen this working as I’m writing this.)


import RPi.GPIO as GPIO        #This line alone caused 90 minutes of frustration

import time


GPIO.setup(21, GPIO.OUT) #set pin 21 to output

p = GPIO.PWM(21,50)        #set the PWM on pin 21 to 50%

p.start(0) #I don’t remember what this does but trust me, you need it.


while True:

for i in range (100):


time.sleep(0.02)         #These last three lines are going to loop and increase the power from 1% to 100% gradually

for i in range(100):


time.sleep(0.02)         #These three lines loop and decrease the power from 100%-1% gradually

except KeyboardInterrupt:

pass                   #This is supposed to stop the program if a key is hit, but it doesn’t work for us.  Only ctrl^c works




It works!  We have an LED that goes from dark to bright to dark again gradually over and over.  The only difference between our program and the one in the video referenced above is that we used pin 21 for our LED and he used pin 7.

So, I started playing with the numbers.  I found that the duty cycle is not allowed to go over 100.  By changing the time.sleep value, I can change how fast the dimming and brightening cycle is.  Changing it to 0.01 gives a nice, steady pulse.  We could change the i in range to 50 if we didn’t want the LED to go to full brightness.

See the un-amazing video here:

Next step is to control a servo motor instead of an LED.  It should be a very similar process.  After that, we’ll try and take over the world, dun dun duh.


Raspberry Pi, power supply, keyboard, mouse, USB hub, etc.

Occidentalis distro of Linux

RPi.GPIO module

LEDs, breadboard, wires, resistors

Wifi dongle or other direct internet connection

Infinite patience (no URL for that one)

11 Responses to “PWM Dimming of an LED with Raspberry Pi”

  1. DXM40HOURS February 3, 2014 at 2:51 pm #

    All this arsing around is why the type system in Python sucks, even if the language itself is good.

    • Geri Freitas February 17, 2014 at 6:00 am #

      for i in range(100):


      Should be:

      for i in range(100):


      • Geri Freitas February 17, 2014 at 6:02 am #

        Import RPi.GPIO as GPIO #This line alone …

        Import time

        Should be lower-case “i” in “import”:

        import RPi.GPIO as GPIO

        import time

      • krystal92586 February 20, 2014 at 4:36 am #

        Fixed, thanks!

  2. mattyd02 March 12, 2014 at 10:30 pm #

    Thank god I’m not the only 11 (nearly 12) year old person that actually seems to want to learn about the raspberry pi and it’s infinite possibilities 😄

  3. koaaladekoolGerry July 9, 2014 at 8:48 am #

    Thank you for the great tutorial, been looking for ages how to get my RGB led control working with python, this one helped me out a lot! Cheers!

  4. plasma October 3, 2014 at 2:40 am #

    Why p.changeDutyCycle(100-i)? Isn’t range(100,0,-1) enough for a decreasing iterator(`i’ will go from 100 to 0 then)?
    Also, KeyboardInterrupt is only raised when Ctrl+C (SIGINT) key sequence is pressed, so it is NOT usable for catching key events.

    Great tutorial anyway, thanks!

    • plasma October 3, 2014 at 2:45 am #

      Another one, xrange should be used instead of range for memory and performance (range creates whole array)

    • krystal92586 October 11, 2014 at 3:53 am #

      Thanks, plasma. It’s just two different ways to accomplish the same thing and I chose the one that makes the most sense to me and I can remember the longest.
      Thanks for the top on KeyboardInterrupt. Apparently, it’s not exactly what it sounds like.


  1. PWM Dimming of an LED with Raspberry Pi | Raspberry World - February 3, 2014

    […] By krystal92586 […]

  2. PWM Dimming of an LED with Raspberry Pi #piday #raspberrypi @Raspberry_Pi « adafruit industries blog - February 7, 2014

    […] PWM Dimming of an LED with Raspberry Pi: […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: