1 /* 2 * Copyright (c) 2016 Intel Corporation 3 * Copyright (c) 2020 Nordic Semiconductor ASA 4 * 5 * SPDX-License-Identifier: Apache-2.0 6 */ 7 8 /** 9 * @file Sample app to demonstrate PWM-based LED fade 10 */ 11 12 #include <zephyr/kernel.h> 13 #include <zephyr/sys/printk.h> 14 #include <zephyr/device.h> 15 #include <zephyr/drivers/pwm.h> 16 17 static const struct pwm_dt_spec pwm_led0 = PWM_DT_SPEC_GET(DT_ALIAS(pwm_led0)); 18 19 #define NUM_STEPS 50U 20 #define SLEEP_MSEC 25U 21 main(void)22int main(void) 23 { 24 uint32_t pulse_width = 0U; 25 uint32_t step = pwm_led0.period / NUM_STEPS; 26 uint8_t dir = 1U; 27 int ret; 28 29 printk("PWM-based LED fade\n"); 30 31 if (!pwm_is_ready_dt(&pwm_led0)) { 32 printk("Error: PWM device %s is not ready\n", 33 pwm_led0.dev->name); 34 return 0; 35 } 36 37 while (1) { 38 ret = pwm_set_pulse_dt(&pwm_led0, pulse_width); 39 if (ret) { 40 printk("Error %d: failed to set pulse width\n", ret); 41 return 0; 42 } 43 printk("Using pulse width %d%%\n", 100 * pulse_width / pwm_led0.period); 44 45 if (dir) { 46 pulse_width += step; 47 if (pulse_width >= pwm_led0.period) { 48 pulse_width = pwm_led0.period - step; 49 dir = 0U; 50 } 51 } else { 52 if (pulse_width >= step) { 53 pulse_width -= step; 54 } else { 55 pulse_width = step; 56 dir = 1U; 57 } 58 } 59 60 k_sleep(K_MSEC(SLEEP_MSEC)); 61 } 62 return 0; 63 } 64