Skip to content

Instantly share code, notes, and snippets.

@benevpi
Created January 14, 2021 11:21
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benevpi/845e5dc432f05b6160ed56fc6f3b4032 to your computer and use it in GitHub Desktop.
Save benevpi/845e5dc432f05b6160ed56fc6f3b4032 to your computer and use it in GitHub Desktop.
# Example of using PIO for PWM, and fading the brightness of an LED
# for a more wrapped-up examples, see https://github.com/raspberrypi/pico-micropython-examples/blob/master/pio/pio_pwm.py
from machine import Pin
from rp2 import PIO, StateMachine, asm_pio
from time import sleep
max_count = 500
@asm_pio(sideset_init=PIO.OUT_LOW)
def pwm_prog():
pull(noblock) .side(0)
mov(x, osr) # Keep most recent pull data stashed in X, for recycling by noblock
mov(y, isr) # ISR must be preloaded with PWM count max
label("pwmloop")
jmp(x_not_y, "skip")
nop() .side(1)
label("skip")
jmp(y_dec, "pwmloop")
pwm_sm = StateMachine(0, pwm_prog, freq=10000000, sideset_base=Pin(25))
pwm_sm.put(max_count)
pwm_sm.exec("pull()")
pwm_sm.exec("mov(isr, osr)")
pwm_sm.active(1)
while True:
for i in range(500):
pwm_sm.put(i)
sleep(0.001)
@kevinjwalters
Copy link

Would you recommend 10MHz as a good general frequency for PWM for an LED?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment