soft_pwm.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import utime
  2. from hwconfig import LED
  3. # Using sleep_ms() gives pretty poor PWM resolution and
  4. # brightness control, but we use it in the attempt to
  5. # make this demo portable to even more boards (e.g. to
  6. # those which don't provide sleep_us(), or provide, but
  7. # it's not precise, like would be on non realtime OSes).
  8. # We otherwise use 20ms period, to make frequency not less
  9. # than 50Hz to avoid visible flickering (you may still see
  10. # if you're unlucky).
  11. def pwm_cycle(led, duty, cycles):
  12. duty_off = 20 - duty
  13. for i in range(cycles):
  14. if duty:
  15. led.on()
  16. utime.sleep_ms(duty)
  17. if duty_off:
  18. led.off()
  19. utime.sleep_ms(duty_off)
  20. # At the duty setting of 1, an LED is still pretty bright, then
  21. # at duty 0, it's off. This makes rather unsmooth transition, and
  22. # breaks fade effect. So, we avoid value of 0 and oscillate between
  23. # 1 and 20. Actually, highest values like 19 and 20 are also
  24. # barely distinguishible (like, both of them too bright and burn
  25. # your eye). So, improvement to the visible effect would be to use
  26. # more steps (at least 10x), and then higher frequency, and use
  27. # range which includes 1 but excludes values at the top.
  28. while True:
  29. # Fade in
  30. for i in range(1, 21):
  31. pwm_cycle(LED, i, 2)
  32. # Fade out
  33. for i in range(20, 0, -1):
  34. pwm_cycle(LED, i, 2)