raspberrypi / pico-sdk

BSD 3-Clause "New" or "Revised" License
3.26k stars 838 forks source link

Can not setup PWM on ADC pin. #1614

Closed phb98 closed 1 month ago

phb98 commented 5 months ago

Hello. I am trying to output a 2khz PWM on GPIO 28 and 29, which is also ADC pin. But after setting up the gpio there is nothing on GPIO, it stuck at low(or floating, since the PWM is going to Gate of power mosfer, which is being pulled low). Trying below code with non-ADC pin and it works fine. Did i miss anything when config it. Thanks


static void pwm_pin_setup(uint16_t pin)
{
  #define MCU_CLOCK (125000000.0) // 125MHz

  // Set GPIO function to PWM
  gpio_set_function(pin, GPIO_FUNC_PWM);

  // Find out which PWM slice is connected to the given pin
  uint16_t slice_num = pwm_gpio_to_slice_num(pin);
  uint16_t wrap_val = OUTPUT_MCU_PWM_MAX_VAL;

  // Calculate clock divider
  float clk_div = (MCU_CLOCK / (float)CONFIG_MCU_PWM_FREQ) / (float)(OUTPUT_MCU_PWM_MAX_VAL + 1);

  // Check if the calculated clock divider is within valid range
  if (clk_div > 256.0 || clk_div < 1.0)
  {
    CONSOLE_LOG_ERROR("Cannot calculate PWM clock divider, setting default clock to 1kHz");
    clk_div = (MCU_CLOCK / 1000.0) / (float)(OUTPUT_MCU_PWM_MAX_VAL + 1);
  }

  // Log information about the PWM setup
  CONSOLE_LOG_VERBOSE("Pin:%d, PWM slice:%d, PWM channel:%d", pin, pwm_gpio_to_slice_num(pin), pwm_gpio_to_channel(pin));
  CONSOLE_LOG_VERBOSE("PWM clock divider:%f, Wrap value:%d", clk_div, wrap_val);

  // Set PWM clock divider and wrap value
  pwm_set_clkdiv(slice_num, clk_div);
  pwm_set_wrap(slice_num, wrap_val);

  // Set default output to 50% duty cycle
  pwm_set_gpio_level(pin, wrap_val / 2);

  // Enable PWM
  pwm_set_enabled(slice_num, true);
}
kilograham commented 1 month ago

please post questions here https://forums.raspberrypi.com/viewforum.php?f=143