{"id":132513,"date":"2023-08-24T09:56:29","date_gmt":"2023-08-24T09:56:29","guid":{"rendered":"https:\/\/randomnerdtutorials.com\/?p=132513"},"modified":"2024-05-06T10:55:58","modified_gmt":"2024-05-06T10:55:58","slug":"raspberry-pi-pico-pwm-micropython","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-pwm-micropython\/","title":{"rendered":"Raspberry Pi Pico: PWM Fading an LED (MicroPython)"},"content":{"rendered":"\n<p>Learn how to generate PWM signals with the Raspberry Pi Pico using MicroPython firmware. As an example, we\u2019ll show you how to dim the brightness of an LED by changing the duty cycle over time.<\/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\/06\/Raspberry-Pi-Pico-PWM-MicroPython.jpg?resize=1200%2C675&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico PWM with MicroPython Fading LED\" class=\"wp-image-132553\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/Raspberry-Pi-Pico-PWM-MicroPython.jpg?w=1280&amp;quality=100&amp;strip=all&amp;ssl=1 1280w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/Raspberry-Pi-Pico-PWM-MicroPython.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/Raspberry-Pi-Pico-PWM-MicroPython.jpg?resize=1024%2C576&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/Raspberry-Pi-Pico-PWM-MicroPython.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<p class=\"rntbox rntclgreen\">We have a similar guide using <strong>Arduino IDE<\/strong>: <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-pwm-analogwrite-arduino\/\">Raspberry Pi Pico: Fading an LED using PWM (Arduino IDE)<\/a>.<\/p>\n\n\n\n<p><strong>Table of Contents<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"#prerequisites\" title=\"\">Install and Run MicroPython on the Raspberry Pi Pico<\/a><\/li>\n\n\n\n<li><a href=\"#introducing-pwm\" title=\"\">Introducing PWM<\/a><\/li>\n\n\n\n<li><a href=\"#rpi-pico-pwm-gpios\" title=\"\">Raspberry Pi Pico GPIOs and PWM<\/a><\/li>\n\n\n\n<li><a href=\"#pwm-machine-class\" title=\"\">The machine.PWM class<\/a><\/li>\n\n\n\n<li><a href=\"#fade-led-code-rpi-pico\" title=\"\">Fading an LED &#8211; MicroPython Script<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"prerequisites\">Prerequisites<\/h2>\n\n\n\n<p>To follow this tutorial you need MicroPython firmware installed in your Raspberry Pi Pico board. You also need an IDE to write and upload the code to your board. <\/p>\n\n\n\n<p>The recommended MicroPython IDE for the Raspberry Pi Pico is Thonny IDE. Follow the next tutorial to learn how to install Thonny IDE, flash MicroPython firmware, and upload code to the board.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-raspberry-pi-pico-w\/#install-thonny-ide\" title=\"\">Programming Raspberry Pi Pico using MicroPython<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"introducing-pwm\">Introducing PWM (Pulse-Width Modulation)<\/h2>\n\n\n\n<p>PWM, or Pulse Width Modulation, is a technique that controls the power delivered to devices. It achieves this by turning the power on and off very quickly. <\/p>\n\n\n\n<p>For example, 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=\"Fading LED example PWM Pulse-Width Modulation\" 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 refers to the percentage of time the power is on compared to the total time of the on-off cycle\u2014take a look at the following diagram.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" 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 PWM works Pulse-Width Modulation\" 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\" \/><\/figure><\/div>\n\n\n<p>By adjusting the duty cycle, we can control the average power delivered to the device. For instance, a higher duty cycle means the device receives more power, while a lower duty cycle results in less power. This enables us to control things like brightness in LEDs, speed in motors, or volume in speakers.<\/p>\n\n\n\n<p>For example, 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<h2 class=\"wp-block-heading\" id=\"rpi-pico-pwm-gpios\">Raspberry Pi Pico GPIOs<\/h2>\n\n\n\n<p>The Raspberry Pi Pico comes with 40 pins, 26 of which are programmable GPIOs that you can use to connect peripherals. All Raspberry Pi Pico GPIOs can output PWM signals\u2014they are marked in the diagrams in light green color.<\/p>\n\n\n\n<p>You can use the following pinouts as a reference to identify and locate each GPIO on your board. The pinout is slightly different for the Pico and Pico W.<\/p>\n\n\n\n<p>The following picture shows the Raspberry Pi Pico pinout (which functions are supported by each pin).<\/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=\"842\" height=\"642\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/05\/Raspberry-Pi-Pico-pinout.png?resize=842%2C642&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico Pinout\" class=\"wp-image-130916\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/05\/Raspberry-Pi-Pico-pinout.png?w=842&amp;quality=100&amp;strip=all&amp;ssl=1 842w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/05\/Raspberry-Pi-Pico-pinout.png?resize=300%2C229&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/05\/Raspberry-Pi-Pico-pinout.png?resize=768%2C586&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 842px) 100vw, 842px\" \/><figcaption class=\"wp-element-caption\">Image source: <a href=\"https:\/\/raspberrypi.com\" target=\"_blank\" rel=\"noopener\" title=\"\">raspberrypi.com<\/a><\/figcaption><\/figure><\/div>\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"861\" height=\"620\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/05\/Raspberry-Pi-Pico-W-Pinout.png?resize=861%2C620&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico W pinout\" class=\"wp-image-130917\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/05\/Raspberry-Pi-Pico-W-Pinout.png?w=861&amp;quality=100&amp;strip=all&amp;ssl=1 861w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/05\/Raspberry-Pi-Pico-W-Pinout.png?resize=300%2C216&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/05\/Raspberry-Pi-Pico-W-Pinout.png?resize=768%2C553&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 861px) 100vw, 861px\" \/><\/figure><\/div>\n\n\n<p>The pins marked in red are power pins that output 3.3V. The black pins are GND pins. All pins in light green can be used as &#8220;regular&#8221; GPIOs (input and output).<\/p>\n\n\n\n<p class=\"rntbox rntclgreen\">To learn more about the Pico Pinout, read the following guide:&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-w-pinout-gpios\/\">Raspberry Pi Pico and Pico W Pinout Guide: GPIOs Explained<\/a>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Raspberry Pi Pico &#8211; PWM Channels<\/h3>\n\n\n\n<p>The Raspberry Pi Pico has <strong>8 independent PWM generators<\/strong> called slices. Each slice has two channels, which makes a total of <strong>16 PWM channels<\/strong>. <\/p>\n\n\n\n<p>The frequency of the PWM signal can range between 8Hz and 62.5MHz, while the microcontroller is running at a frequency of 125MHz.<\/p>\n\n\n\n<p>Two channels of the same slice run at the same frequency, but can have a different duty rate.&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"pwm-machine-class\">The machine.PWM class<\/h2>\n\n\n\n<p>To handle PWM signals with the Raspberry Pi Pico using MicroPython, use the <span class=\"rnthl rntliteral\">machine.PWM<\/span> class. After creating a <span class=\"rnthl rntliteral\">PWM<\/span> object, called <span class=\"rnthl rntliteral\">led_pwm<\/span> for example:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>led_pwm = PWM(Pin(20))<\/code><\/pre>\n\n\n\n<p>You can use the following methods:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><span class=\"rnthl rntliteral\">led_pwm.freq(FREQUENCY)<\/span> to set the frequency of the PWM signal.<\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li><span class=\"rnthl rntliteral\">led_pwm.duty_u16(DUTY_CYCLE)<\/span> to set the duty cycle. It should be a value between 0 and 65535 (16-bit)<\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li><span class=\"rnthl rntliteral\">led_pwm.deinit()<\/span> to turn off PWM on the PWM slice used by the LED (in this example, it&#8217;s GPIO 20, so it will also stop PWM on GPIO 21 because they belong to the same PWM slice).<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Schematic<\/h2>\n\n\n\n<p>Now, let&#8217;s create an example to better understand those PWM concepts. We&#8217;ll create a simple example to dim an LED (increase and decrease brightness smoothly).<\/p>\n\n\n\n<p>Before proceeding, connect an LED to the Raspberry Pi Pico. We&#8217;re connecting to GPIO 20, but you can use any other GPIO.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Parts Required<\/h3>\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=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/Raspberry-Pi-Pico-LED-breadboard.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico LED PWM\" class=\"wp-image-132548\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/Raspberry-Pi-Pico-LED-breadboard.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/Raspberry-Pi-Pico-LED-breadboard.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>Here\u2019s a list of the parts you need to build the circuit:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/raspberry-pi-pico-w\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Raspberry Pi Pico<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/3mm-5mm-leds-kit-storage-box\/\" target=\"_blank\" rel=\"noopener\" title=\"\">5 mm LED<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/resistors-kits\/\" target=\"_blank\" rel=\"noopener\" title=\"\">330 Ohm resistor<\/a><\/li>\n\n\n\n<li><a rel=\"noreferrer noopener\" href=\"https:\/\/makeradvisor.com\/tools\/mb-102-solderless-breadboard-830-points\/\" target=\"_blank\">Breadboard<\/a><\/li>\n\n\n\n<li><a rel=\"noreferrer noopener\" href=\"https:\/\/makeradvisor.com\/tools\/jumper-wires-kit-120-pieces\/\" target=\"_blank\">Jumper wires<\/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\n<h3 class=\"wp-block-heading\">Schematic \u2013 Raspberry Pi Pico<\/h3>\n\n\n\n<p>You can use the following diagram as a reference to connect the LED to the Raspberry Pi Pico board.<\/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=\"500\" height=\"681\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/raspberry-pi-pico-led-gpio20_bb.jpg?resize=500%2C681&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico LED connected to GPIO 20 diagram\" class=\"wp-image-132546\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/raspberry-pi-pico-led-gpio20_bb.jpg?w=500&amp;quality=100&amp;strip=all&amp;ssl=1 500w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/raspberry-pi-pico-led-gpio20_bb.jpg?resize=220%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 220w\" sizes=\"(max-width: 500px) 100vw, 500px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"fade-led-code-rpi-pico\">Script &#8211; RPi Pico Fading an LED<\/h2>\n\n\n\n<p>The following code creates a PWM signal on GPIO 20 and increases and decreases the duty cycle over time to dim the LED.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Complete project details at https:\/\/RandomNerdTutorials.com\/raspberry-pi-pico-pwm-micropython\/\nfrom machine import Pin, PWM\nfrom time import sleep\n\n# Set up PWM Pin\nled = machine.Pin(20)\nled_pwm = PWM(led)\nduty_step = 129  # Step size for changing the duty cycle\n\n#Set PWM frequency\nfrequency = 5000\nled_pwm.freq (frequency)\n\ntry:\n    while True:\n      # Increase the duty cycle gradually\n      for duty_cycle in range(0, 65536, duty_step):\n        led_pwm.duty_u16(duty_cycle)\n        sleep(0.005)\n        \n      # Decrease the duty cycle gradually\n      for duty_cycle in range(65536, 0, -duty_step):\n        led_pwm.duty_u16(duty_cycle)\n        sleep(0.005)\n        \nexcept KeyboardInterrupt:\n    print(&quot;Keyboard interrupt&quot;)\n    led_pwm.duty_u16(0)\n    print(led_pwm)\n    led_pwm.deinit()\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-Pico\/MicroPython\/main_PWM_Fade_LED.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How the code works<\/h3>\n\n\n\n<p>To create a PWM pin, import the <span class=\"rnthl rntliteral\">PWM<\/span> class in addition to the <span class=\"rnthl rntliteral\">Pin<\/span> class from the <span class=\"rnthl rntliteral\">machine<\/span> module.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>from machine import Pin, PWM<\/code><\/pre>\n\n\n\n<p>You also need to import the <span class=\"rnthl rntliteral\">sleep<\/span> function from the <span class=\"rnthl rntliteral\">time<\/span> module to add delays to the code.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>from time import sleep<\/code><\/pre>\n\n\n\n<p>First, create a <span class=\"rnthl rntliteral\">Pin<\/span> object on the GPIO of your choice. In this case, we&#8217;re using GPIO 20.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>led = machine.Pin(20)<\/code><\/pre>\n\n\n\n<p>Then, create a <span class=\"rnthl rntliteral\">PWM<\/span> object on that pin, called <span class=\"rnthl rntliteral\">led_pwm<\/span> as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>led_pwm = PWM(led)<\/code><\/pre>\n\n\n\n<p>Set the duty cycle step\u2014lower values result in smoother and slower transitions while higher values result in more abrupt and rapid changes. We&#8217;re using the value 129, because it is an integer divisor of 65535.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>duty_step = 129  # Step size for changing the duty cycle<\/code><\/pre>\n\n\n\n<p>Note: The duty cycle can be a value between 0 and 65535 (16-bit). Which 65535 corresponds to 100% duty cycle (full brightness), and 0 corresponds to 0% duty cycle (unlit LED).<\/p>\n\n\n\n<p>Set the frequency of the signal. We&#8217;re using a 5000Hz frequency, but you can choose a different value. The frequency can be a value between 0 and 62500.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>#Set PWM frequency\nfrequency = 5000\nled_pwm.freq (frequency)<\/code><\/pre>\n\n\n\n<p>To set the duty cycle use the <span class=\"rnthl rntliteral\">duty_16()<\/span> method on the <span class=\"rnthl rntliteral\">PWM<\/span> object and pass the duty cycle as an argument:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>led.duty(duty_cycle)<\/code><\/pre>\n\n\n\n<p>Inside the <span class=\"rnthl rntliteral\">while<\/span> loop, we create a <span class=\"rnthl rntliteral\">for<\/span> loop that increases the duty cycle by 129 in each loop with an interval of 5 ms between each change.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>for duty_cycle in range(0, 65536, duty_step):\n    led_pwm.duty_u16(duty_cycle)\n    sleep(0.005)<\/code><\/pre>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">range()<\/span> function has the following syntax:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>range(start, stop, step)<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Start<\/strong>: a number that specifies at which position to start. We want to start with 0 duty cycle;<\/li>\n\n\n\n<li><strong>Stop<\/strong>: a number that specifies at which position we want to stop, excluding that value. The maximum duty cycle is 65535. So, we use 65535 +1, which is 65536.<\/li>\n\n\n\n<li><strong>Step<\/strong>: an integer number that specifies the incrementation. By default, incrementation is 1.<\/li>\n<\/ul>\n\n\n\n<p>In each for loop, we set the LED\u2019s duty cycle to the current <span class=\"rnthl rntliteral\">duty_cycle<\/span> value:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code> led_pwm.duty_u16(duty_cycle)<\/code><\/pre>\n\n\n\n<p>After that, the <span class=\"rnthl rntliteral\">duty_cycle<\/span> variable is incremented by the step you specified.<\/p>\n\n\n\n<p>When the duty cycle reaches full brightness, we decrease the brightness gradually in a similar way.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Decrease the duty cycle gradually\nfor duty_cycle in range(65536, 0, -duty_step):\n    led_pwm.duty_u16(duty_cycle)\n    sleep(0.005)<\/code><\/pre>\n\n\n\n<p>Notice that we use <span class=\"rnthl rntliteral\">try<\/span> and <span class=\"rnthl rntliteral\">except<\/span> statements in this example.<\/p>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">try<\/span> block encloses the code that we want to run.<\/p>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">except<\/span> block is executed if a specific error occurs within the <span class=\"rnthl rntliteral\">try<\/span> block. In this case, it catches the <span class=\"rnthl rntliteral\">KeyboardInterrupt<\/span> error, which is raised when the user interrupts the program by pressing Ctrl+C in the terminal or stops the program in the IDE. When this error is detected, the code within the <span class=\"rnthl rntliteral\">except<\/span> block is executed.<\/p>\n\n\n\n<p>In the <span class=\"rnthl rntliteral\">except<\/span> block, we set the duty cycle of the LED to 0 (fully off) using <span class=\"rnthl rntliteral\">led.duty_u16(0)<\/span> and call the <span class=\"rnthl rntliteral\">led.deinit()<\/span> to turn off PWM.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>except KeyboardInterrupt:\n    print(\"Keyboard interrupt\")\n    led_pwm.duty_u16(0)\n    print(led_pwm)\n    led_pwm.deinit()<\/code><\/pre>\n\n\n\n<p>This ensures that the LED is properly turned off and any necessary cleanup is performed, even if the program is interrupted by the user.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Demonstration<\/h2>\n\n\n\n<p>Save the code to your Raspberry Pi Pico board using <a href=\"https:\/\/randomnerdtutorials.com\/getting-started-raspberry-pi-pico-w\/#install-thonny-ide\">Thonny IDE<\/a> or any other MicroPython IDE of your choice.<\/p>\n\n\n\n<p>Follow the next instructions if you&#8217;re using Thonny IDE.<\/p>\n\n\n\n<p>Copy the code provided to the Thonny IDE untitled file.<\/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=\"679\" height=\"663\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/fade-led-thonny-ide-micropython-raspberry-pi-pico.png?resize=679%2C663&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Thonny IDE PWM Fade LED MicroPython Raspberry Pi Pico\" class=\"wp-image-132531\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/fade-led-thonny-ide-micropython-raspberry-pi-pico.png?w=679&amp;quality=100&amp;strip=all&amp;ssl=1 679w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/fade-led-thonny-ide-micropython-raspberry-pi-pico.png?resize=300%2C293&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 679px) 100vw, 679px\" \/><\/figure><\/div>\n\n\n<p>With the code copied to the file, click on the&nbsp;<strong>Save&nbsp;<\/strong>icon. Then, select&nbsp;<strong>Raspberry Pi Pico<\/strong>.<\/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=\"214\" height=\"203\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/05\/Save-file-to-Raspberry-Pi-Pico.png?resize=214%2C203&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Saving file to Raspberry Pi Pico MicroPython IDE\" class=\"wp-image-130899\"\/><\/figure><\/div>\n\n\n<p>Save the file with the following name:&nbsp;<strong>main.py<\/strong>. Overwrite any existing files with the same name.<\/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=\"545\" height=\"327\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/micropython-main-py-file.png?resize=545%2C327&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"micropython main.py file\" class=\"wp-image-132452\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/micropython-main-py-file.png?w=545&amp;quality=100&amp;strip=all&amp;ssl=1 545w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/micropython-main-py-file.png?resize=300%2C180&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 545px) 100vw, 545px\" \/><\/figure><\/div>\n\n\n<p><strong>Note:<\/strong> When you name a file <span class=\"rnthl rntliteral\">main.py<\/span>, the Raspberry Pi Pico will run that file automatically on boot. If you call it a different name, it will still be saved on the board filesystem, but it will not run automatically on boot.<\/p>\n\n\n\n<p>Reset your board (unplug and plug it into your computer). Click the little green button &#8220;Run Current Script&#8221; or press F5.<\/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=\"450\" height=\"78\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/thonny-ide-run-code.png?resize=450%2C78&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"micropython main.py file run command script\" class=\"wp-image-132505\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/thonny-ide-run-code.png?w=450&amp;quality=100&amp;strip=all&amp;ssl=1 450w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/thonny-ide-run-code.png?resize=300%2C52&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 450px) 100vw, 450px\" \/><\/figure><\/div>\n\n\n<p>Notice that the LED connected to GPIO 20 will start &#8220;breathing&#8221;, it will increase and decrease brightness over time gradually.<\/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:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/Raspberry-Pi-Pico-LED-PWM0.jpg?resize=422%2C422&#038;strip=info&#038;ssl=1 422w\" alt=\"\" data-height=\"422\" data-id=\"132549\" data-link=\"https:\/\/randomnerdtutorials.com\/?attachment_id=132549#main\" data-url=\"https:\/\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/Raspberry-Pi-Pico-LED-PWM0.jpg\" data-width=\"750\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/Raspberry-Pi-Pico-LED-PWM0.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:\/\/i1.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/Raspberry-Pi-Pico-LED-PWM1.jpg?resize=422%2C422&#038;strip=info&#038;ssl=1 422w\" alt=\"\" data-height=\"422\" data-id=\"132551\" data-link=\"https:\/\/randomnerdtutorials.com\/?attachment_id=132551#main\" data-url=\"https:\/\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/Raspberry-Pi-Pico-LED-PWM1.jpg\" data-width=\"750\" src=\"https:\/\/i1.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/Raspberry-Pi-Pico-LED-PWM1.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:\/\/i1.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/Raspberry-Pi-Pico-LED-PWM2.jpg?resize=422%2C422&#038;strip=info&#038;ssl=1 422w\" alt=\"\" data-height=\"422\" data-id=\"132550\" data-link=\"https:\/\/randomnerdtutorials.com\/?attachment_id=132550#main\" data-url=\"https:\/\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/Raspberry-Pi-Pico-LED-PWM2.jpg\" data-width=\"750\" src=\"https:\/\/i1.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/Raspberry-Pi-Pico-LED-PWM2.jpg?ssl=1&amp;resize=422%2C422\" data-amp-layout=\"responsive\"\/><\/figure><\/div><\/div><\/div><\/div>\n\n\n\n<p>You can stop the execution of the program by pressing&nbsp;<strong>CTRL<\/strong>+<strong>C<\/strong> or by clicking on the STOP button. Notice that the LED will turn off, and a message will be printed on the Terminal shell.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Wrapping Up<\/h2>\n\n\n\n<p>To wrap up, to output PWM signals on the Raspberry Pi Pico GPIOs, we can use the <span class=\"rnthl rntliteral\">machine.PWM<\/span> class. First, you create a <span class=\"rnthl rntliteral\">PWM<\/span> object on a GPIO of your choice. After that, you can use the <span class=\"rnthl rntliteral\">freq()<\/span>, <span class=\"rnthl rntliteral\">duty_u16<\/span> and <span class=\"rnthl rntliteral\">deinit()<\/span> methods on the <span class=\"rnthl rntliteral\">PWM<\/span> object, to set the PWM frequency, duty cycle, and stop PWM, respectively.<\/p>\n\n\n\n<p>Learn more about the Raspberry Pi Pico with our eBook:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-w-micropython-ebook\/\" title=\"\">Learn Raspberry Pi Pico with MicroPython (eBook)<\/a><\/li>\n<\/ul>\n\n\n\n<p>We hope you&#8217;ve found this tutorial useful. If you&#8217;re just getting started with the Raspberry Pi Pico, make sure you read our getting started guides:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-raspberry-pi-pico-w\/?preview=true&amp;_thumbnail_id=130915\" title=\"\">Getting Started with Raspberry Pi Pico (and Pico W)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-w-pinout-gpios\/\">Raspberry Pi Pico and Pico W Pinout Guide: GPIOs Explained<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-outputs-inputs-micropython\/\">Raspberry Pi Pico: Control Digital Outputs and Read Digital Inputs (MicroPython)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-analog-inputs-micropython\/\">Raspberry Pi Pico: Read Analog Inputs (MicroPython)<\/a><\/li>\n<\/ul>\n\n\n\n<p><a href=\"https:\/\/randomnerdtutorials.com\/projects-raspberry-pi-pico\/\">Check out all our Raspberry Pi Pico Guides \u00bb<\/a><\/p>\n\n\n\n<p>If you prefer to program the Raspberry Pi Pico using Arduino IDE, you can get started with the following tutorial:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/programming-raspberry-pi-pico-w-arduino-ide\/\" title=\"\">Programming Raspberry Pi Pico with Arduino IDE<\/a><\/li>\n<\/ul>\n\n\n\n<p>Thanks for reading.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn how to generate PWM signals with the Raspberry Pi Pico using MicroPython firmware. As an example, we\u2019ll show you how to dim the brightness of an LED by changing &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"Raspberry Pi Pico: PWM Fading an LED (MicroPython)\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-pwm-micropython\/#more-132513\" aria-label=\"Read more about Raspberry Pi Pico: PWM Fading an LED (MicroPython)\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":5,"featured_media":132553,"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":[324,326],"tags":[],"class_list":["post-132513","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-raspberry-pi-pico","category-raspberry-pi-pico-micropython"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/Raspberry-Pi-Pico-PWM-MicroPython.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\/132513","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=132513"}],"version-history":[{"count":21,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/132513\/revisions"}],"predecessor-version":[{"id":154874,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/132513\/revisions\/154874"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/132553"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=132513"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=132513"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=132513"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}