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