diff --git a/samples/basic/fade_led/README.rst b/samples/basic/fade_led/README.rst index 846b58031eb..d86f0f2edfb 100644 --- a/samples/basic/fade_led/README.rst +++ b/samples/basic/fade_led/README.rst @@ -10,7 +10,9 @@ This application "fades" a LED using the :ref:`PWM API `. The LED starts off increases its brightness until it is fully or nearly fully on. The brightness then decreases until the LED is off, completing on fade -cycle. Each cycle takes 2.5 seconds, and the cycles repeat forever. +cycle. Each cycle takes 2.5 seconds, and the cycles repeat forever. The PWM +period is taken from Devicetree. It should be fast enough to be above the +flicker fusion threshold. Requirements and Wiring *********************** diff --git a/samples/basic/fade_led/src/main.c b/samples/basic/fade_led/src/main.c index 2455e8174e6..e809a397998 100644 --- a/samples/basic/fade_led/src/main.c +++ b/samples/basic/fade_led/src/main.c @@ -14,63 +14,44 @@ #include #include -#define PWM_LED0_NODE DT_ALIAS(pwm_led0) +static const struct pwm_dt_spec pwm_led0 = PWM_DT_SPEC_GET(DT_ALIAS(pwm_led0)); -#if DT_NODE_HAS_STATUS(PWM_LED0_NODE, okay) -#define PWM_CTLR DT_PWMS_CTLR(PWM_LED0_NODE) -#define PWM_CHANNEL DT_PWMS_CHANNEL(PWM_LED0_NODE) -#define PWM_FLAGS DT_PWMS_FLAGS(PWM_LED0_NODE) -#else -#error "Unsupported board: pwm-led0 devicetree alias is not defined" -#define PWM_CTLR DT_INVALID_NODE -#define PWM_CHANNEL 0 -#define PWM_FLAGS 0 -#endif - -/* - * This period should be fast enough to be above the flicker fusion - * threshold. The steps should also be small enough, and happen - * quickly enough, to make the output fade change appear continuous. - */ -#define PERIOD_USEC 20000U #define NUM_STEPS 50U -#define STEP_USEC (PERIOD_USEC / NUM_STEPS) #define SLEEP_MSEC 25U void main(void) { - const struct device *pwm; uint32_t pulse_width = 0U; + uint32_t step = pwm_led0.period / NUM_STEPS; uint8_t dir = 1U; int ret; printk("PWM-based LED fade\n"); - pwm = DEVICE_DT_GET(PWM_CTLR); - if (!device_is_ready(pwm)) { - printk("Error: PWM device %s is not ready\n", pwm->name); + if (!device_is_ready(pwm_led0.dev)) { + printk("Error: PWM device %s is not ready\n", + pwm_led0.dev->name); return; } while (1) { - ret = pwm_set_usec(pwm, PWM_CHANNEL, PERIOD_USEC, pulse_width, - PWM_FLAGS); + ret = pwm_set_nsec_pulse_dt(&pwm_led0, pulse_width); if (ret) { printk("Error %d: failed to set pulse width\n", ret); return; } if (dir) { - pulse_width += STEP_USEC; - if (pulse_width >= PERIOD_USEC) { - pulse_width = PERIOD_USEC - STEP_USEC; + pulse_width += step; + if (pulse_width >= pwm_led0.period) { + pulse_width = pwm_led0.period - step; dir = 0U; } } else { - if (pulse_width >= STEP_USEC) { - pulse_width -= STEP_USEC; + if (pulse_width >= step) { + pulse_width -= step; } else { - pulse_width = STEP_USEC; + pulse_width = step; dir = 1U; } }