servo.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2013, 2014 Damien P. George
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. */
  26. #include <stdio.h>
  27. #include "py/runtime.h"
  28. #include "py/mphal.h"
  29. #include "pin.h"
  30. #include "timer.h"
  31. #include "servo.h"
  32. #if MICROPY_HW_ENABLE_SERVO
  33. // This file implements the pyb.Servo class which controls standard hobby servo
  34. // motors that have 3-wires (ground, power, signal).
  35. //
  36. // The driver uses hardware PWM to drive servos on pins X1, X2, X3, X4 which are
  37. // assumed to be on PA0, PA1, PA2, PA3 but not necessarily in that order (the
  38. // pins PA0-PA3 are used directly if the X pins are not defined).
  39. //
  40. // TIM2 and TIM5 have CH1-CH4 on PA0-PA3 respectively. They are both 32-bit
  41. // counters with 16-bit prescaler. TIM5 is used by this driver.
  42. #define PYB_SERVO_NUM (4)
  43. typedef struct _pyb_servo_obj_t {
  44. mp_obj_base_t base;
  45. const pin_obj_t *pin;
  46. uint8_t pulse_min; // units of 10us
  47. uint8_t pulse_max; // units of 10us
  48. uint8_t pulse_centre; // units of 10us
  49. uint8_t pulse_angle_90; // units of 10us; pulse at 90 degrees, minus pulse_centre
  50. uint8_t pulse_speed_100; // units of 10us; pulse at 100% forward speed, minus pulse_centre
  51. uint16_t pulse_cur; // units of 10us
  52. uint16_t pulse_dest; // units of 10us
  53. int16_t pulse_accum;
  54. uint16_t time_left;
  55. } pyb_servo_obj_t;
  56. STATIC pyb_servo_obj_t pyb_servo_obj[PYB_SERVO_NUM];
  57. void servo_init(void) {
  58. timer_tim5_init();
  59. // reset servo objects
  60. for (int i = 0; i < PYB_SERVO_NUM; i++) {
  61. pyb_servo_obj[i].base.type = &pyb_servo_type;
  62. pyb_servo_obj[i].pulse_min = 64;
  63. pyb_servo_obj[i].pulse_max = 242;
  64. pyb_servo_obj[i].pulse_centre = 150;
  65. pyb_servo_obj[i].pulse_angle_90 = 97;
  66. pyb_servo_obj[i].pulse_speed_100 = 70;
  67. pyb_servo_obj[i].pulse_cur = 150;
  68. pyb_servo_obj[i].pulse_dest = 0;
  69. pyb_servo_obj[i].time_left = 0;
  70. }
  71. // assign servo objects to specific pins (must be some permutation of PA0-PA3)
  72. #ifdef pyb_pin_X1
  73. pyb_servo_obj[0].pin = pyb_pin_X1;
  74. pyb_servo_obj[1].pin = pyb_pin_X2;
  75. pyb_servo_obj[2].pin = pyb_pin_X3;
  76. pyb_servo_obj[3].pin = pyb_pin_X4;
  77. #else
  78. pyb_servo_obj[0].pin = pin_A0;
  79. pyb_servo_obj[1].pin = pin_A1;
  80. pyb_servo_obj[2].pin = pin_A2;
  81. pyb_servo_obj[3].pin = pin_A3;
  82. #endif
  83. }
  84. void servo_timer_irq_callback(void) {
  85. bool need_it = false;
  86. for (int i = 0; i < PYB_SERVO_NUM; i++) {
  87. pyb_servo_obj_t *s = &pyb_servo_obj[i];
  88. if (s->pulse_cur != s->pulse_dest) {
  89. // clamp pulse to within min/max
  90. if (s->pulse_dest < s->pulse_min) {
  91. s->pulse_dest = s->pulse_min;
  92. } else if (s->pulse_dest > s->pulse_max) {
  93. s->pulse_dest = s->pulse_max;
  94. }
  95. // adjust cur to get closer to dest
  96. if (s->time_left <= 1) {
  97. s->pulse_cur = s->pulse_dest;
  98. s->time_left = 0;
  99. } else {
  100. s->pulse_accum += s->pulse_dest - s->pulse_cur;
  101. s->pulse_cur += s->pulse_accum / s->time_left;
  102. s->pulse_accum %= s->time_left;
  103. s->time_left--;
  104. need_it = true;
  105. }
  106. // set the pulse width
  107. *(&TIM5->CCR1 + s->pin->pin) = s->pulse_cur;
  108. }
  109. }
  110. if (need_it) {
  111. __HAL_TIM_ENABLE_IT(&TIM5_Handle, TIM_IT_UPDATE);
  112. } else {
  113. __HAL_TIM_DISABLE_IT(&TIM5_Handle, TIM_IT_UPDATE);
  114. }
  115. }
  116. STATIC void servo_init_channel(pyb_servo_obj_t *s) {
  117. static const uint8_t channel_table[4] =
  118. {TIM_CHANNEL_1, TIM_CHANNEL_2, TIM_CHANNEL_3, TIM_CHANNEL_4};
  119. uint32_t channel = channel_table[s->pin->pin];
  120. // GPIO configuration
  121. mp_hal_pin_config(s->pin, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, GPIO_AF2_TIM5);
  122. // PWM mode configuration
  123. TIM_OC_InitTypeDef oc_init;
  124. oc_init.OCMode = TIM_OCMODE_PWM1;
  125. oc_init.Pulse = s->pulse_cur; // units of 10us
  126. oc_init.OCPolarity = TIM_OCPOLARITY_HIGH;
  127. oc_init.OCFastMode = TIM_OCFAST_DISABLE;
  128. HAL_TIM_PWM_ConfigChannel(&TIM5_Handle, &oc_init, channel);
  129. // start PWM
  130. HAL_TIM_PWM_Start(&TIM5_Handle, channel);
  131. }
  132. /******************************************************************************/
  133. // MicroPython bindings
  134. STATIC mp_obj_t pyb_servo_set(mp_obj_t port, mp_obj_t value) {
  135. int p = mp_obj_get_int(port);
  136. int v = mp_obj_get_int(value);
  137. if (v < 50) { v = 50; }
  138. if (v > 250) { v = 250; }
  139. switch (p) {
  140. case 1: TIM5->CCR1 = v; break;
  141. case 2: TIM5->CCR2 = v; break;
  142. case 3: TIM5->CCR3 = v; break;
  143. case 4: TIM5->CCR4 = v; break;
  144. }
  145. return mp_const_none;
  146. }
  147. MP_DEFINE_CONST_FUN_OBJ_2(pyb_servo_set_obj, pyb_servo_set);
  148. STATIC mp_obj_t pyb_pwm_set(mp_obj_t period, mp_obj_t pulse) {
  149. int pe = mp_obj_get_int(period);
  150. int pu = mp_obj_get_int(pulse);
  151. TIM5->ARR = pe;
  152. TIM5->CCR3 = pu;
  153. return mp_const_none;
  154. }
  155. MP_DEFINE_CONST_FUN_OBJ_2(pyb_pwm_set_obj, pyb_pwm_set);
  156. STATIC void pyb_servo_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
  157. pyb_servo_obj_t *self = MP_OBJ_TO_PTR(self_in);
  158. mp_printf(print, "<Servo %u at %uus>", self - &pyb_servo_obj[0] + 1, 10 * self->pulse_cur);
  159. }
  160. /// \classmethod \constructor(id)
  161. /// Create a servo object. `id` is 1-4.
  162. STATIC mp_obj_t pyb_servo_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
  163. // check arguments
  164. mp_arg_check_num(n_args, n_kw, 1, 1, false);
  165. // get servo number
  166. mp_int_t servo_id = mp_obj_get_int(args[0]) - 1;
  167. // check servo number
  168. if (!(0 <= servo_id && servo_id < PYB_SERVO_NUM)) {
  169. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Servo(%d) doesn't exist", servo_id + 1));
  170. }
  171. // get and init servo object
  172. pyb_servo_obj_t *s = &pyb_servo_obj[servo_id];
  173. s->pulse_dest = s->pulse_cur;
  174. s->time_left = 0;
  175. servo_init_channel(s);
  176. return MP_OBJ_FROM_PTR(s);
  177. }
  178. /// \method pulse_width([value])
  179. /// Get or set the pulse width in milliseconds.
  180. STATIC mp_obj_t pyb_servo_pulse_width(size_t n_args, const mp_obj_t *args) {
  181. pyb_servo_obj_t *self = MP_OBJ_TO_PTR(args[0]);
  182. if (n_args == 1) {
  183. // get pulse width, in us
  184. return mp_obj_new_int(10 * self->pulse_cur);
  185. } else {
  186. // set pulse width, in us
  187. self->pulse_dest = mp_obj_get_int(args[1]) / 10;
  188. self->time_left = 0;
  189. servo_timer_irq_callback();
  190. return mp_const_none;
  191. }
  192. }
  193. STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_servo_pulse_width_obj, 1, 2, pyb_servo_pulse_width);
  194. /// \method calibration([pulse_min, pulse_max, pulse_centre, [pulse_angle_90, pulse_speed_100]])
  195. /// Get or set the calibration of the servo timing.
  196. // TODO should accept 1 arg, a 5-tuple of values to set
  197. STATIC mp_obj_t pyb_servo_calibration(size_t n_args, const mp_obj_t *args) {
  198. pyb_servo_obj_t *self = MP_OBJ_TO_PTR(args[0]);
  199. if (n_args == 1) {
  200. // get calibration values
  201. mp_obj_t tuple[5];
  202. tuple[0] = mp_obj_new_int(10 * self->pulse_min);
  203. tuple[1] = mp_obj_new_int(10 * self->pulse_max);
  204. tuple[2] = mp_obj_new_int(10 * self->pulse_centre);
  205. tuple[3] = mp_obj_new_int(10 * (self->pulse_angle_90 + self->pulse_centre));
  206. tuple[4] = mp_obj_new_int(10 * (self->pulse_speed_100 + self->pulse_centre));
  207. return mp_obj_new_tuple(5, tuple);
  208. } else if (n_args >= 4) {
  209. // set min, max, centre
  210. self->pulse_min = mp_obj_get_int(args[1]) / 10;
  211. self->pulse_max = mp_obj_get_int(args[2]) / 10;
  212. self->pulse_centre = mp_obj_get_int(args[3]) / 10;
  213. if (n_args == 4) {
  214. return mp_const_none;
  215. } else if (n_args == 6) {
  216. self->pulse_angle_90 = mp_obj_get_int(args[4]) / 10 - self->pulse_centre;
  217. self->pulse_speed_100 = mp_obj_get_int(args[5]) / 10 - self->pulse_centre;
  218. return mp_const_none;
  219. }
  220. }
  221. // bad number of arguments
  222. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "calibration expecting 1, 4 or 6 arguments, got %d", n_args));
  223. }
  224. STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_servo_calibration_obj, 1, 6, pyb_servo_calibration);
  225. /// \method angle([angle, time=0])
  226. /// Get or set the angle of the servo.
  227. ///
  228. /// - `angle` is the angle to move to in degrees.
  229. /// - `time` is the number of milliseconds to take to get to the specified angle.
  230. STATIC mp_obj_t pyb_servo_angle(size_t n_args, const mp_obj_t *args) {
  231. pyb_servo_obj_t *self = MP_OBJ_TO_PTR(args[0]);
  232. if (n_args == 1) {
  233. // get angle
  234. return mp_obj_new_int((self->pulse_cur - self->pulse_centre) * 90 / self->pulse_angle_90);
  235. } else {
  236. #if MICROPY_PY_BUILTINS_FLOAT
  237. self->pulse_dest = self->pulse_centre + self->pulse_angle_90 * mp_obj_get_float(args[1]) / 90.0;
  238. #else
  239. self->pulse_dest = self->pulse_centre + self->pulse_angle_90 * mp_obj_get_int(args[1]) / 90;
  240. #endif
  241. if (n_args == 2) {
  242. // set angle immediately
  243. self->time_left = 0;
  244. } else {
  245. // set angle over a given time (given in milli seconds)
  246. self->time_left = mp_obj_get_int(args[2]) / 20;
  247. self->pulse_accum = 0;
  248. }
  249. servo_timer_irq_callback();
  250. return mp_const_none;
  251. }
  252. }
  253. STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_servo_angle_obj, 1, 3, pyb_servo_angle);
  254. /// \method speed([speed, time=0])
  255. /// Get or set the speed of a continuous rotation servo.
  256. ///
  257. /// - `speed` is the speed to move to change to, between -100 and 100.
  258. /// - `time` is the number of milliseconds to take to get to the specified speed.
  259. STATIC mp_obj_t pyb_servo_speed(size_t n_args, const mp_obj_t *args) {
  260. pyb_servo_obj_t *self = MP_OBJ_TO_PTR(args[0]);
  261. if (n_args == 1) {
  262. // get speed
  263. return mp_obj_new_int((self->pulse_cur - self->pulse_centre) * 100 / self->pulse_speed_100);
  264. } else {
  265. #if MICROPY_PY_BUILTINS_FLOAT
  266. self->pulse_dest = self->pulse_centre + self->pulse_speed_100 * mp_obj_get_float(args[1]) / 100.0;
  267. #else
  268. self->pulse_dest = self->pulse_centre + self->pulse_speed_100 * mp_obj_get_int(args[1]) / 100;
  269. #endif
  270. if (n_args == 2) {
  271. // set speed immediately
  272. self->time_left = 0;
  273. } else {
  274. // set speed over a given time (given in milli seconds)
  275. self->time_left = mp_obj_get_int(args[2]) / 20;
  276. self->pulse_accum = 0;
  277. }
  278. servo_timer_irq_callback();
  279. return mp_const_none;
  280. }
  281. }
  282. STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_servo_speed_obj, 1, 3, pyb_servo_speed);
  283. STATIC const mp_rom_map_elem_t pyb_servo_locals_dict_table[] = {
  284. { MP_ROM_QSTR(MP_QSTR_pulse_width), MP_ROM_PTR(&pyb_servo_pulse_width_obj) },
  285. { MP_ROM_QSTR(MP_QSTR_calibration), MP_ROM_PTR(&pyb_servo_calibration_obj) },
  286. { MP_ROM_QSTR(MP_QSTR_angle), MP_ROM_PTR(&pyb_servo_angle_obj) },
  287. { MP_ROM_QSTR(MP_QSTR_speed), MP_ROM_PTR(&pyb_servo_speed_obj) },
  288. };
  289. STATIC MP_DEFINE_CONST_DICT(pyb_servo_locals_dict, pyb_servo_locals_dict_table);
  290. const mp_obj_type_t pyb_servo_type = {
  291. { &mp_type_type },
  292. .name = MP_QSTR_Servo,
  293. .print = pyb_servo_print,
  294. .make_new = pyb_servo_make_new,
  295. .locals_dict = (mp_obj_dict_t*)&pyb_servo_locals_dict,
  296. };
  297. #endif // MICROPY_HW_ENABLE_SERVO