creat1001

RP2040 SDK PWM example Take 2

Feb 7th, 2021 (edited)
1,063
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.17 KB | None | 0 0
  1. /*
  2.     Raspberry Pi Pico PWM example
  3.  
  4.     Scott Beasley (2021) No Copyright.
  5.  
  6.     Code used by Damien P. George Copyright (c) 2020
  7.     From the RPI Pico MicroPython project. See below for copyright info.
  8.     https://github.com/raspberrypi/micropython/blob/pico/ports/rp2/machine_pwm.c
  9. */
  10.  
  11. #include "pico/stdlib.h"
  12. #include <stdio.h>
  13. #include "pico/time.h"
  14. #include "hardware/pwm.h"
  15. #include "hardware/clocks.h"
  16.  
  17. #define LED_PIN 25
  18. #define PWM_PIN 16
  19. #define DUTY_50_PCT 32767
  20. #define PWM_1KHZ 62500  // Wrap val for 1khz at SYSCLK / 2
  21. // Not worring about less than 1k for now.
  22.  
  23. int set_pwm_duty (uint slice, uint channel, uint32_t top, uint32_t duty);
  24.  
  25. int main (void)
  26. {
  27.     uint32_t div = 0, top = 0;
  28.     uint slice_num, channel;
  29.  
  30.     // Use the LED for error notifications
  31.     gpio_init (LED_PIN);
  32.     gpio_set_dir (LED_PIN, GPIO_OUT);
  33.  
  34.     slice_num = pwm_gpio_to_slice_num (PWM_PIN);
  35.     channel = pwm_gpio_to_channel (PWM_PIN);
  36.     gpio_set_function (PWM_PIN, GPIO_FUNC_PWM);
  37.  
  38.     // Div the sys clock by 2
  39.     pwm_set_clkdiv (slice_num, (float)2 * 1.0f);
  40.  
  41.     // Set the PWM counter wrap value to reset on
  42.     top = PWM_1KHZ / 50;  // Set for 50khz freq - Close to it anyway.
  43.     pwm_set_wrap (slice_num, top);
  44.  
  45.     while (1) {
  46.         tight_loop_contents ( );
  47.         set_pwm_duty (slice_num, channel, top, (uint32_t)DUTY_50_PCT);
  48.         sleep_ms(2000);
  49.         set_pwm_duty (slice_num, channel, top, (uint32_t)DUTY_50_PCT / 2);
  50.         sleep_ms(2000);
  51.         set_pwm_duty (slice_num, channel, top, (uint32_t)DUTY_50_PCT / 4);
  52.         sleep_ms(2000);
  53.         set_pwm_duty (slice_num, channel, top, (uint32_t)DUTY_50_PCT / 6);
  54.         sleep_ms(2000);
  55.     }
  56. }
  57.  
  58. // Code used from https://github.com/raspberrypi/micropython/blob/pico/ports/rp2/machine_pwm.c
  59. // Function - machine_pwm_duty_u16
  60. // Shaped for my needs (Scott Beasley) No Copyright.
  61. // MIT License (MIT) Damien P. George Copyright (c) 2020
  62. int set_pwm_duty (uint slice, uint channel, uint32_t top, uint32_t duty)
  63. {
  64.     // Set duty cycle.
  65.     uint32_t cc = duty * (top + 1) / 65535;
  66.     pwm_set_chan_level (slice, channel, cc);
  67.     pwm_set_enabled (slice, true);
  68.  
  69.     return 0;
  70. }
  71.  
  72.  
  73.  
Add Comment
Please, Sign In to add comment