machine_pwm.c 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. /*
  2. * This file is part of the Micro Python project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2016 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 "driver/ledc.h"
  28. #include "esp_err.h"
  29. #include "py/nlr.h"
  30. #include "py/runtime.h"
  31. #include "modmachine.h"
  32. #include "mphalport.h"
  33. // Forward dec'l
  34. extern const mp_obj_type_t machine_pwm_type;
  35. typedef struct _esp32_pwm_obj_t {
  36. mp_obj_base_t base;
  37. gpio_num_t pin;
  38. uint8_t active;
  39. uint8_t channel;
  40. } esp32_pwm_obj_t;
  41. // Which channel has which GPIO pin assigned?
  42. // (-1 if not assigned)
  43. STATIC int chan_gpio[LEDC_CHANNEL_MAX];
  44. // Params for PW operation
  45. // 5khz
  46. #define PWFREQ (5000)
  47. // High speed mode
  48. #define PWMODE (LEDC_HIGH_SPEED_MODE)
  49. // 10-bit resolution (compatible with esp8266 PWM)
  50. #define PWRES (LEDC_TIMER_10_BIT)
  51. // Timer 1
  52. #define PWTIMER (LEDC_TIMER_1)
  53. // Config of timer upon which we run all PWM'ed GPIO pins
  54. STATIC bool pwm_inited = false;
  55. STATIC ledc_timer_config_t timer_cfg = {
  56. .bit_num = PWRES,
  57. .freq_hz = PWFREQ,
  58. .speed_mode = PWMODE,
  59. .timer_num = PWTIMER
  60. };
  61. STATIC void pwm_init(void) {
  62. // Initial condition: no channels assigned
  63. for (int x = 0; x < LEDC_CHANNEL_MAX; ++x) {
  64. chan_gpio[x] = -1;
  65. }
  66. // Init with default timer params
  67. ledc_timer_config(&timer_cfg);
  68. }
  69. STATIC int set_freq(int newval) {
  70. int oval = timer_cfg.freq_hz;
  71. timer_cfg.freq_hz = newval;
  72. if (ledc_timer_config(&timer_cfg) != ESP_OK) {
  73. timer_cfg.freq_hz = oval;
  74. return 0;
  75. }
  76. return 1;
  77. }
  78. /******************************************************************************/
  79. // MicroPython bindings for PWM
  80. STATIC void esp32_pwm_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
  81. esp32_pwm_obj_t *self = MP_OBJ_TO_PTR(self_in);
  82. mp_printf(print, "PWM(%u", self->pin);
  83. if (self->active) {
  84. mp_printf(print, ", freq=%u, duty=%u", timer_cfg.freq_hz,
  85. ledc_get_duty(PWMODE, self->channel));
  86. }
  87. mp_printf(print, ")");
  88. }
  89. STATIC void esp32_pwm_init_helper(esp32_pwm_obj_t *self,
  90. size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
  91. enum { ARG_freq, ARG_duty };
  92. static const mp_arg_t allowed_args[] = {
  93. { MP_QSTR_freq, MP_ARG_INT, {.u_int = -1} },
  94. { MP_QSTR_duty, MP_ARG_INT, {.u_int = -1} },
  95. };
  96. mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
  97. mp_arg_parse_all(n_args, pos_args, kw_args,
  98. MP_ARRAY_SIZE(allowed_args), allowed_args, args);
  99. int channel;
  100. int avail = -1;
  101. // Find a free PWM channel, also spot if our pin is
  102. // already mentioned.
  103. for (channel = 0; channel < LEDC_CHANNEL_MAX; ++channel) {
  104. if (chan_gpio[channel] == self->pin) {
  105. break;
  106. }
  107. if ((avail == -1) && (chan_gpio[channel] == -1)) {
  108. avail = channel;
  109. }
  110. }
  111. if (channel >= LEDC_CHANNEL_MAX) {
  112. if (avail == -1) {
  113. mp_raise_ValueError("out of PWM channels");
  114. }
  115. channel = avail;
  116. }
  117. self->channel = channel;
  118. // New PWM assignment
  119. self->active = 1;
  120. if (chan_gpio[channel] == -1) {
  121. ledc_channel_config_t cfg = {
  122. .channel = channel,
  123. .duty = (1 << PWRES) / 2,
  124. .gpio_num = self->pin,
  125. .intr_type = LEDC_INTR_DISABLE,
  126. .speed_mode = PWMODE,
  127. .timer_sel = PWTIMER,
  128. };
  129. if (ledc_channel_config(&cfg) != ESP_OK) {
  130. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
  131. "PWM not supported on pin %d", self->pin));
  132. }
  133. chan_gpio[channel] = self->pin;
  134. }
  135. // Maybe change PWM timer
  136. int tval = args[ARG_freq].u_int;
  137. if (tval != -1) {
  138. if (tval != timer_cfg.freq_hz) {
  139. if (!set_freq(tval)) {
  140. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
  141. "Bad frequency %d", tval));
  142. }
  143. }
  144. }
  145. // Set duty cycle?
  146. int dval = args[ARG_duty].u_int;
  147. if (dval != -1) {
  148. dval &= ((1 << PWRES)-1);
  149. ledc_set_duty(PWMODE, channel, dval);
  150. ledc_update_duty(PWMODE, channel);
  151. }
  152. }
  153. STATIC mp_obj_t esp32_pwm_make_new(const mp_obj_type_t *type,
  154. size_t n_args, size_t n_kw, const mp_obj_t *args) {
  155. mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);
  156. gpio_num_t pin_id = machine_pin_get_id(args[0]);
  157. // create PWM object from the given pin
  158. esp32_pwm_obj_t *self = m_new_obj(esp32_pwm_obj_t);
  159. self->base.type = &machine_pwm_type;
  160. self->pin = pin_id;
  161. self->active = 0;
  162. self->channel = -1;
  163. // start the PWM subsystem if it's not already running
  164. if (!pwm_inited) {
  165. pwm_init();
  166. pwm_inited = true;
  167. }
  168. // start the PWM running for this channel
  169. mp_map_t kw_args;
  170. mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
  171. esp32_pwm_init_helper(self, n_args - 1, args + 1, &kw_args);
  172. return MP_OBJ_FROM_PTR(self);
  173. }
  174. STATIC mp_obj_t esp32_pwm_init(size_t n_args,
  175. const mp_obj_t *args, mp_map_t *kw_args) {
  176. esp32_pwm_init_helper(args[0], n_args - 1, args + 1, kw_args);
  177. return mp_const_none;
  178. }
  179. MP_DEFINE_CONST_FUN_OBJ_KW(esp32_pwm_init_obj, 1, esp32_pwm_init);
  180. STATIC mp_obj_t esp32_pwm_deinit(mp_obj_t self_in) {
  181. esp32_pwm_obj_t *self = MP_OBJ_TO_PTR(self_in);
  182. int chan = self->channel;
  183. // Valid channel?
  184. if ((chan >= 0) && (chan < LEDC_CHANNEL_MAX)) {
  185. // Mark it unused, and tell the hardware to stop routing
  186. chan_gpio[chan] = -1;
  187. ledc_stop(PWMODE, chan, 0);
  188. self->active = 0;
  189. self->channel = -1;
  190. }
  191. return mp_const_none;
  192. }
  193. STATIC MP_DEFINE_CONST_FUN_OBJ_1(esp32_pwm_deinit_obj, esp32_pwm_deinit);
  194. STATIC mp_obj_t esp32_pwm_freq(size_t n_args, const mp_obj_t *args) {
  195. if (n_args == 1) {
  196. // get
  197. return MP_OBJ_NEW_SMALL_INT(timer_cfg.freq_hz);
  198. }
  199. // set
  200. int tval = mp_obj_get_int(args[1]);
  201. if (!set_freq(tval)) {
  202. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
  203. "Bad frequency %d", tval));
  204. }
  205. return mp_const_none;
  206. }
  207. STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(esp32_pwm_freq_obj, 1, 2, esp32_pwm_freq);
  208. STATIC mp_obj_t esp32_pwm_duty(size_t n_args, const mp_obj_t *args) {
  209. esp32_pwm_obj_t *self = MP_OBJ_TO_PTR(args[0]);
  210. int duty;
  211. if (n_args == 1) {
  212. // get
  213. duty = ledc_get_duty(PWMODE, self->channel);
  214. return MP_OBJ_NEW_SMALL_INT(duty);
  215. }
  216. // set
  217. duty = mp_obj_get_int(args[1]);
  218. duty &= ((1 << PWRES)-1);
  219. ledc_set_duty(PWMODE, self->channel, duty);
  220. ledc_update_duty(PWMODE, self->channel);
  221. return mp_const_none;
  222. }
  223. STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(esp32_pwm_duty_obj,
  224. 1, 2, esp32_pwm_duty);
  225. STATIC const mp_rom_map_elem_t esp32_pwm_locals_dict_table[] = {
  226. { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&esp32_pwm_init_obj) },
  227. { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&esp32_pwm_deinit_obj) },
  228. { MP_ROM_QSTR(MP_QSTR_freq), MP_ROM_PTR(&esp32_pwm_freq_obj) },
  229. { MP_ROM_QSTR(MP_QSTR_duty), MP_ROM_PTR(&esp32_pwm_duty_obj) },
  230. };
  231. STATIC MP_DEFINE_CONST_DICT(esp32_pwm_locals_dict,
  232. esp32_pwm_locals_dict_table);
  233. const mp_obj_type_t machine_pwm_type = {
  234. { &mp_type_type },
  235. .name = MP_QSTR_PWM,
  236. .print = esp32_pwm_print,
  237. .make_new = esp32_pwm_make_new,
  238. .locals_dict = (mp_obj_dict_t*)&esp32_pwm_locals_dict,
  239. };