|
| 1 | +// SPDX-License-Identifier: MIT |
| 2 | +// Copyright (c) 2026 The Pybricks Authors |
| 3 | + |
| 4 | +#include <pbdrv/config.h> |
| 5 | + |
| 6 | +#if PBDRV_CONFIG_PWM_PICO |
| 7 | + |
| 8 | +#include <pbdrv/pwm.h> |
| 9 | +#include <pbdrv/gpio.h> |
| 10 | +#include <pbio/error.h> |
| 11 | + |
| 12 | +#include "../drv/pwm/pwm.h" |
| 13 | +#include "../drv/pwm/pwm_pico.h" |
| 14 | +#include "../../drv/led/led_pwm.h" |
| 15 | + |
| 16 | +#include "hardware/gpio.h" |
| 17 | +#include "hardware/pwm.h" |
| 18 | + |
| 19 | +static pbio_error_t pbdrv_pwm_pico_set_duty(pbdrv_pwm_dev_t *dev, uint32_t ch, uint32_t value) { |
| 20 | + // Blue not available. |
| 21 | + if (ch == PBDRV_LED_PWM_CHANNEL_INVALID) { |
| 22 | + return PBIO_SUCCESS; |
| 23 | + } |
| 24 | + |
| 25 | + if (ch >= PBDRV_CONFIG_PWM_PICO_NUM_CHANNELS) { |
| 26 | + return PBIO_ERROR_INVALID_ARG; |
| 27 | + } |
| 28 | + |
| 29 | + const pbdrv_pwm_pico_platform_data_t *pdata = dev->pdata; |
| 30 | + const pbdrv_pwm_pico_channel_t *channel = &pdata->channels[ch]; |
| 31 | + |
| 32 | + pwm_set_gpio_level(channel->gpio, value); |
| 33 | + |
| 34 | + return PBIO_SUCCESS; |
| 35 | +} |
| 36 | + |
| 37 | +static const pbdrv_pwm_driver_funcs_t pbdrv_pwm_pico_funcs = { |
| 38 | + .set_duty = pbdrv_pwm_pico_set_duty, |
| 39 | +}; |
| 40 | + |
| 41 | +void pbdrv_pwm_pico_init(pbdrv_pwm_dev_t *devs) { |
| 42 | + const pbdrv_pwm_pico_platform_data_t *pdata = &pbdrv_pwm_pico_platform_data; |
| 43 | + |
| 44 | + devs[pdata->id].funcs = &pbdrv_pwm_pico_funcs; |
| 45 | + devs[pdata->id].pdata = pdata; |
| 46 | + |
| 47 | + // Set GPIO alt modes for the PRU |
| 48 | + for (int i = 0; i < PBDRV_CONFIG_PWM_PICO_NUM_CHANNELS; i++) { |
| 49 | + const pbdrv_pwm_pico_channel_t *channel = &pdata->channels[i]; |
| 50 | + |
| 51 | + // Tell the LED pin that the PWM is in charge of its value. |
| 52 | + gpio_set_function(channel->gpio, GPIO_FUNC_PWM); |
| 53 | + // Figure out which slice we just connected to the LED pin |
| 54 | + uint slice_num = pwm_gpio_to_slice_num(channel->gpio); |
| 55 | + |
| 56 | + // Get some sensible defaults for the slice configuration. By default, |
| 57 | + // the counter is allowed to wrap over its maximum range (0 to 2**16-1) |
| 58 | + pwm_config config = pwm_get_default_config(); |
| 59 | + // Set divider, reduces counter clock to sysclock/this value |
| 60 | + pwm_config_set_clkdiv(&config, 4.f); |
| 61 | + // Load the configuration into our PWM slice, and set it running. |
| 62 | + pwm_init(slice_num, &config, true); |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +#endif // PBDRV_CONFIG_PWM_PICO |
0 commit comments