0
0
Iot-protocolsHow-ToBeginner · 4 min read

How to Use PWM on Raspberry Pi Pico: Simple Guide

To use PWM on Raspberry Pi Pico, import the machine module, create a PWM object on a GPIO pin, and set its frequency and duty cycle. The duty cycle controls the signal's power by adjusting the percentage of time the signal is high.
📐

Syntax

Here is the basic syntax to create and control PWM on Raspberry Pi Pico using MicroPython:

  • machine.PWM(pin): Create a PWM object on a specified pin.
  • pwm.freq(frequency): Set the PWM frequency in Hertz.
  • pwm.duty_u16(value): Set the duty cycle using a 16-bit value (0 to 65535).
  • pwm.deinit(): Stop the PWM signal.
python
from machine import Pin, PWM

pwm = PWM(Pin(15))  # Create PWM on GPIO15
pwm.freq(1000)      # Set frequency to 1000 Hz
pwm.duty_u16(32768) # Set duty cycle to 50% (half of 65535)

# To stop PWM
# pwm.deinit()
💻

Example

This example shows how to blink an LED connected to GPIO 15 with varying brightness using PWM. The duty cycle changes gradually to fade the LED in and out.

python
from machine import Pin, PWM
import time

led = PWM(Pin(15))
led.freq(1000)  # 1 kHz frequency

try:
    while True:
        # Fade in
        for duty in range(0, 65536, 1000):
            led.duty_u16(duty)
            time.sleep(0.01)
        # Fade out
        for duty in range(65535, -1, -1000):
            led.duty_u16(duty)
            time.sleep(0.01)
except KeyboardInterrupt:
    led.deinit()  # Stop PWM when interrupted
Output
LED connected to GPIO15 will smoothly fade in and out repeatedly until stopped.
⚠️

Common Pitfalls

Some common mistakes when using PWM on Raspberry Pi Pico include:

  • Not setting the frequency before the duty cycle, which can cause unexpected behavior.
  • Using duty() instead of duty_u16() in MicroPython on Pico, which expects 16-bit values.
  • Forgetting to call deinit() to stop PWM, which can leave the pin in PWM mode.
  • Using pins that do not support PWM (check Pico pinout).
python
from machine import Pin, PWM

# Wrong: Using duty() instead of duty_u16()
pwm = PWM(Pin(15))
pwm.freq(1000)
# pwm.duty(512)  # This will cause error on Pico

# Correct:
pwm.duty_u16(32768)  # 50% duty cycle
📊

Quick Reference

FunctionDescriptionExample
PWM(pin)Create PWM on a GPIO pinpwm = PWM(Pin(15))
freq(frequency)Set PWM frequency in Hzpwm.freq(1000)
duty_u16(value)Set duty cycle (0-65535)pwm.duty_u16(32768)
deinit()Stop PWM signalpwm.deinit()

Key Takeaways

Use machine.PWM with a Pin to create PWM on Raspberry Pi Pico.
Set frequency first, then duty cycle with duty_u16 (0 to 65535).
Call deinit() to stop PWM and free the pin.
Only certain GPIO pins support PWM; check the Pico pinout.
Avoid using duty() method; use duty_u16() for correct duty cycle.