|
| 1 | +/* |
| 2 | + * Copyright (c) 2025 Basalte bv |
| 3 | + * |
| 4 | + * SPDX-License-Identifier: Apache-2.0 |
| 5 | + */ |
| 6 | + |
| 7 | +#include <zephyr/drivers/pwm.h> |
| 8 | +#include <zephyr/dt-bindings/pwm/pwm.h> |
| 9 | +#include <zephyr/kernel.h> |
| 10 | + |
| 11 | +#define N_PERIODS 5 |
| 12 | + |
| 13 | +#define PWM_CHANNEL 0 |
| 14 | +#define PWM_PERIOD_NS (1 * NSEC_PER_MSEC) |
| 15 | +#define PWM_FLAGS PWM_POLARITY_NORMAL |
| 16 | + |
| 17 | +static struct pwm_event_callback callback; |
| 18 | + |
| 19 | +static bool pwm_idle; |
| 20 | +static uint8_t counter; |
| 21 | + |
| 22 | +static void pwm_callback_handler(const struct device *dev, struct pwm_event_callback *cb, |
| 23 | + uint32_t channel, pwm_events_t events) |
| 24 | +{ |
| 25 | + ARG_UNUSED(channel); |
| 26 | + ARG_UNUSED(events); |
| 27 | + int ret; |
| 28 | + |
| 29 | + if (++counter == N_PERIODS) { |
| 30 | + pwm_idle = !pwm_idle; |
| 31 | + counter = 0; |
| 32 | + |
| 33 | + ret = pwm_set(dev, PWM_CHANNEL, PWM_PERIOD_NS, pwm_idle ? 0 : PWM_PERIOD_NS / 2, |
| 34 | + PWM_FLAGS); |
| 35 | + if (ret < 0) { |
| 36 | + printk("failed to set pwm (%d)\n", ret); |
| 37 | + (void)pwm_remove_event_callback(dev, cb); |
| 38 | + return; |
| 39 | + } |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +int main(void) |
| 44 | +{ |
| 45 | + const struct device *const dev = DEVICE_DT_GET(DT_ALIAS(pwm_0)); |
| 46 | + int ret; |
| 47 | + |
| 48 | + if (!device_is_ready(dev)) { |
| 49 | + printk("device is not ready\n"); |
| 50 | + return 0; |
| 51 | + } |
| 52 | + |
| 53 | + ret = pwm_set(dev, PWM_CHANNEL, PWM_PERIOD_NS, PWM_PERIOD_NS / 2, PWM_FLAGS); |
| 54 | + if (ret < 0) { |
| 55 | + printk("failed to set idle (%d)\n", ret); |
| 56 | + return ret; |
| 57 | + } |
| 58 | + |
| 59 | + pwm_init_event_callback(&callback, pwm_callback_handler, PWM_CHANNEL, |
| 60 | + PWM_EVENT_TYPE_PERIOD); |
| 61 | + |
| 62 | + ret = pwm_add_event_callback(dev, &callback); |
| 63 | + if (ret < 0) { |
| 64 | + printk("failed to add event callback (%d)\n", ret); |
| 65 | + return ret; |
| 66 | + } |
| 67 | + |
| 68 | + return 0; |
| 69 | +} |
0 commit comments