1 /*
2  * SPDX-FileCopyrightText: Copyright (c) 2025 Jilay Sandeep Pandya.
3  * SPDX-License-Identifier: Apache-2.0
4  */
5 
6 #include <zephyr/device.h>
7 #include <zephyr/drivers/gpio.h>
8 #include <zephyr/drivers/stepper.h>
9 #include <zephyr/kernel.h>
10 #include <zephyr/drivers/stepper/stepper_trinamic.h>
11 
12 #include <zephyr/logging/log.h>
13 LOG_MODULE_REGISTER(stepper_tmc50xx, CONFIG_STEPPER_LOG_LEVEL);
14 
15 static const struct device *stepper = DEVICE_DT_GET(DT_ALIAS(stepper));
16 static const struct device *stepper_drv = DEVICE_DT_GET(DT_ALIAS(stepper_drv));
17 
18 int32_t ping_pong_target_position = CONFIG_STEPS_PER_REV * CONFIG_PING_PONG_N_REV *
19 				    DT_PROP(DT_ALIAS(stepper_drv), micro_step_res);
20 
21 K_SEM_DEFINE(steps_completed_sem, 0, 1);
22 
stepper_callback(const struct device * dev,const enum stepper_event event,void * user_data)23 void stepper_callback(const struct device *dev, const enum stepper_event event, void *user_data)
24 {
25 	ARG_UNUSED(user_data);
26 	switch (event) {
27 	case STEPPER_EVENT_STEPS_COMPLETED:
28 		k_sem_give(&steps_completed_sem);
29 		break;
30 	default:
31 		break;
32 	}
33 }
34 
main(void)35 int main(void)
36 {
37 	LOG_INF("Starting tmc50xx stepper sample");
38 	if (!device_is_ready(stepper)) {
39 		LOG_ERR("Device %s is not ready", stepper->name);
40 		return -ENODEV;
41 	}
42 	LOG_DBG("stepper is %p, name is %s", stepper, stepper->name);
43 
44 	stepper_set_event_callback(stepper, stepper_callback, NULL);
45 	stepper_drv_enable(stepper);
46 
47 	enum stepper_drv_micro_step_resolution micro_step_res;
48 
49 	stepper_drv_get_micro_step_res(stepper_drv, &micro_step_res);
50 	LOG_DBG("Microstep resolution is %d", micro_step_res);
51 
52 	stepper_set_reference_position(stepper, 0);
53 	stepper_move_by(stepper, ping_pong_target_position);
54 
55 	/* Change Max Velocity during runtime */
56 	int32_t tmc_velocity;
57 
58 	tmc_velocity = DT_PROP(DT_ALIAS(stepper), vmax) * CONFIG_MAX_VELOCITY_MULTIPLIER;
59 	(void)tmc50xx_stepper_set_max_velocity(stepper, tmc_velocity);
60 
61 	for (;;) {
62 		if (k_sem_take(&steps_completed_sem, K_FOREVER) == 0) {
63 			ping_pong_target_position *= -1;
64 			stepper_move_by(stepper, ping_pong_target_position);
65 
66 			int32_t actual_position;
67 			int ret;
68 
69 			ret = stepper_get_actual_position(stepper, &actual_position);
70 			if (ret == 0) {
71 				LOG_INF("Actual position: %d", actual_position);
72 			} else {
73 				LOG_ERR("Failed to get actual position");
74 			}
75 		}
76 	}
77 	return 0;
78 }
79