{"id":129523,"date":"2023-05-26T13:22:33","date_gmt":"2023-05-26T13:22:33","guid":{"rendered":"https:\/\/randomnerdtutorials.com\/?p=129523"},"modified":"2023-07-19T11:04:25","modified_gmt":"2023-07-19T11:04:25","slug":"raspberry-pi-pwm-python","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/raspberry-pi-pwm-python\/","title":{"rendered":"Raspberry Pi: PWM Outputs with Python (Fading LED)"},"content":{"rendered":"\n<p>In this guide, you&#8217;ll learn how to generate PWM signals on the Raspberry Pi GPIOs. As an example, we&#8217;ll show you how to dim the brightness of an LED by changing the duty cycle over time. Generating PWM signals can also be useful to control other peripherals like servo motors.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" fetchpriority=\"high\" decoding=\"async\" width=\"1200\" height=\"675\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Raspberry-Pi-PWM-output.jpg?resize=1200%2C675&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi PWM Outputs with Python Fading LED\" class=\"wp-image-129853\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Raspberry-Pi-PWM-output.jpg?w=1280&amp;quality=100&amp;strip=all&amp;ssl=1 1280w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Raspberry-Pi-PWM-output.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Raspberry-Pi-PWM-output.jpg?resize=1024%2C576&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Raspberry-Pi-PWM-output.jpg?resize=768%2C432&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\">Table of Contents<\/h2>\n\n\n\n<p>Throughout this tutorial, we\u2019ll cover the following main topics:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><a href=\"#Raspberry-Pi-GPIOs-introduction\" title=\"\">Introducing the Raspberry Pi GPIOs<\/a><\/li>\n\n\n\n<li><a href=\"#introducing-pwm\" title=\"\">Introducing PWM<\/a><\/li>\n\n\n\n<li><a href=\"#connect-led-Raspberry-Pi-wire-circuit\" title=\"\">Connect an LED to the Raspberry Pi<\/a><\/li>\n\n\n\n<li><a href=\"#raspberry-pi-dim-led\" title=\"\">Dim an LED with the Raspberry Pi using PWM<\/a><\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites<\/h2>\n\n\n\n<p>Before continuing with this tutorial, check the following prerequisites.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Get familiar with the Raspberry Pi board\u2014if you&#8217;re not familiar with the Raspberry Pi, you can read our <a href=\"https:\/\/randomnerdtutorials.com\/getting-started-with-raspberry-pi\/\" title=\"\"><strong>Raspberry Pi Getting Started Guide<\/strong>.<\/a><\/li>\n\n\n\n<li>You must know how to run and create Python files on your Raspberry Pi. We like to program our Raspberry Pi via SSH using an extension on VS Code. We have a detailed tutorial about that subject: <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-remote-ssh-vs-code\/\" title=\"\"><strong>Programming Raspberry Pi Remotely using VS Code (Remote-SSH)<\/strong><\/a>.<\/li>\n<\/ol>\n\n\n\n<p class=\"rntbox rntclblue\"><strong>First time controlling the Raspberry Pi Outputs?<\/strong> Get Started by <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-digital-outputs-python\/\">controlling the Raspberry Pi Digital Outputs<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"Raspberry-Pi-GPIOs-introduction\">Introducing the Raspberry Pi GPIOs<\/h2>\n\n\n\n<p>GPIO stands for <em>General Purpose Input Output<\/em> pins and those allow you to connect and control electronic hardware, like LEDs, motors, and sensors to your Raspberry Pi.<\/p>\n\n\n\n<p>Most models of Raspberry Pi boards have a double row of 40 GPIO pins. The layout of the pins is usually the same for most Raspberry Pi models.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"1024\" height=\"576\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Raspberry-Pi-Pinout-Random-Nerd-Tutorials.png?resize=1024%2C576&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi  Pinout Random Nerd Tutorials\" class=\"wp-image-129396\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Raspberry-Pi-Pinout-Random-Nerd-Tutorials.png?resize=1024%2C576&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Raspberry-Pi-Pinout-Random-Nerd-Tutorials.png?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Raspberry-Pi-Pinout-Random-Nerd-Tutorials.png?resize=768%2C432&amp;quality=100&amp;strip=all&amp;ssl=1 768w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Raspberry-Pi-Pinout-Random-Nerd-Tutorials.png?w=1280&amp;quality=100&amp;strip=all&amp;ssl=1 1280w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">Raspberry Pi Pinout<\/figcaption><\/figure><\/div>\n\n\n<p>There are two different ways to refer to a GPIO pin: its name (which is known as GPIO numbering or Broadcom numbering) or its corresponding pin physical number (which corresponds to the pin&#8217;s physical location on the header). <\/p>\n\n\n\n<p>For example, GPIO 25 corresponds to pin 22 (see the picture above). Throughout this tutorial, we&#8217;ll refer to GPIO pins by their GPIO numbering (Broadcom numbering).<\/p>\n\n\n\n<p class=\"rntbox rntclgreen\">To learn more about the Raspberry Pi GPIOs, check the Raspberry Pi Pinout Guide: <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pinout-gpios\/\">Raspberry Pi Pinout Guide: How to use the Raspberry Pi GPIOs?<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"introducing-pwm\">Introducing PWM (Pulse-Width Modulation)<\/h2>\n\n\n\n<p>The Raspberry Pi GPIOs can be set either to output 0V or 3.3V (<strong><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-digital-outputs-python\/\">check this tutorial about the Raspberry Pi Digital Outputs<\/a><\/strong>), but they can\u2019t output any voltages in between. However, you can output \u201cfake\u201d mid-level voltages using pulse\u2011width modulation (PWM), which is how you\u2019ll produce varying levels of LED brightness for this project. PWM is also useful for other applications like varying the speed of DC motors, setting the position of a servo motor, and much more.<\/p>\n\n\n\n<p>If you alternate an LED\u2019s voltage between HIGH and LOW very fast, your eyes can\u2019t keep up with the speed at which the LED switches on and off; you\u2019ll simply see some gradations in brightness.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"895\" height=\"182\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/07\/led-fade.png?resize=895%2C182&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Fade LED with Pulse-Width Modulation (PWM)\" class=\"wp-image-86976\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/07\/led-fade.png?w=895&amp;quality=100&amp;strip=all&amp;ssl=1 895w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/07\/led-fade.png?resize=300%2C61&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/07\/led-fade.png?resize=768%2C156&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 895px) 100vw, 895px\" \/><\/figure><\/div>\n\n\n<p>That\u2019s basically how PWM works \u2014 by producing an output that changes between HIGH and LOW at a very high frequency.<\/p>\n\n\n\n<p>The duty cycle is the fraction of the time period at which LED is set to HIGH. The following figure illustrates how PWM works.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"711\" height=\"658\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/07\/PWM-how-it-works.png?resize=711%2C658&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"How Pulse-Width Modulation (PWM) works to fade LED\" class=\"wp-image-86977\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/07\/PWM-how-it-works.png?w=711&amp;quality=100&amp;strip=all&amp;ssl=1 711w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/07\/PWM-how-it-works.png?resize=300%2C278&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 711px) 100vw, 711px\" \/><figcaption class=\"wp-element-caption\">How PWM Works<\/figcaption><\/figure><\/div>\n\n\n<p>A duty cycle of 50 percent results in 50 percent LED brightness, a duty cycle of 0 means the LED is fully off, and a duty cycle of 100 means the LED is fully on. Changing the duty cycle is how you produce different levels of brightness.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">PWM Pins on the Raspberry Pi<\/h3>\n\n\n\n<p>The Raspberry Pi has 4 hardware PWM pins:&nbsp;<strong>GPIO 12<\/strong>,&nbsp;<strong>GPIO 13<\/strong>,&nbsp;<strong>GPIO 18<\/strong>,&nbsp;<strong>GPIO 19<\/strong>.<\/p>\n\n\n\n<p><strong>You can have software PWM on all pins.<\/strong> You can pretty much choose any pin (except GPIO 0 and 1) to output PWM signals.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"connect-led-Raspberry-Pi-wire-circuit\">Wiring the Circuit<\/h2>\n\n\n\n<p>Wire an LED to one of the Raspberry Pi GPIOs. We&#8217;ll connect one LED to <span class=\"rnthl rntcorange\">GPIO 14<\/span> (pin 8). You can use any other pins, except GPIO 0 and GPIO 1.<\/p>\n\n\n\n<p>Here&#8217;s a list of components you need:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/raspberry-pi-board\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Raspberry Pi Board<\/a> &#8211; read <a href=\"https:\/\/makeradvisor.com\/best-raspberry-pi-starter-kits\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Best Raspberry Pi Starter Kits<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/3mm-5mm-leds-kit-storage-box\/\" target=\"_blank\" rel=\"noopener\" title=\"\">LED<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/resistors-kits\/\" target=\"_blank\" rel=\"noopener\" title=\"\">220 Ohm resistor<\/a> (or similar)<\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/mb-102-solderless-breadboard-830-points\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Breadboard<\/a><\/li>\n<\/ul>\n\n\n<p>You can use the preceding links or go directly to <a href=\"https:\/\/makeradvisor.com\/tools\/?utm_source=rnt&utm_medium=post&utm_campaign=post\" target=\"_blank\">MakerAdvisor.com\/tools<\/a> to find all the parts for your projects at the best price!<\/p><p style=\"text-align:center;\"><a href=\"https:\/\/makeradvisor.com\/tools\/?utm_source=rnt&utm_medium=post&utm_campaign=post\" target=\"_blank\"><img data-recalc-dims=\"1\" decoding=\"async\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/10\/header-200.png?w=1200&#038;quality=100&#038;strip=all&#038;ssl=1\"><\/a><\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"544\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Wire-LED-to-Raspberry-Pi.png?resize=750%2C544&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"LED connected to Raspberry Pi GPIO14 Circuit Diagram\" class=\"wp-image-129832\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Wire-LED-to-Raspberry-Pi.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Wire-LED-to-Raspberry-Pi.png?resize=300%2C218&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"raspberry-pi-dim-led\">Dim an LED with Python on the Raspberry Pi<\/h2>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">gpiozero<\/span> library provides a collection of interfaces for everyday components like LEDs, buttons, potentiometers, sensors, and much more. <\/p>\n\n\n\n<p>So, instead of setting the GPIO properties to dim an LED, the <span class=\"rnthl rntliteral\">gpiozero<\/span> provides an interface called <span class=\"rnthl rntliteral\">PWMLED<\/span> with methods that are useful to control LEDs, including a method to produce PWM signals to vary the LED brightness.<\/p>\n\n\n\n<p>Instead, you can also use the <span class=\"rnthl rntliteral\">PWMOutputDevice<\/span> interface that can be used to control other digital outputs with PWM. Let&#8217;s see how it works.<\/p>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">gpiozero<\/span> library should already be installed if you&#8217;re running Raspberry Pi OS \u2014 if not, you can run:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><span class=\"rnthl rntliteral\">python3 -m pip gpiozero<\/span>.<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Python Script &#8211; PWM on Raspberry Pi GPIOs<\/h3>\n\n\n\n<p>Create a new python file on your Raspberry Pi called <em>fade_led.py<\/em> and copy the following code.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Complete Project Details: https:\/\/RandomNerdTutorials.com\/raspberry-pi-pwm-python\/\r\n\r\nfrom gpiozero import PWMLED\r\nfrom time import sleep\r\n\r\nled = PWMLED(14)\r\n\r\nled.value = 1   #LED fully on\r\nsleep(1)\r\nled.value = 0.5  #LED half-brightness\r\nsleep(1)\r\nled.value = 0    #LED fully off\r\nsleep(1)\r\n\r\ntry:\r\n  # fade in and out forever\r\n  while True:\r\n    #fade in\r\n    for duty_cycle in range(0, 100, 1):\r\n      led.value = duty_cycle\/100.0\r\n      sleep(0.05)\r\n\r\n    #fade out\r\n    for duty_cycle in range(100, 0, -1):\r\n      led.value = duty_cycle\/100.0\r\n      sleep(0.05)\r\n      \r\nexcept KeyboardInterrupt:\r\n  print(&quot;Stop the program and turning off the LED&quot;)\r\n  led.value = 0\r\n  pass<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/Raspberry-Pi\/pwm\/fade_led.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<h4 class=\"wp-block-heading\">How the Code Works<\/h4>\n\n\n\n<p>Continue reading to learn how the code works.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Importing Libraries<\/h4>\n\n\n\n<p>First, you import the <span class=\"rnthl rntliteral\">PWMLED<\/span> component from the <span class=\"rnthl rntliteral\">gpiozero<\/span> library to control the GPIO that the LED is connected to. Then, you also need to import the <span class=\"rnthl rntliteral\">sleep()<\/span> function from the <span class=\"rnthl rntliteral\">time<\/span> module to create delays in the code.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>from gpiozero import LED\nfrom time import sleep<\/code><\/pre>\n\n\n\n<p>Instead of the <span class=\"rnthl rntliteral\">PWMLED<\/span> component, you can use the <span class=\"rnthl rntliteral\">PWMOutputDevice<\/span> component which works exactly the same.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>from gpiozero import PWMOutputDevice<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Declaring the PWM LED<\/h4>\n\n\n\n<p>Next, you create a <span class=\"rnthl rntliteral\">PWMLED<\/span> object called <span class=\"rnthl rntliteral\">led<\/span> that refers to <span class=\"rnthl rntcorange\">GPIO 14<\/span>, which is the GPIO that the LED is connected to. Change the number if you&#8217;re using another GPIO.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>led = LED(14)<\/code><\/pre>\n\n\n\n<p>When you create and use this <span class=\"rnthl rntliteral\">PWMLED<\/span> object, your program knows that <span class=\"rnthl rntcorange\">GPIO 14<\/span> is a PWM output that can produce PWM signals with different duty cycle values. After this declaration, you can use <span class=\"rnthl rntliteral\">led<\/span> to refer to your <span class=\"rnthl rntcorange\">GPIO 14<\/span>.<\/p>\n\n\n\n<p><strong>Note<\/strong>: if you want to use the <span class=\"rnthl rntliteral\">PWMOutputDevice<\/span> component instead, the declaration would be as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>led = PWMOutputDevice(14)<\/code><\/pre>\n\n\n\n<p><strong>Note<\/strong>: if you want to use PWM signals to control DC and servo motors, the <span class=\"rnthl rntliteral\">gpiozero<\/span> provides the <span class=\"rnthl rntliteral\">Motor<\/span>, <span class=\"rnthl rntliteral\">Servo<\/span>, and <span class=\"rnthl rntliteral\">AngularServo<\/span> classes.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Control the LED Brightness<\/h4>\n\n\n\n<p>You can assign a specific brightness level to the LED by setting a specific number to the <span class=\"rnthl rntliteral\">value<\/span> property as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>led.value = 1   #LED fully on<\/code><\/pre>\n\n\n\n<p>Setting <span class=\"rnthl rntliteral\">led.value<\/span> to <span class=\"rnthl rntliteral\">1<\/span> corresponds to 100% duty cycle, and so the LED will be fully on.<\/p>\n\n\n\n<p>To turn off the LED completely, you set the <span class=\"rnthl rntliteral\">value<\/span> to <span class=\"rnthl rntliteral\">0<\/span> (0% duty cycle).<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>led.value = 0    #LED fully off<\/code><\/pre>\n\n\n\n<p>For varying levels of duty cycle, and thus varying brightness levels, set the <span class=\"rnthl rntliteral\">value<\/span> to a number between 0 and 1.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>led.value = 0.5  #LED half-brightness<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Fade In an LED<\/h4>\n\n\n\n<p>The code then enters a loop where it gradually increases the duty cycle from 0% to 100% in steps of 1% with a delay of 0.05 seconds between each step. This causes the LED to fade in gradually.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>for duty_cycle in range(0, 100, 1):\n      led.value = duty_cycle\/100.0\n      sleep(0.05)<\/code><\/pre>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">range()<\/span> function only accepts integer numbers, that&#8217;s why then we divide the <span class=\"rnthl rntliteral\">duty_cycle<\/span> variable by 100 so that we can have a value between 0 and 1.<\/p>\n\n\n\n<div class=\"wp-block-group rntbox rntclgray\"><div class=\"wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained\">\n<p>The <span class=\"rnthl rntliteral\">range(start, stop, increment)<\/span> function in Python generates a sequence of numbers. It accepts as arguments the following:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><span class=\"rnthl rntliteral\">start<\/span>: the starting value of the sequence (inclusive)<\/li>\n\n\n\n<li><span class=\"rnthl rntliteral\">stop<\/span>: the last value of the sequence (exclusive)<\/li>\n\n\n\n<li><span class=\"rnthl rntliteral\">step<\/span>: increment between each value, the default is 1<\/li>\n<\/ul>\n<\/div><\/div>\n\n\n\n<h4 class=\"wp-block-heading\">Fade Out an LED<\/h4>\n\n\n\n<p>We do exactly the same thing to fade out the LED, but we change the arguments of the <span class=\"rnthl rntliteral\">range()<\/span> function so that it starts at 100 and decreases the duty cycle by 1 in each loop.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>#fade out\nfor duty_cycle in range(100, 0, -1):\n  led.value = duty_cycle\/100.0\n  sleep(0.05)<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Try and Except with Keyboard Interrupt<\/h4>\n\n\n\n<p>To prevent staying with an LED on when you stop the execution of the program, we added a <em>Try <\/em>and <em>Except <\/em>statement. This will catch the <span class=\"rnthl rntliteral\">KeyboardInterrupt<\/span> exception, which is raised when you press <strong>Ctrl<\/strong>+<strong>C<\/strong> to stop the program. When this happens, we turn off the LED before exiting the program.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>except KeyboardInterrupt:\n  print(\"Stop the program and turning off the LED\")\n  led.value = 0\n  pass<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">In summary&#8230;<\/h3>\n\n\n\n<p><strong>1)<\/strong> To output PWM signals on the Raspberry Pi GPIOs, you can use the <span class=\"rnthl rntliteral\">PWMLED<\/span> or the <span class=\"rnthl rntliteral\">PWMOutputDevice<\/span> interface of the <span class=\"rnthl rntliteral\">gpiozero<\/span> library. You need to import it first like this:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>from gpiozero import PWMLED<\/code><\/pre>\n\n\n\n<p>or like this:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>from gpiozero import PWMOutputDevice<\/code><\/pre>\n\n\n\n<p><strong>2)<\/strong> Define the GPIO that you want to control. Using the <span class=\"rnthl rntliteral\">LED<\/span> interface:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>led = PWMLED(<strong>GPIO_NUMBER_OF_YOUR_CHOICE<\/strong>)<\/code><\/pre>\n\n\n\n<p>Or if you use the <span class=\"rnthl rntliteral\">DigitalOutputDevice<\/span> interface:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>led = PWMOutputDevice(<strong>GPIO_NUMBER_OF_YOUR_CHOICE<\/strong>)<\/code><\/pre>\n\n\n\n<p><strong>3)<\/strong> Set the duty cycle (change the LED brightness) with the <span class=\"rnthl rntliteral\">value<\/span> property:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>led.value = 1   #LED fully on <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>led.value = 0.5  #LED half-brightness<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>led.value = 0    #LED fully off<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Demonstration<\/h3>\n\n\n\n<p>Save your python file. Then run it on your Raspberry Pi. Run the following command on the directory of your project file (use the name of your file):<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>python <em>fade_led.py<\/em><\/code><\/pre>\n\n\n\n<p>The LED connected to <span class=\"rnthl rntcorange\">GPIO 14<\/span> will first turn on, then with 50% brightness, and next, it will turn off.<\/p>\n\n\n\n<p>Finally, it will start fading in and out continuously until you stop the execution of the program.<\/p>\n\n\n\n<div class=\"wp-block-jetpack-tiled-gallery aligncenter is-style-square\"><div class=\"tiled-gallery__gallery\"><div class=\"tiled-gallery__row columns-3\"><div class=\"tiled-gallery__col\"><figure class=\"tiled-gallery__item\"><img decoding=\"async\" srcset=\"https:\/\/i1.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/RPi-Fade-LED-low-brightness.jpg?resize=422%2C422&#038;strip=info&#038;ssl=1 422w\" alt=\"\" data-height=\"422\" data-id=\"129859\" data-link=\"https:\/\/randomnerdtutorials.com\/?attachment_id=129859#main\" data-url=\"https:\/\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/RPi-Fade-LED-low-brightness.jpg\" data-width=\"750\" src=\"https:\/\/i1.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/RPi-Fade-LED-low-brightness.jpg?ssl=1&amp;resize=422%2C422\" data-amp-layout=\"responsive\"\/><\/figure><\/div><div class=\"tiled-gallery__col\"><figure class=\"tiled-gallery__item\"><img decoding=\"async\" srcset=\"https:\/\/i2.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/RPi-Fade-LED-half-brightness.jpg?resize=422%2C422&#038;strip=info&#038;ssl=1 422w\" alt=\"\" data-height=\"422\" data-id=\"129860\" data-link=\"https:\/\/randomnerdtutorials.com\/?attachment_id=129860#main\" data-url=\"https:\/\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/RPi-Fade-LED-half-brightness.jpg\" data-width=\"750\" src=\"https:\/\/i2.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/RPi-Fade-LED-half-brightness.jpg?ssl=1&amp;resize=422%2C422\" data-amp-layout=\"responsive\"\/><\/figure><\/div><div class=\"tiled-gallery__col\"><figure class=\"tiled-gallery__item\"><img decoding=\"async\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/RPi-Fade-LED-full-brightness.jpg?resize=422%2C422&#038;strip=info&#038;ssl=1 422w\" alt=\"\" data-height=\"422\" data-id=\"129861\" data-link=\"https:\/\/randomnerdtutorials.com\/?attachment_id=129861#main\" data-url=\"https:\/\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/RPi-Fade-LED-full-brightness.jpg\" data-width=\"750\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/RPi-Fade-LED-full-brightness.jpg?ssl=1&amp;resize=422%2C422\" data-amp-layout=\"responsive\"\/><\/figure><\/div><\/div><\/div><\/div>\n\n\n\n<p>We added a condition that when the program stops, the LED turns off.<\/p>\n\n\n\n<p>You can stop the execution of the program by pressing <strong>CTRL<\/strong>+<strong>C<\/strong>. Notice that the LED will turn off, and a message will be printed on the Terminal shell.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">PWM Output Device<\/h3>\n\n\n\n<p>If you&#8217;re using a Generic PWM Output device, here&#8217;s an example using the <span class=\"rnthl rntliteral\">PWMOutputDevice<\/span> class.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Complete Project Details: https:\/\/RandomNerdTutorials.com\/raspberry-pi-pwm-python\/\r\n\r\nfrom gpiozero import PWMOutputDevice\r\nfrom time import sleep\r\n\r\nled = PWMOutputDevice(14)\r\n\r\nled.value = 1   #LED fully on\r\nsleep(1)\r\nled.value = 0.5  #LED half-brightness\r\nsleep(1)\r\nled.value = 0    #LED fully off\r\nsleep(1)\r\n\r\ntry:\r\n  # Fade in and out forever\r\n  while True:\r\n    #fade in\r\n    for duty_cycle in range(0, 100, 1):\r\n      led.value = duty_cycle\/100.0\r\n      sleep(0.05)\r\n\r\n    #fade out\r\n    for duty_cycle in range(100, 0, -1):\r\n      led.value = duty_cycle\/100.0\r\n      sleep(0.05)\r\n\r\nexcept KeyboardInterrupt:\r\n  print(&quot;Stop the program and turning off the LED&quot;)\r\n  led.value = 0\r\n  pass<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/Raspberry-Pi\/pwm\/fade_pwm_output_device.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Other Useful Methods<\/h3>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">PWMLED<\/span> and <span class=\"rnthl rntliteral\">DigitalOutputDevice<\/span> interfaces provide other useful additional methods.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">pulse()<\/h4>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">pulse()<\/span> method fades in and out repeatedly. Here&#8217;s an example of how you use the <span class=\"rnthl rntliteral\">pulse()<\/span> method.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Complete Project Details: https:\/\/RandomNerdTutorials.com\/raspberry-pi-pwm-python\/\r\n\r\nfrom gpiozero import PWMLED\r\nfrom signal import pause\r\n\r\nled = PWMLED(14)\r\n\r\n# pulse an LED forever\r\nled.pulse()\r\npause()<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/Raspberry-Pi\/pwm\/fade_led_pulse.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>You can pass the following parameters to the <span class=\"rnthl rntliteral\">pulse()<\/span> method:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>pulse(fade_in_time=1, fade_out_time=1, n=None, background=True)<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><span class=\"rnthl rntliteral\">fade_in_time<\/span>: number of seconds to spend fading in. The default is one second.<\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li><span class=\"rnthl rntliteral\">fade_out_time<\/span>: number of seconds to spend fading out. The default is one second.<\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li><span class=\"rnthl rntliteral\">n<\/span>: number of times to pulse. Set to <span class=\"rnthl rntliteral\">None<\/span> to run forever. <span class=\"rnthl rntliteral\">None<\/span> is the default value.<\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li><span class=\"rnthl rntliteral\">background<\/span>: if <span class=\"rnthl rntliteral\">True<\/span> (the default), start a background thread to continue pulsing and return immediately.<\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading\">blink()<\/h4>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">blink()<\/span> method of the <span class=\"rnthl rntliteral\">PWMLED<\/span> object can be either used to blink an LED or to fade in and out an LED. Here&#8217;s an example of how yo use the <span class=\"rnthl rntliteral\">blink()<\/span> method to fade an LED.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Complete Project Details: https:\/\/RandomNerdTutorials.com\/raspberry-pi-pwm-python\/\r\n\r\nfrom gpiozero import PWMLED\r\nfrom signal import pause\r\n\r\nled = PWMLED(14)\r\n\r\n#blink(on_time=1, off_time=1, fade_in_time=0, fade_out_time=0, n=None, background=True)\r\n# fading an LED forever\r\nled.blink(0, 0, 1, 1, None, True)\r\npause()\r\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/Raspberry-Pi\/pwm\/pulse_with_blink.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">blink()<\/span> method accepts the following arguments, with the following values as default:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>blink(on_time=1, off_time=1, fade_in_time=0, fade_out_time=0, n=None, background=True)<\/code><\/pre>\n\n\n\n<p>So, to fade the LED instead of blinking, you need to pass the following parameters:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>led.blink(0, 0, 1, 1, None, True)<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Wrapping Up<\/h2>\n\n\n\n<p>In this tutorial, you learned how to output PWM signals on the Raspberry Pi GPIOs using the <span class=\"rnthl rntliteral\">PWMLED<\/span> and <span class=\"rnthl rntliteral\">PWMOutputDevice<\/span> interfaces of the <span class=\"rnthl rntliteral\">gpiozero<\/span> library. We&#8217;ve also explored three different ways to fade in and out an LED.<\/p>\n\n\n\n<p>We hope you found this tutorial useful. If you&#8217;re new to the Raspberry Pi, I&#8217;m sure you&#8217;ll find the following tutorials useful:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-with-raspberry-pi\/\">Getting Started with Raspberry Pi<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pinout-gpios\/\">Raspberry Pi Pinout Guide: How to use the Raspberry Pi GPIOs?<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-digital-outputs-python\/\">Control Raspberry Pi Digital Outputs with Python (LED)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-remote-ssh-vs-code\/\">Programming Raspberry Pi Remotely using VS Code (Remote-SSH)<\/a><\/li>\n<\/ul>\n\n\n\n<p>You can check all our Raspberry Pi projects on the following link:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/projects-raspberry-pi\/\" title=\"\">Free Raspberry Pi Projects and Tutorials<\/a><\/li>\n<\/ul>\n\n\n\n<p>Thanks for reading.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this guide, you&#8217;ll learn how to generate PWM signals on the Raspberry Pi GPIOs. As an example, we&#8217;ll show you how to dim the brightness of an LED by &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"Raspberry Pi: PWM Outputs with Python (Fading LED)\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pwm-python\/#more-129523\" aria-label=\"Read more about Raspberry Pi: PWM Outputs with Python (Fading LED)\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":5,"featured_media":129853,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[301,264,268,190],"tags":[],"class_list":["post-129523","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-0-raspberrypi","category-project","category-raspberry-pi-project","category-raspberry-pi"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Raspberry-Pi-PWM-output.jpg?fit=1280%2C720&quality=100&strip=all&ssl=1","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/129523","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/comments?post=129523"}],"version-history":[{"count":24,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/129523\/revisions"}],"predecessor-version":[{"id":133372,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/129523\/revisions\/133372"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/129853"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=129523"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=129523"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=129523"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}