timer.c 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516
  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 <stdint.h>
  27. #include <stdio.h>
  28. #include <string.h>
  29. #include "py/runtime.h"
  30. #include "py/gc.h"
  31. #include "timer.h"
  32. #include "servo.h"
  33. #include "pin.h"
  34. #include "irq.h"
  35. /// \moduleref pyb
  36. /// \class Timer - periodically call a function
  37. ///
  38. /// Timers can be used for a great variety of tasks. At the moment, only
  39. /// the simplest case is implemented: that of calling a function periodically.
  40. ///
  41. /// Each timer consists of a counter that counts up at a certain rate. The rate
  42. /// at which it counts is the peripheral clock frequency (in Hz) divided by the
  43. /// timer prescaler. When the counter reaches the timer period it triggers an
  44. /// event, and the counter resets back to zero. By using the callback method,
  45. /// the timer event can call a Python function.
  46. ///
  47. /// Example usage to toggle an LED at a fixed frequency:
  48. ///
  49. /// tim = pyb.Timer(4) # create a timer object using timer 4
  50. /// tim.init(freq=2) # trigger at 2Hz
  51. /// tim.callback(lambda t:pyb.LED(1).toggle())
  52. ///
  53. /// Further examples:
  54. ///
  55. /// tim = pyb.Timer(4, freq=100) # freq in Hz
  56. /// tim = pyb.Timer(4, prescaler=0, period=99)
  57. /// tim.counter() # get counter (can also set)
  58. /// tim.prescaler(2) # set prescaler (can also get)
  59. /// tim.period(199) # set period (can also get)
  60. /// tim.callback(lambda t: ...) # set callback for update interrupt (t=tim instance)
  61. /// tim.callback(None) # clear callback
  62. ///
  63. /// *Note:* Timer 3 is used for fading the blue LED. Timer 5 controls
  64. /// the servo driver, and Timer 6 is used for timed ADC/DAC reading/writing.
  65. /// It is recommended to use the other timers in your programs.
  66. // The timers can be used by multiple drivers, and need a common point for
  67. // the interrupts to be dispatched, so they are all collected here.
  68. //
  69. // TIM3:
  70. // - LED 4, PWM to set the LED intensity
  71. //
  72. // TIM5:
  73. // - servo controller, PWM
  74. //
  75. // TIM6:
  76. // - ADC, DAC for read_timed and write_timed
  77. typedef enum {
  78. CHANNEL_MODE_PWM_NORMAL,
  79. CHANNEL_MODE_PWM_INVERTED,
  80. CHANNEL_MODE_OC_TIMING,
  81. CHANNEL_MODE_OC_ACTIVE,
  82. CHANNEL_MODE_OC_INACTIVE,
  83. CHANNEL_MODE_OC_TOGGLE,
  84. CHANNEL_MODE_OC_FORCED_ACTIVE,
  85. CHANNEL_MODE_OC_FORCED_INACTIVE,
  86. CHANNEL_MODE_IC,
  87. CHANNEL_MODE_ENC_A,
  88. CHANNEL_MODE_ENC_B,
  89. CHANNEL_MODE_ENC_AB,
  90. } pyb_channel_mode;
  91. STATIC const struct {
  92. qstr name;
  93. uint32_t oc_mode;
  94. } channel_mode_info[] = {
  95. { MP_QSTR_PWM, TIM_OCMODE_PWM1 },
  96. { MP_QSTR_PWM_INVERTED, TIM_OCMODE_PWM2 },
  97. { MP_QSTR_OC_TIMING, TIM_OCMODE_TIMING },
  98. { MP_QSTR_OC_ACTIVE, TIM_OCMODE_ACTIVE },
  99. { MP_QSTR_OC_INACTIVE, TIM_OCMODE_INACTIVE },
  100. { MP_QSTR_OC_TOGGLE, TIM_OCMODE_TOGGLE },
  101. { MP_QSTR_OC_FORCED_ACTIVE, TIM_OCMODE_FORCED_ACTIVE },
  102. { MP_QSTR_OC_FORCED_INACTIVE, TIM_OCMODE_FORCED_INACTIVE },
  103. { MP_QSTR_IC, 0 },
  104. { MP_QSTR_ENC_A, TIM_ENCODERMODE_TI1 },
  105. { MP_QSTR_ENC_B, TIM_ENCODERMODE_TI2 },
  106. { MP_QSTR_ENC_AB, TIM_ENCODERMODE_TI12 },
  107. };
  108. typedef struct _pyb_timer_channel_obj_t {
  109. mp_obj_base_t base;
  110. struct _pyb_timer_obj_t *timer;
  111. uint8_t channel;
  112. uint8_t mode;
  113. mp_obj_t callback;
  114. struct _pyb_timer_channel_obj_t *next;
  115. } pyb_timer_channel_obj_t;
  116. typedef struct _pyb_timer_obj_t {
  117. mp_obj_base_t base;
  118. uint8_t tim_id;
  119. uint8_t is_32bit;
  120. mp_obj_t callback;
  121. TIM_HandleTypeDef tim;
  122. IRQn_Type irqn;
  123. pyb_timer_channel_obj_t *channel;
  124. } pyb_timer_obj_t;
  125. // The following yields TIM_IT_UPDATE when channel is zero and
  126. // TIM_IT_CC1..TIM_IT_CC4 when channel is 1..4
  127. #define TIMER_IRQ_MASK(channel) (1 << (channel))
  128. #define TIMER_CNT_MASK(self) ((self)->is_32bit ? 0xffffffff : 0xffff)
  129. #define TIMER_CHANNEL(self) ((((self)->channel) - 1) << 2)
  130. TIM_HandleTypeDef TIM5_Handle;
  131. TIM_HandleTypeDef TIM6_Handle;
  132. #define PYB_TIMER_OBJ_ALL_NUM MP_ARRAY_SIZE(MP_STATE_PORT(pyb_timer_obj_all))
  133. STATIC mp_obj_t pyb_timer_deinit(mp_obj_t self_in);
  134. STATIC mp_obj_t pyb_timer_callback(mp_obj_t self_in, mp_obj_t callback);
  135. STATIC mp_obj_t pyb_timer_channel_callback(mp_obj_t self_in, mp_obj_t callback);
  136. void timer_init0(void) {
  137. for (uint i = 0; i < PYB_TIMER_OBJ_ALL_NUM; i++) {
  138. MP_STATE_PORT(pyb_timer_obj_all)[i] = NULL;
  139. }
  140. }
  141. // unregister all interrupt sources
  142. void timer_deinit(void) {
  143. for (uint i = 0; i < PYB_TIMER_OBJ_ALL_NUM; i++) {
  144. pyb_timer_obj_t *tim = MP_STATE_PORT(pyb_timer_obj_all)[i];
  145. if (tim != NULL) {
  146. pyb_timer_deinit(MP_OBJ_FROM_PTR(tim));
  147. }
  148. }
  149. }
  150. #if defined(TIM5)
  151. // TIM5 is set-up for the servo controller
  152. // This function inits but does not start the timer
  153. void timer_tim5_init(void) {
  154. // TIM5 clock enable
  155. __HAL_RCC_TIM5_CLK_ENABLE();
  156. // set up and enable interrupt
  157. NVIC_SetPriority(TIM5_IRQn, IRQ_PRI_TIM5);
  158. HAL_NVIC_EnableIRQ(TIM5_IRQn);
  159. // PWM clock configuration
  160. TIM5_Handle.Instance = TIM5;
  161. TIM5_Handle.Init.Period = 2000 - 1; // timer cycles at 50Hz
  162. TIM5_Handle.Init.Prescaler = (timer_get_source_freq(5) / 100000) - 1; // timer runs at 100kHz
  163. TIM5_Handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  164. TIM5_Handle.Init.CounterMode = TIM_COUNTERMODE_UP;
  165. HAL_TIM_PWM_Init(&TIM5_Handle);
  166. }
  167. #endif
  168. #if defined(TIM6)
  169. // Init TIM6 with a counter-overflow at the given frequency (given in Hz)
  170. // TIM6 is used by the DAC and ADC for auto sampling at a given frequency
  171. // This function inits but does not start the timer
  172. TIM_HandleTypeDef *timer_tim6_init(uint freq) {
  173. // TIM6 clock enable
  174. __HAL_RCC_TIM6_CLK_ENABLE();
  175. // Timer runs at SystemCoreClock / 2
  176. // Compute the prescaler value so TIM6 triggers at freq-Hz
  177. uint32_t period = MAX(1, timer_get_source_freq(6) / freq);
  178. uint32_t prescaler = 1;
  179. while (period > 0xffff) {
  180. period >>= 1;
  181. prescaler <<= 1;
  182. }
  183. // Time base clock configuration
  184. TIM6_Handle.Instance = TIM6;
  185. TIM6_Handle.Init.Period = period - 1;
  186. TIM6_Handle.Init.Prescaler = prescaler - 1;
  187. TIM6_Handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; // unused for TIM6
  188. TIM6_Handle.Init.CounterMode = TIM_COUNTERMODE_UP; // unused for TIM6
  189. HAL_TIM_Base_Init(&TIM6_Handle);
  190. return &TIM6_Handle;
  191. }
  192. #endif
  193. // Interrupt dispatch
  194. void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) {
  195. #if MICROPY_HW_ENABLE_SERVO
  196. if (htim == &TIM5_Handle) {
  197. servo_timer_irq_callback();
  198. }
  199. #endif
  200. }
  201. // Get the frequency (in Hz) of the source clock for the given timer.
  202. // On STM32F405/407/415/417 there are 2 cases for how the clock freq is set.
  203. // If the APB prescaler is 1, then the timer clock is equal to its respective
  204. // APB clock. Otherwise (APB prescaler > 1) the timer clock is twice its
  205. // respective APB clock. See DM00031020 Rev 4, page 115.
  206. uint32_t timer_get_source_freq(uint32_t tim_id) {
  207. uint32_t source, clk_div;
  208. if (tim_id == 1 || (8 <= tim_id && tim_id <= 11)) {
  209. // TIM{1,8,9,10,11} are on APB2
  210. #if defined(STM32F0)
  211. source = HAL_RCC_GetPCLK1Freq();
  212. clk_div = RCC->CFGR & RCC_CFGR_PPRE;
  213. #elif defined(STM32H7)
  214. source = HAL_RCC_GetPCLK2Freq();
  215. clk_div = RCC->D2CFGR & RCC_D2CFGR_D2PPRE2;
  216. #else
  217. source = HAL_RCC_GetPCLK2Freq();
  218. clk_div = RCC->CFGR & RCC_CFGR_PPRE2;
  219. #endif
  220. } else {
  221. // TIM{2,3,4,5,6,7,12,13,14} are on APB1
  222. source = HAL_RCC_GetPCLK1Freq();
  223. #if defined(STM32F0)
  224. clk_div = RCC->CFGR & RCC_CFGR_PPRE;
  225. #elif defined(STM32H7)
  226. clk_div = RCC->D2CFGR & RCC_D2CFGR_D2PPRE1;
  227. #else
  228. clk_div = RCC->CFGR & RCC_CFGR_PPRE1;
  229. #endif
  230. }
  231. if (clk_div != 0) {
  232. // APB prescaler for this timer is > 1
  233. source *= 2;
  234. }
  235. return source;
  236. }
  237. /******************************************************************************/
  238. /* MicroPython bindings */
  239. STATIC const mp_obj_type_t pyb_timer_channel_type;
  240. // This is the largest value that we can multiply by 100 and have the result
  241. // fit in a uint32_t.
  242. #define MAX_PERIOD_DIV_100 42949672
  243. // computes prescaler and period so TIM triggers at freq-Hz
  244. STATIC uint32_t compute_prescaler_period_from_freq(pyb_timer_obj_t *self, mp_obj_t freq_in, uint32_t *period_out) {
  245. uint32_t source_freq = timer_get_source_freq(self->tim_id);
  246. uint32_t prescaler = 1;
  247. uint32_t period;
  248. if (0) {
  249. #if MICROPY_PY_BUILTINS_FLOAT
  250. } else if (MP_OBJ_IS_TYPE(freq_in, &mp_type_float)) {
  251. float freq = mp_obj_get_float(freq_in);
  252. if (freq <= 0) {
  253. goto bad_freq;
  254. }
  255. while (freq < 1 && prescaler < 6553) {
  256. prescaler *= 10;
  257. freq *= 10;
  258. }
  259. period = (float)source_freq / freq;
  260. #endif
  261. } else {
  262. mp_int_t freq = mp_obj_get_int(freq_in);
  263. if (freq <= 0) {
  264. goto bad_freq;
  265. bad_freq:
  266. mp_raise_ValueError("must have positive freq");
  267. }
  268. period = source_freq / freq;
  269. }
  270. period = MAX(1, period);
  271. while (period > TIMER_CNT_MASK(self)) {
  272. // if we can divide exactly, do that first
  273. if (period % 5 == 0) {
  274. prescaler *= 5;
  275. period /= 5;
  276. } else if (period % 3 == 0) {
  277. prescaler *= 3;
  278. period /= 3;
  279. } else {
  280. // may not divide exactly, but loses minimal precision
  281. prescaler <<= 1;
  282. period >>= 1;
  283. }
  284. }
  285. *period_out = (period - 1) & TIMER_CNT_MASK(self);
  286. return (prescaler - 1) & 0xffff;
  287. }
  288. // computes prescaler and period so TIM triggers with a period of t_num/t_den seconds
  289. STATIC uint32_t compute_prescaler_period_from_t(pyb_timer_obj_t *self, int32_t t_num, int32_t t_den, uint32_t *period_out) {
  290. uint32_t source_freq = timer_get_source_freq(self->tim_id);
  291. if (t_num <= 0 || t_den <= 0) {
  292. mp_raise_ValueError("must have positive freq");
  293. }
  294. uint64_t period = (uint64_t)source_freq * (uint64_t)t_num / (uint64_t)t_den;
  295. uint32_t prescaler = 1;
  296. while (period > TIMER_CNT_MASK(self)) {
  297. // if we can divide exactly, and without prescaler overflow, do that first
  298. if (prescaler <= 13107 && period % 5 == 0) {
  299. prescaler *= 5;
  300. period /= 5;
  301. } else if (prescaler <= 21845 && period % 3 == 0) {
  302. prescaler *= 3;
  303. period /= 3;
  304. } else {
  305. // may not divide exactly, but loses minimal precision
  306. uint32_t period_lsb = period & 1;
  307. prescaler <<= 1;
  308. period >>= 1;
  309. if (period < prescaler) {
  310. // round division up
  311. prescaler |= period_lsb;
  312. }
  313. if (prescaler > 0x10000) {
  314. mp_raise_ValueError("period too large");
  315. }
  316. }
  317. }
  318. *period_out = (period - 1) & TIMER_CNT_MASK(self);
  319. return (prescaler - 1) & 0xffff;
  320. }
  321. // Helper function for determining the period used for calculating percent
  322. STATIC uint32_t compute_period(pyb_timer_obj_t *self) {
  323. // In center mode, compare == period corresponds to 100%
  324. // In edge mode, compare == (period + 1) corresponds to 100%
  325. uint32_t period = (__HAL_TIM_GET_AUTORELOAD(&self->tim) & TIMER_CNT_MASK(self));
  326. if (period != 0xffffffff) {
  327. if (self->tim.Init.CounterMode == TIM_COUNTERMODE_UP ||
  328. self->tim.Init.CounterMode == TIM_COUNTERMODE_DOWN) {
  329. // Edge mode
  330. period++;
  331. }
  332. }
  333. return period;
  334. }
  335. // Helper function to compute PWM value from timer period and percent value.
  336. // 'percent_in' can be an int or a float between 0 and 100 (out of range
  337. // values are clamped).
  338. STATIC uint32_t compute_pwm_value_from_percent(uint32_t period, mp_obj_t percent_in) {
  339. uint32_t cmp;
  340. if (0) {
  341. #if MICROPY_PY_BUILTINS_FLOAT
  342. } else if (MP_OBJ_IS_TYPE(percent_in, &mp_type_float)) {
  343. mp_float_t percent = mp_obj_get_float(percent_in);
  344. if (percent <= 0.0) {
  345. cmp = 0;
  346. } else if (percent >= 100.0) {
  347. cmp = period;
  348. } else {
  349. cmp = percent / 100.0 * ((mp_float_t)period);
  350. }
  351. #endif
  352. } else {
  353. // For integer arithmetic, if period is large and 100*period will
  354. // overflow, then divide period before multiplying by cmp. Otherwise
  355. // do it the other way round to retain precision.
  356. mp_int_t percent = mp_obj_get_int(percent_in);
  357. if (percent <= 0) {
  358. cmp = 0;
  359. } else if (percent >= 100) {
  360. cmp = period;
  361. } else if (period > MAX_PERIOD_DIV_100) {
  362. cmp = (uint32_t)percent * (period / 100);
  363. } else {
  364. cmp = ((uint32_t)percent * period) / 100;
  365. }
  366. }
  367. return cmp;
  368. }
  369. // Helper function to compute percentage from timer perion and PWM value.
  370. STATIC mp_obj_t compute_percent_from_pwm_value(uint32_t period, uint32_t cmp) {
  371. #if MICROPY_PY_BUILTINS_FLOAT
  372. mp_float_t percent;
  373. if (cmp >= period) {
  374. percent = 100.0;
  375. } else {
  376. percent = (mp_float_t)cmp * 100.0 / ((mp_float_t)period);
  377. }
  378. return mp_obj_new_float(percent);
  379. #else
  380. mp_int_t percent;
  381. if (cmp >= period) {
  382. percent = 100;
  383. } else if (cmp > MAX_PERIOD_DIV_100) {
  384. percent = cmp / (period / 100);
  385. } else {
  386. percent = cmp * 100 / period;
  387. }
  388. return mp_obj_new_int(percent);
  389. #endif
  390. }
  391. // Computes the 8-bit value for the DTG field in the BDTR register.
  392. //
  393. // 1 tick = 1 count of the timer's clock (source_freq) divided by div.
  394. // 0-128 ticks in inrements of 1
  395. // 128-256 ticks in increments of 2
  396. // 256-512 ticks in increments of 8
  397. // 512-1008 ticks in increments of 16
  398. STATIC uint32_t compute_dtg_from_ticks(mp_int_t ticks) {
  399. if (ticks <= 0) {
  400. return 0;
  401. }
  402. if (ticks < 128) {
  403. return ticks;
  404. }
  405. if (ticks < 256) {
  406. return 0x80 | ((ticks - 128) / 2);
  407. }
  408. if (ticks < 512) {
  409. return 0xC0 | ((ticks - 256) / 8);
  410. }
  411. if (ticks < 1008) {
  412. return 0xE0 | ((ticks - 512) / 16);
  413. }
  414. return 0xFF;
  415. }
  416. // Given the 8-bit value stored in the DTG field of the BDTR register, compute
  417. // the number of ticks.
  418. STATIC mp_int_t compute_ticks_from_dtg(uint32_t dtg) {
  419. if ((dtg & 0x80) == 0) {
  420. return dtg & 0x7F;
  421. }
  422. if ((dtg & 0xC0) == 0x80) {
  423. return 128 + ((dtg & 0x3F) * 2);
  424. }
  425. if ((dtg & 0xE0) == 0xC0) {
  426. return 256 + ((dtg & 0x1F) * 8);
  427. }
  428. return 512 + ((dtg & 0x1F) * 16);
  429. }
  430. STATIC void config_deadtime(pyb_timer_obj_t *self, mp_int_t ticks) {
  431. TIM_BreakDeadTimeConfigTypeDef deadTimeConfig;
  432. deadTimeConfig.OffStateRunMode = TIM_OSSR_DISABLE;
  433. deadTimeConfig.OffStateIDLEMode = TIM_OSSI_DISABLE;
  434. deadTimeConfig.LockLevel = TIM_LOCKLEVEL_OFF;
  435. deadTimeConfig.DeadTime = compute_dtg_from_ticks(ticks);
  436. deadTimeConfig.BreakState = TIM_BREAK_DISABLE;
  437. deadTimeConfig.BreakPolarity = TIM_BREAKPOLARITY_LOW;
  438. deadTimeConfig.AutomaticOutput = TIM_AUTOMATICOUTPUT_DISABLE;
  439. HAL_TIMEx_ConfigBreakDeadTime(&self->tim, &deadTimeConfig);
  440. }
  441. TIM_HandleTypeDef *pyb_timer_get_handle(mp_obj_t timer) {
  442. if (mp_obj_get_type(timer) != &pyb_timer_type) {
  443. mp_raise_ValueError("need a Timer object");
  444. }
  445. pyb_timer_obj_t *self = MP_OBJ_TO_PTR(timer);
  446. return &self->tim;
  447. }
  448. STATIC void pyb_timer_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
  449. pyb_timer_obj_t *self = MP_OBJ_TO_PTR(self_in);
  450. if (self->tim.State == HAL_TIM_STATE_RESET) {
  451. mp_printf(print, "Timer(%u)", self->tim_id);
  452. } else {
  453. uint32_t prescaler = self->tim.Instance->PSC & 0xffff;
  454. uint32_t period = __HAL_TIM_GET_AUTORELOAD(&self->tim) & TIMER_CNT_MASK(self);
  455. // for efficiency, we compute and print freq as an int (not a float)
  456. uint32_t freq = timer_get_source_freq(self->tim_id) / ((prescaler + 1) * (period + 1));
  457. mp_printf(print, "Timer(%u, freq=%u, prescaler=%u, period=%u, mode=%s, div=%u",
  458. self->tim_id,
  459. freq,
  460. prescaler,
  461. period,
  462. self->tim.Init.CounterMode == TIM_COUNTERMODE_UP ? "UP" :
  463. self->tim.Init.CounterMode == TIM_COUNTERMODE_DOWN ? "DOWN" : "CENTER",
  464. self->tim.Init.ClockDivision == TIM_CLOCKDIVISION_DIV4 ? 4 :
  465. self->tim.Init.ClockDivision == TIM_CLOCKDIVISION_DIV2 ? 2 : 1);
  466. #if defined(IS_TIM_ADVANCED_INSTANCE)
  467. if (IS_TIM_ADVANCED_INSTANCE(self->tim.Instance))
  468. #elif defined(IS_TIM_BREAK_INSTANCE)
  469. if (IS_TIM_BREAK_INSTANCE(self->tim.Instance))
  470. #else
  471. if (0)
  472. #endif
  473. {
  474. mp_printf(print, ", deadtime=%u",
  475. compute_ticks_from_dtg(self->tim.Instance->BDTR & TIM_BDTR_DTG));
  476. }
  477. mp_print_str(print, ")");
  478. }
  479. }
  480. /// \method init(*, freq, prescaler, period)
  481. /// Initialise the timer. Initialisation must be either by frequency (in Hz)
  482. /// or by prescaler and period:
  483. ///
  484. /// tim.init(freq=100) # set the timer to trigger at 100Hz
  485. /// tim.init(prescaler=83, period=999) # set the prescaler and period directly
  486. ///
  487. /// Keyword arguments:
  488. ///
  489. /// - `freq` - specifies the periodic frequency of the timer. You migh also
  490. /// view this as the frequency with which the timer goes through
  491. /// one complete cycle.
  492. ///
  493. /// - `prescaler` [0-0xffff] - specifies the value to be loaded into the
  494. /// timer's Prescaler Register (PSC). The timer clock source is divided by
  495. /// (`prescaler + 1`) to arrive at the timer clock. Timers 2-7 and 12-14
  496. /// have a clock source of 84 MHz (pyb.freq()[2] * 2), and Timers 1, and 8-11
  497. /// have a clock source of 168 MHz (pyb.freq()[3] * 2).
  498. ///
  499. /// - `period` [0-0xffff] for timers 1, 3, 4, and 6-15. [0-0x3fffffff] for timers 2 & 5.
  500. /// Specifies the value to be loaded into the timer's AutoReload
  501. /// Register (ARR). This determines the period of the timer (i.e. when the
  502. /// counter cycles). The timer counter will roll-over after `period + 1`
  503. /// timer clock cycles.
  504. ///
  505. /// - `mode` can be one of:
  506. /// - `Timer.UP` - configures the timer to count from 0 to ARR (default)
  507. /// - `Timer.DOWN` - configures the timer to count from ARR down to 0.
  508. /// - `Timer.CENTER` - confgures the timer to count from 0 to ARR and
  509. /// then back down to 0.
  510. ///
  511. /// - `div` can be one of 1, 2, or 4. Divides the timer clock to determine
  512. /// the sampling clock used by the digital filters.
  513. ///
  514. /// - `callback` - as per Timer.callback()
  515. ///
  516. /// - `deadtime` - specifies the amount of "dead" or inactive time between
  517. /// transitions on complimentary channels (both channels will be inactive)
  518. /// for this time). `deadtime` may be an integer between 0 and 1008, with
  519. /// the following restrictions: 0-128 in steps of 1. 128-256 in steps of
  520. /// 2, 256-512 in steps of 8, and 512-1008 in steps of 16. `deadime`
  521. /// measures ticks of `source_freq` divided by `div` clock ticks.
  522. /// `deadtime` is only available on timers 1 and 8.
  523. ///
  524. /// You must either specify freq or both of period and prescaler.
  525. STATIC mp_obj_t pyb_timer_init_helper(pyb_timer_obj_t *self, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
  526. enum { ARG_freq, ARG_prescaler, ARG_period, ARG_tick_hz, ARG_mode, ARG_div, ARG_callback, ARG_deadtime };
  527. static const mp_arg_t allowed_args[] = {
  528. { MP_QSTR_freq, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_PTR(&mp_const_none_obj)} },
  529. { MP_QSTR_prescaler, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
  530. { MP_QSTR_period, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
  531. { MP_QSTR_tick_hz, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1000} },
  532. { MP_QSTR_mode, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = TIM_COUNTERMODE_UP} },
  533. { MP_QSTR_div, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1} },
  534. { MP_QSTR_callback, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_PTR(&mp_const_none_obj)} },
  535. { MP_QSTR_deadtime, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
  536. };
  537. // parse args
  538. mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
  539. mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
  540. // set the TIM configuration values
  541. TIM_Base_InitTypeDef *init = &self->tim.Init;
  542. if (args[ARG_freq].u_obj != mp_const_none) {
  543. // set prescaler and period from desired frequency
  544. init->Prescaler = compute_prescaler_period_from_freq(self, args[ARG_freq].u_obj, &init->Period);
  545. } else if (args[ARG_prescaler].u_int != 0xffffffff && args[ARG_period].u_int != 0xffffffff) {
  546. // set prescaler and period directly
  547. init->Prescaler = args[ARG_prescaler].u_int;
  548. init->Period = args[ARG_period].u_int;
  549. } else if (args[ARG_period].u_int != 0xffffffff) {
  550. // set prescaler and period from desired period and tick_hz scale
  551. init->Prescaler = compute_prescaler_period_from_t(self, args[ARG_period].u_int, args[ARG_tick_hz].u_int, &init->Period);
  552. } else {
  553. mp_raise_TypeError("must specify either freq, period, or prescaler and period");
  554. }
  555. init->CounterMode = args[ARG_mode].u_int;
  556. if (!IS_TIM_COUNTER_MODE(init->CounterMode)) {
  557. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid mode (%d)", init->CounterMode));
  558. }
  559. init->ClockDivision = args[ARG_div].u_int == 2 ? TIM_CLOCKDIVISION_DIV2 :
  560. args[ARG_div].u_int == 4 ? TIM_CLOCKDIVISION_DIV4 :
  561. TIM_CLOCKDIVISION_DIV1;
  562. init->RepetitionCounter = 0;
  563. // enable TIM clock
  564. switch (self->tim_id) {
  565. case 1: __HAL_RCC_TIM1_CLK_ENABLE(); break;
  566. case 2: __HAL_RCC_TIM2_CLK_ENABLE(); break;
  567. case 3: __HAL_RCC_TIM3_CLK_ENABLE(); break;
  568. #if defined(TIM4)
  569. case 4: __HAL_RCC_TIM4_CLK_ENABLE(); break;
  570. #endif
  571. #if defined(TIM5)
  572. case 5: __HAL_RCC_TIM5_CLK_ENABLE(); break;
  573. #endif
  574. #if defined(TIM6)
  575. case 6: __HAL_RCC_TIM6_CLK_ENABLE(); break;
  576. #endif
  577. #if defined(TIM7)
  578. case 7: __HAL_RCC_TIM7_CLK_ENABLE(); break;
  579. #endif
  580. #if defined(TIM8)
  581. case 8: __HAL_RCC_TIM8_CLK_ENABLE(); break;
  582. #endif
  583. #if defined(TIM9)
  584. case 9: __HAL_RCC_TIM9_CLK_ENABLE(); break;
  585. #endif
  586. #if defined(TIM10)
  587. case 10: __HAL_RCC_TIM10_CLK_ENABLE(); break;
  588. #endif
  589. #if defined(TIM11)
  590. case 11: __HAL_RCC_TIM11_CLK_ENABLE(); break;
  591. #endif
  592. #if defined(TIM12)
  593. case 12: __HAL_RCC_TIM12_CLK_ENABLE(); break;
  594. #endif
  595. #if defined(TIM13)
  596. case 13: __HAL_RCC_TIM13_CLK_ENABLE(); break;
  597. #endif
  598. #if defined(TIM14)
  599. case 14: __HAL_RCC_TIM14_CLK_ENABLE(); break;
  600. #endif
  601. #if defined(TIM15)
  602. case 15: __HAL_RCC_TIM15_CLK_ENABLE(); break;
  603. #endif
  604. #if defined(TIM16)
  605. case 16: __HAL_RCC_TIM16_CLK_ENABLE(); break;
  606. #endif
  607. #if defined(TIM17)
  608. case 17: __HAL_RCC_TIM17_CLK_ENABLE(); break;
  609. #endif
  610. }
  611. // set IRQ priority (if not a special timer)
  612. if (self->tim_id != 5) {
  613. NVIC_SetPriority(IRQn_NONNEG(self->irqn), IRQ_PRI_TIMX);
  614. if (self->tim_id == 1) {
  615. NVIC_SetPriority(TIM1_CC_IRQn, IRQ_PRI_TIMX);
  616. #if defined(TIM8)
  617. } else if (self->tim_id == 8) {
  618. NVIC_SetPriority(TIM8_CC_IRQn, IRQ_PRI_TIMX);
  619. #endif
  620. }
  621. }
  622. // init TIM
  623. HAL_TIM_Base_Init(&self->tim);
  624. #if defined(IS_TIM_ADVANCED_INSTANCE)
  625. if (IS_TIM_ADVANCED_INSTANCE(self->tim.Instance)) {
  626. #elif defined(IS_TIM_BREAK_INSTANCE)
  627. if (IS_TIM_BREAK_INSTANCE(self->tim.Instance)) {
  628. #else
  629. if (0) {
  630. #endif
  631. config_deadtime(self, args[ARG_deadtime].u_int);
  632. }
  633. // Enable ARPE so that the auto-reload register is buffered.
  634. // This allows to smoothly change the frequency of the timer.
  635. self->tim.Instance->CR1 |= TIM_CR1_ARPE;
  636. // Start the timer running
  637. if (args[ARG_callback].u_obj == mp_const_none) {
  638. HAL_TIM_Base_Start(&self->tim);
  639. } else {
  640. pyb_timer_callback(MP_OBJ_FROM_PTR(self), args[ARG_callback].u_obj);
  641. }
  642. return mp_const_none;
  643. }
  644. // This table encodes the timer instance and irq number (for the update irq).
  645. // It assumes that timer instance pointer has the lower 8 bits cleared.
  646. #define TIM_ENTRY(id, irq) [id - 1] = (uint32_t)TIM##id | irq
  647. STATIC const uint32_t tim_instance_table[MICROPY_HW_MAX_TIMER] = {
  648. #if defined(STM32F0)
  649. TIM_ENTRY(1, TIM1_BRK_UP_TRG_COM_IRQn),
  650. #elif defined(STM32F4) || defined(STM32F7)
  651. TIM_ENTRY(1, TIM1_UP_TIM10_IRQn),
  652. #elif defined(STM32L4)
  653. TIM_ENTRY(1, TIM1_UP_TIM16_IRQn),
  654. #endif
  655. TIM_ENTRY(2, TIM2_IRQn),
  656. TIM_ENTRY(3, TIM3_IRQn),
  657. #if defined(TIM4)
  658. TIM_ENTRY(4, TIM4_IRQn),
  659. #endif
  660. #if defined(TIM5)
  661. TIM_ENTRY(5, TIM5_IRQn),
  662. #endif
  663. #if defined(TIM6)
  664. TIM_ENTRY(6, TIM6_DAC_IRQn),
  665. #endif
  666. #if defined(TIM7)
  667. TIM_ENTRY(7, TIM7_IRQn),
  668. #endif
  669. #if defined(TIM8)
  670. #if defined(STM32F4) || defined(STM32F7)
  671. TIM_ENTRY(8, TIM8_UP_TIM13_IRQn),
  672. #elif defined(STM32L4)
  673. TIM_ENTRY(8, TIM8_UP_IRQn),
  674. #endif
  675. #endif
  676. #if defined(TIM9)
  677. TIM_ENTRY(9, TIM1_BRK_TIM9_IRQn),
  678. #endif
  679. #if defined(TIM10)
  680. TIM_ENTRY(10, TIM1_UP_TIM10_IRQn),
  681. #endif
  682. #if defined(TIM11)
  683. TIM_ENTRY(11, TIM1_TRG_COM_TIM11_IRQn),
  684. #endif
  685. #if defined(TIM12)
  686. TIM_ENTRY(12, TIM8_BRK_TIM12_IRQn),
  687. #endif
  688. #if defined(TIM13)
  689. TIM_ENTRY(13, TIM8_UP_TIM13_IRQn),
  690. #endif
  691. #if defined(STM32F0)
  692. TIM_ENTRY(14, TIM14_IRQn),
  693. #elif defined(TIM14)
  694. TIM_ENTRY(14, TIM8_TRG_COM_TIM14_IRQn),
  695. #endif
  696. #if defined(TIM15)
  697. #if defined(STM32F0) || defined(STM32H7)
  698. TIM_ENTRY(15, TIM15_IRQn),
  699. #else
  700. TIM_ENTRY(15, TIM1_BRK_TIM15_IRQn),
  701. #endif
  702. #endif
  703. #if defined(TIM16)
  704. #if defined(STM32F0) || defined(STM32H7)
  705. TIM_ENTRY(16, TIM16_IRQn),
  706. #else
  707. TIM_ENTRY(16, TIM1_UP_TIM16_IRQn),
  708. #endif
  709. #endif
  710. #if defined(TIM17)
  711. #if defined(STM32F0) || defined(STM32H7)
  712. TIM_ENTRY(17, TIM17_IRQn),
  713. #else
  714. TIM_ENTRY(17, TIM1_TRG_COM_TIM17_IRQn),
  715. #endif
  716. #endif
  717. };
  718. #undef TIM_ENTRY
  719. /// \classmethod \constructor(id, ...)
  720. /// Construct a new timer object of the given id. If additional
  721. /// arguments are given, then the timer is initialised by `init(...)`.
  722. /// `id` can be 1 to 14, excluding 3.
  723. STATIC mp_obj_t pyb_timer_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
  724. // check arguments
  725. mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);
  726. // get the timer id
  727. mp_int_t tim_id = mp_obj_get_int(args[0]);
  728. // check if the timer exists
  729. if (tim_id <= 0 || tim_id > MICROPY_HW_MAX_TIMER || tim_instance_table[tim_id - 1] == 0) {
  730. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Timer(%d) doesn't exist", tim_id));
  731. }
  732. pyb_timer_obj_t *tim;
  733. if (MP_STATE_PORT(pyb_timer_obj_all)[tim_id - 1] == NULL) {
  734. // create new Timer object
  735. tim = m_new_obj(pyb_timer_obj_t);
  736. memset(tim, 0, sizeof(*tim));
  737. tim->base.type = &pyb_timer_type;
  738. tim->tim_id = tim_id;
  739. tim->is_32bit = tim_id == 2 || tim_id == 5;
  740. tim->callback = mp_const_none;
  741. uint32_t ti = tim_instance_table[tim_id - 1];
  742. tim->tim.Instance = (TIM_TypeDef*)(ti & 0xffffff00);
  743. tim->irqn = ti & 0xff;
  744. MP_STATE_PORT(pyb_timer_obj_all)[tim_id - 1] = tim;
  745. } else {
  746. // reference existing Timer object
  747. tim = MP_STATE_PORT(pyb_timer_obj_all)[tim_id - 1];
  748. }
  749. if (n_args > 1 || n_kw > 0) {
  750. // start the peripheral
  751. mp_map_t kw_args;
  752. mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
  753. pyb_timer_init_helper(tim, n_args - 1, args + 1, &kw_args);
  754. }
  755. return MP_OBJ_FROM_PTR(tim);
  756. }
  757. STATIC mp_obj_t pyb_timer_init(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
  758. return pyb_timer_init_helper(MP_OBJ_TO_PTR(args[0]), n_args - 1, args + 1, kw_args);
  759. }
  760. STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_timer_init_obj, 1, pyb_timer_init);
  761. // timer.deinit()
  762. STATIC mp_obj_t pyb_timer_deinit(mp_obj_t self_in) {
  763. pyb_timer_obj_t *self = MP_OBJ_TO_PTR(self_in);
  764. // Disable the base interrupt
  765. pyb_timer_callback(self_in, mp_const_none);
  766. pyb_timer_channel_obj_t *chan = self->channel;
  767. self->channel = NULL;
  768. // Disable the channel interrupts
  769. while (chan != NULL) {
  770. pyb_timer_channel_callback(MP_OBJ_FROM_PTR(chan), mp_const_none);
  771. pyb_timer_channel_obj_t *prev_chan = chan;
  772. chan = chan->next;
  773. prev_chan->next = NULL;
  774. }
  775. self->tim.State = HAL_TIM_STATE_RESET;
  776. self->tim.Instance->CCER = 0x0000; // disable all capture/compare outputs
  777. self->tim.Instance->CR1 = 0x0000; // disable the timer and reset its state
  778. return mp_const_none;
  779. }
  780. STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_timer_deinit_obj, pyb_timer_deinit);
  781. /// \method channel(channel, mode, ...)
  782. ///
  783. /// If only a channel number is passed, then a previously initialized channel
  784. /// object is returned (or `None` if there is no previous channel).
  785. ///
  786. /// Othwerwise, a TimerChannel object is initialized and returned.
  787. ///
  788. /// Each channel can be configured to perform pwm, output compare, or
  789. /// input capture. All channels share the same underlying timer, which means
  790. /// that they share the same timer clock.
  791. ///
  792. /// Keyword arguments:
  793. ///
  794. /// - `mode` can be one of:
  795. /// - `Timer.PWM` - configure the timer in PWM mode (active high).
  796. /// - `Timer.PWM_INVERTED` - configure the timer in PWM mode (active low).
  797. /// - `Timer.OC_TIMING` - indicates that no pin is driven.
  798. /// - `Timer.OC_ACTIVE` - the pin will be made active when a compare
  799. /// match occurs (active is determined by polarity)
  800. /// - `Timer.OC_INACTIVE` - the pin will be made inactive when a compare
  801. /// match occurs.
  802. /// - `Timer.OC_TOGGLE` - the pin will be toggled when an compare match occurs.
  803. /// - `Timer.OC_FORCED_ACTIVE` - the pin is forced active (compare match is ignored).
  804. /// - `Timer.OC_FORCED_INACTIVE` - the pin is forced inactive (compare match is ignored).
  805. /// - `Timer.IC` - configure the timer in Input Capture mode.
  806. /// - `Timer.ENC_A` --- configure the timer in Encoder mode. The counter only changes when CH1 changes.
  807. /// - `Timer.ENC_B` --- configure the timer in Encoder mode. The counter only changes when CH2 changes.
  808. /// - `Timer.ENC_AB` --- configure the timer in Encoder mode. The counter changes when CH1 or CH2 changes.
  809. ///
  810. /// - `callback` - as per TimerChannel.callback()
  811. ///
  812. /// - `pin` None (the default) or a Pin object. If specified (and not None)
  813. /// this will cause the alternate function of the the indicated pin
  814. /// to be configured for this timer channel. An error will be raised if
  815. /// the pin doesn't support any alternate functions for this timer channel.
  816. ///
  817. /// Keyword arguments for Timer.PWM modes:
  818. ///
  819. /// - `pulse_width` - determines the initial pulse width value to use.
  820. /// - `pulse_width_percent` - determines the initial pulse width percentage to use.
  821. ///
  822. /// Keyword arguments for Timer.OC modes:
  823. ///
  824. /// - `compare` - determines the initial value of the compare register.
  825. ///
  826. /// - `polarity` can be one of:
  827. /// - `Timer.HIGH` - output is active high
  828. /// - `Timer.LOW` - output is acive low
  829. ///
  830. /// Optional keyword arguments for Timer.IC modes:
  831. ///
  832. /// - `polarity` can be one of:
  833. /// - `Timer.RISING` - captures on rising edge.
  834. /// - `Timer.FALLING` - captures on falling edge.
  835. /// - `Timer.BOTH` - captures on both edges.
  836. ///
  837. /// Note that capture only works on the primary channel, and not on the
  838. /// complimentary channels.
  839. ///
  840. /// Notes for Timer.ENC modes:
  841. ///
  842. /// - Requires 2 pins, so one or both pins will need to be configured to use
  843. /// the appropriate timer AF using the Pin API.
  844. /// - Read the encoder value using the timer.counter() method.
  845. /// - Only works on CH1 and CH2 (and not on CH1N or CH2N)
  846. /// - The channel number is ignored when setting the encoder mode.
  847. ///
  848. /// PWM Example:
  849. ///
  850. /// timer = pyb.Timer(2, freq=1000)
  851. /// ch2 = timer.channel(2, pyb.Timer.PWM, pin=pyb.Pin.board.X2, pulse_width=210000)
  852. /// ch3 = timer.channel(3, pyb.Timer.PWM, pin=pyb.Pin.board.X3, pulse_width=420000)
  853. STATIC mp_obj_t pyb_timer_channel(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
  854. static const mp_arg_t allowed_args[] = {
  855. { MP_QSTR_mode, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 0} },
  856. { MP_QSTR_callback, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_PTR(&mp_const_none_obj)} },
  857. { MP_QSTR_pin, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_PTR(&mp_const_none_obj)} },
  858. { MP_QSTR_pulse_width, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
  859. { MP_QSTR_pulse_width_percent, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_PTR(&mp_const_none_obj)} },
  860. { MP_QSTR_compare, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
  861. { MP_QSTR_polarity, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
  862. };
  863. pyb_timer_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]);
  864. mp_int_t channel = mp_obj_get_int(pos_args[1]);
  865. if (channel < 1 || channel > 4) {
  866. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid channel (%d)", channel));
  867. }
  868. pyb_timer_channel_obj_t *chan = self->channel;
  869. pyb_timer_channel_obj_t *prev_chan = NULL;
  870. while (chan != NULL) {
  871. if (chan->channel == channel) {
  872. break;
  873. }
  874. prev_chan = chan;
  875. chan = chan->next;
  876. }
  877. // If only the channel number is given return the previously allocated
  878. // channel (or None if no previous channel).
  879. if (n_args == 2 && kw_args->used == 0) {
  880. if (chan) {
  881. return MP_OBJ_FROM_PTR(chan);
  882. }
  883. return mp_const_none;
  884. }
  885. // If there was already a channel, then remove it from the list. Note that
  886. // the order we do things here is important so as to appear atomic to
  887. // the IRQ handler.
  888. if (chan) {
  889. // Turn off any IRQ associated with the channel.
  890. pyb_timer_channel_callback(MP_OBJ_FROM_PTR(chan), mp_const_none);
  891. // Unlink the channel from the list.
  892. if (prev_chan) {
  893. prev_chan->next = chan->next;
  894. }
  895. self->channel = chan->next;
  896. chan->next = NULL;
  897. }
  898. // Allocate and initialize a new channel
  899. mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
  900. mp_arg_parse_all(n_args - 2, pos_args + 2, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
  901. chan = m_new_obj(pyb_timer_channel_obj_t);
  902. memset(chan, 0, sizeof(*chan));
  903. chan->base.type = &pyb_timer_channel_type;
  904. chan->timer = self;
  905. chan->channel = channel;
  906. chan->mode = args[0].u_int;
  907. chan->callback = args[1].u_obj;
  908. mp_obj_t pin_obj = args[2].u_obj;
  909. if (pin_obj != mp_const_none) {
  910. if (!MP_OBJ_IS_TYPE(pin_obj, &pin_type)) {
  911. mp_raise_ValueError("pin argument needs to be be a Pin type");
  912. }
  913. const pin_obj_t *pin = MP_OBJ_TO_PTR(pin_obj);
  914. const pin_af_obj_t *af = pin_find_af(pin, AF_FN_TIM, self->tim_id);
  915. if (af == NULL) {
  916. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Pin(%q) doesn't have an af for Timer(%d)", pin->name, self->tim_id));
  917. }
  918. // pin.init(mode=AF_PP, af=idx)
  919. const mp_obj_t args2[6] = {
  920. MP_OBJ_FROM_PTR(&pin_init_obj),
  921. pin_obj,
  922. MP_OBJ_NEW_QSTR(MP_QSTR_mode), MP_OBJ_NEW_SMALL_INT(GPIO_MODE_AF_PP),
  923. MP_OBJ_NEW_QSTR(MP_QSTR_af), MP_OBJ_NEW_SMALL_INT(af->idx)
  924. };
  925. mp_call_method_n_kw(0, 2, args2);
  926. }
  927. // Link the channel to the timer before we turn the channel on.
  928. // Note that this needs to appear atomic to the IRQ handler (the write
  929. // to self->channel is atomic, so we're good, but I thought I'd mention
  930. // in case this was ever changed in the future).
  931. chan->next = self->channel;
  932. self->channel = chan;
  933. switch (chan->mode) {
  934. case CHANNEL_MODE_PWM_NORMAL:
  935. case CHANNEL_MODE_PWM_INVERTED: {
  936. TIM_OC_InitTypeDef oc_config;
  937. oc_config.OCMode = channel_mode_info[chan->mode].oc_mode;
  938. if (args[4].u_obj != mp_const_none) {
  939. // pulse width percent given
  940. uint32_t period = compute_period(self);
  941. oc_config.Pulse = compute_pwm_value_from_percent(period, args[4].u_obj);
  942. } else {
  943. // use absolute pulse width value (defaults to 0 if nothing given)
  944. oc_config.Pulse = args[3].u_int;
  945. }
  946. oc_config.OCPolarity = TIM_OCPOLARITY_HIGH;
  947. oc_config.OCNPolarity = TIM_OCNPOLARITY_HIGH;
  948. oc_config.OCFastMode = TIM_OCFAST_DISABLE;
  949. oc_config.OCIdleState = TIM_OCIDLESTATE_SET;
  950. oc_config.OCNIdleState = TIM_OCNIDLESTATE_SET;
  951. HAL_TIM_PWM_ConfigChannel(&self->tim, &oc_config, TIMER_CHANNEL(chan));
  952. if (chan->callback == mp_const_none) {
  953. HAL_TIM_PWM_Start(&self->tim, TIMER_CHANNEL(chan));
  954. } else {
  955. pyb_timer_channel_callback(MP_OBJ_FROM_PTR(chan), chan->callback);
  956. }
  957. // Start the complimentary channel too (if its supported)
  958. if (IS_TIM_CCXN_INSTANCE(self->tim.Instance, TIMER_CHANNEL(chan))) {
  959. HAL_TIMEx_PWMN_Start(&self->tim, TIMER_CHANNEL(chan));
  960. }
  961. break;
  962. }
  963. case CHANNEL_MODE_OC_TIMING:
  964. case CHANNEL_MODE_OC_ACTIVE:
  965. case CHANNEL_MODE_OC_INACTIVE:
  966. case CHANNEL_MODE_OC_TOGGLE:
  967. case CHANNEL_MODE_OC_FORCED_ACTIVE:
  968. case CHANNEL_MODE_OC_FORCED_INACTIVE: {
  969. TIM_OC_InitTypeDef oc_config;
  970. oc_config.OCMode = channel_mode_info[chan->mode].oc_mode;
  971. oc_config.Pulse = args[5].u_int;
  972. oc_config.OCPolarity = args[6].u_int;
  973. if (oc_config.OCPolarity == 0xffffffff) {
  974. oc_config.OCPolarity = TIM_OCPOLARITY_HIGH;
  975. }
  976. if (oc_config.OCPolarity == TIM_OCPOLARITY_HIGH) {
  977. oc_config.OCNPolarity = TIM_OCNPOLARITY_HIGH;
  978. } else {
  979. oc_config.OCNPolarity = TIM_OCNPOLARITY_LOW;
  980. }
  981. oc_config.OCFastMode = TIM_OCFAST_DISABLE;
  982. oc_config.OCIdleState = TIM_OCIDLESTATE_SET;
  983. oc_config.OCNIdleState = TIM_OCNIDLESTATE_SET;
  984. if (!IS_TIM_OC_POLARITY(oc_config.OCPolarity)) {
  985. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid polarity (%d)", oc_config.OCPolarity));
  986. }
  987. HAL_TIM_OC_ConfigChannel(&self->tim, &oc_config, TIMER_CHANNEL(chan));
  988. if (chan->callback == mp_const_none) {
  989. HAL_TIM_OC_Start(&self->tim, TIMER_CHANNEL(chan));
  990. } else {
  991. pyb_timer_channel_callback(MP_OBJ_FROM_PTR(chan), chan->callback);
  992. }
  993. // Start the complimentary channel too (if its supported)
  994. if (IS_TIM_CCXN_INSTANCE(self->tim.Instance, TIMER_CHANNEL(chan))) {
  995. HAL_TIMEx_OCN_Start(&self->tim, TIMER_CHANNEL(chan));
  996. }
  997. break;
  998. }
  999. case CHANNEL_MODE_IC: {
  1000. TIM_IC_InitTypeDef ic_config;
  1001. ic_config.ICPolarity = args[6].u_int;
  1002. if (ic_config.ICPolarity == 0xffffffff) {
  1003. ic_config.ICPolarity = TIM_ICPOLARITY_RISING;
  1004. }
  1005. ic_config.ICSelection = TIM_ICSELECTION_DIRECTTI;
  1006. ic_config.ICPrescaler = TIM_ICPSC_DIV1;
  1007. ic_config.ICFilter = 0;
  1008. if (!IS_TIM_IC_POLARITY(ic_config.ICPolarity)) {
  1009. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid polarity (%d)", ic_config.ICPolarity));
  1010. }
  1011. HAL_TIM_IC_ConfigChannel(&self->tim, &ic_config, TIMER_CHANNEL(chan));
  1012. if (chan->callback == mp_const_none) {
  1013. HAL_TIM_IC_Start(&self->tim, TIMER_CHANNEL(chan));
  1014. } else {
  1015. pyb_timer_channel_callback(MP_OBJ_FROM_PTR(chan), chan->callback);
  1016. }
  1017. break;
  1018. }
  1019. case CHANNEL_MODE_ENC_A:
  1020. case CHANNEL_MODE_ENC_B:
  1021. case CHANNEL_MODE_ENC_AB: {
  1022. TIM_Encoder_InitTypeDef enc_config;
  1023. enc_config.EncoderMode = channel_mode_info[chan->mode].oc_mode;
  1024. enc_config.IC1Polarity = args[6].u_int;
  1025. if (enc_config.IC1Polarity == 0xffffffff) {
  1026. enc_config.IC1Polarity = TIM_ICPOLARITY_RISING;
  1027. }
  1028. enc_config.IC2Polarity = enc_config.IC1Polarity;
  1029. enc_config.IC1Selection = TIM_ICSELECTION_DIRECTTI;
  1030. enc_config.IC2Selection = TIM_ICSELECTION_DIRECTTI;
  1031. enc_config.IC1Prescaler = TIM_ICPSC_DIV1;
  1032. enc_config.IC2Prescaler = TIM_ICPSC_DIV1;
  1033. enc_config.IC1Filter = 0;
  1034. enc_config.IC2Filter = 0;
  1035. if (!IS_TIM_IC_POLARITY(enc_config.IC1Polarity)) {
  1036. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid polarity (%d)", enc_config.IC1Polarity));
  1037. }
  1038. // Only Timers 1, 2, 3, 4, 5, and 8 support encoder mode
  1039. if (self->tim.Instance != TIM1
  1040. && self->tim.Instance != TIM2
  1041. && self->tim.Instance != TIM3
  1042. #if defined(TIM4)
  1043. && self->tim.Instance != TIM4
  1044. #endif
  1045. #if defined(TIM5)
  1046. && self->tim.Instance != TIM5
  1047. #endif
  1048. #if defined(TIM8)
  1049. && self->tim.Instance != TIM8
  1050. #endif
  1051. ) {
  1052. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "encoder not supported on timer %d", self->tim_id));
  1053. }
  1054. // Disable & clear the timer interrupt so that we don't trigger
  1055. // an interrupt by initializing the timer.
  1056. __HAL_TIM_DISABLE_IT(&self->tim, TIM_IT_UPDATE);
  1057. HAL_TIM_Encoder_Init(&self->tim, &enc_config);
  1058. __HAL_TIM_SET_COUNTER(&self->tim, 0);
  1059. if (self->callback != mp_const_none) {
  1060. __HAL_TIM_CLEAR_FLAG(&self->tim, TIM_IT_UPDATE);
  1061. __HAL_TIM_ENABLE_IT(&self->tim, TIM_IT_UPDATE);
  1062. }
  1063. HAL_TIM_Encoder_Start(&self->tim, TIM_CHANNEL_ALL);
  1064. break;
  1065. }
  1066. default:
  1067. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid mode (%d)", chan->mode));
  1068. }
  1069. return MP_OBJ_FROM_PTR(chan);
  1070. }
  1071. STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_timer_channel_obj, 2, pyb_timer_channel);
  1072. /// \method counter([value])
  1073. /// Get or set the timer counter.
  1074. STATIC mp_obj_t pyb_timer_counter(size_t n_args, const mp_obj_t *args) {
  1075. pyb_timer_obj_t *self = MP_OBJ_TO_PTR(args[0]);
  1076. if (n_args == 1) {
  1077. // get
  1078. return mp_obj_new_int(self->tim.Instance->CNT);
  1079. } else {
  1080. // set
  1081. __HAL_TIM_SET_COUNTER(&self->tim, mp_obj_get_int(args[1]));
  1082. return mp_const_none;
  1083. }
  1084. }
  1085. STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_counter_obj, 1, 2, pyb_timer_counter);
  1086. /// \method source_freq()
  1087. /// Get the frequency of the source of the timer.
  1088. STATIC mp_obj_t pyb_timer_source_freq(mp_obj_t self_in) {
  1089. pyb_timer_obj_t *self = MP_OBJ_TO_PTR(self_in);
  1090. uint32_t source_freq = timer_get_source_freq(self->tim_id);
  1091. return mp_obj_new_int(source_freq);
  1092. }
  1093. STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_timer_source_freq_obj, pyb_timer_source_freq);
  1094. /// \method freq([value])
  1095. /// Get or set the frequency for the timer (changes prescaler and period if set).
  1096. STATIC mp_obj_t pyb_timer_freq(size_t n_args, const mp_obj_t *args) {
  1097. pyb_timer_obj_t *self = MP_OBJ_TO_PTR(args[0]);
  1098. if (n_args == 1) {
  1099. // get
  1100. uint32_t prescaler = self->tim.Instance->PSC & 0xffff;
  1101. uint32_t period = __HAL_TIM_GET_AUTORELOAD(&self->tim) & TIMER_CNT_MASK(self);
  1102. uint32_t source_freq = timer_get_source_freq(self->tim_id);
  1103. uint32_t divide = ((prescaler + 1) * (period + 1));
  1104. #if MICROPY_PY_BUILTINS_FLOAT
  1105. if (source_freq % divide != 0) {
  1106. return mp_obj_new_float((float)source_freq / (float)divide);
  1107. } else
  1108. #endif
  1109. {
  1110. return mp_obj_new_int(source_freq / divide);
  1111. }
  1112. } else {
  1113. // set
  1114. uint32_t period;
  1115. uint32_t prescaler = compute_prescaler_period_from_freq(self, args[1], &period);
  1116. self->tim.Instance->PSC = prescaler;
  1117. __HAL_TIM_SET_AUTORELOAD(&self->tim, period);
  1118. return mp_const_none;
  1119. }
  1120. }
  1121. STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_freq_obj, 1, 2, pyb_timer_freq);
  1122. /// \method prescaler([value])
  1123. /// Get or set the prescaler for the timer.
  1124. STATIC mp_obj_t pyb_timer_prescaler(size_t n_args, const mp_obj_t *args) {
  1125. pyb_timer_obj_t *self = MP_OBJ_TO_PTR(args[0]);
  1126. if (n_args == 1) {
  1127. // get
  1128. return mp_obj_new_int(self->tim.Instance->PSC & 0xffff);
  1129. } else {
  1130. // set
  1131. self->tim.Instance->PSC = mp_obj_get_int(args[1]) & 0xffff;
  1132. return mp_const_none;
  1133. }
  1134. }
  1135. STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_prescaler_obj, 1, 2, pyb_timer_prescaler);
  1136. /// \method period([value])
  1137. /// Get or set the period of the timer.
  1138. STATIC mp_obj_t pyb_timer_period(size_t n_args, const mp_obj_t *args) {
  1139. pyb_timer_obj_t *self = MP_OBJ_TO_PTR(args[0]);
  1140. if (n_args == 1) {
  1141. // get
  1142. return mp_obj_new_int(__HAL_TIM_GET_AUTORELOAD(&self->tim) & TIMER_CNT_MASK(self));
  1143. } else {
  1144. // set
  1145. __HAL_TIM_SET_AUTORELOAD(&self->tim, mp_obj_get_int(args[1]) & TIMER_CNT_MASK(self));
  1146. return mp_const_none;
  1147. }
  1148. }
  1149. STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_period_obj, 1, 2, pyb_timer_period);
  1150. /// \method callback(fun)
  1151. /// Set the function to be called when the timer triggers.
  1152. /// `fun` is passed 1 argument, the timer object.
  1153. /// If `fun` is `None` then the callback will be disabled.
  1154. STATIC mp_obj_t pyb_timer_callback(mp_obj_t self_in, mp_obj_t callback) {
  1155. pyb_timer_obj_t *self = MP_OBJ_TO_PTR(self_in);
  1156. if (callback == mp_const_none) {
  1157. // stop interrupt (but not timer)
  1158. __HAL_TIM_DISABLE_IT(&self->tim, TIM_IT_UPDATE);
  1159. self->callback = mp_const_none;
  1160. } else if (mp_obj_is_callable(callback)) {
  1161. __HAL_TIM_DISABLE_IT(&self->tim, TIM_IT_UPDATE);
  1162. self->callback = callback;
  1163. // start timer, so that it interrupts on overflow, but clear any
  1164. // pending interrupts which may have been set by initializing it.
  1165. __HAL_TIM_CLEAR_FLAG(&self->tim, TIM_IT_UPDATE);
  1166. HAL_TIM_Base_Start_IT(&self->tim); // This will re-enable the IRQ
  1167. HAL_NVIC_EnableIRQ(self->irqn);
  1168. } else {
  1169. mp_raise_ValueError("callback must be None or a callable object");
  1170. }
  1171. return mp_const_none;
  1172. }
  1173. STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_timer_callback_obj, pyb_timer_callback);
  1174. STATIC const mp_rom_map_elem_t pyb_timer_locals_dict_table[] = {
  1175. // instance methods
  1176. { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&pyb_timer_init_obj) },
  1177. { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&pyb_timer_deinit_obj) },
  1178. { MP_ROM_QSTR(MP_QSTR_channel), MP_ROM_PTR(&pyb_timer_channel_obj) },
  1179. { MP_ROM_QSTR(MP_QSTR_counter), MP_ROM_PTR(&pyb_timer_counter_obj) },
  1180. { MP_ROM_QSTR(MP_QSTR_source_freq), MP_ROM_PTR(&pyb_timer_source_freq_obj) },
  1181. { MP_ROM_QSTR(MP_QSTR_freq), MP_ROM_PTR(&pyb_timer_freq_obj) },
  1182. { MP_ROM_QSTR(MP_QSTR_prescaler), MP_ROM_PTR(&pyb_timer_prescaler_obj) },
  1183. { MP_ROM_QSTR(MP_QSTR_period), MP_ROM_PTR(&pyb_timer_period_obj) },
  1184. { MP_ROM_QSTR(MP_QSTR_callback), MP_ROM_PTR(&pyb_timer_callback_obj) },
  1185. { MP_ROM_QSTR(MP_QSTR_UP), MP_ROM_INT(TIM_COUNTERMODE_UP) },
  1186. { MP_ROM_QSTR(MP_QSTR_DOWN), MP_ROM_INT(TIM_COUNTERMODE_DOWN) },
  1187. { MP_ROM_QSTR(MP_QSTR_CENTER), MP_ROM_INT(TIM_COUNTERMODE_CENTERALIGNED1) },
  1188. { MP_ROM_QSTR(MP_QSTR_PWM), MP_ROM_INT(CHANNEL_MODE_PWM_NORMAL) },
  1189. { MP_ROM_QSTR(MP_QSTR_PWM_INVERTED), MP_ROM_INT(CHANNEL_MODE_PWM_INVERTED) },
  1190. { MP_ROM_QSTR(MP_QSTR_OC_TIMING), MP_ROM_INT(CHANNEL_MODE_OC_TIMING) },
  1191. { MP_ROM_QSTR(MP_QSTR_OC_ACTIVE), MP_ROM_INT(CHANNEL_MODE_OC_ACTIVE) },
  1192. { MP_ROM_QSTR(MP_QSTR_OC_INACTIVE), MP_ROM_INT(CHANNEL_MODE_OC_INACTIVE) },
  1193. { MP_ROM_QSTR(MP_QSTR_OC_TOGGLE), MP_ROM_INT(CHANNEL_MODE_OC_TOGGLE) },
  1194. { MP_ROM_QSTR(MP_QSTR_OC_FORCED_ACTIVE), MP_ROM_INT(CHANNEL_MODE_OC_FORCED_ACTIVE) },
  1195. { MP_ROM_QSTR(MP_QSTR_OC_FORCED_INACTIVE), MP_ROM_INT(CHANNEL_MODE_OC_FORCED_INACTIVE) },
  1196. { MP_ROM_QSTR(MP_QSTR_IC), MP_ROM_INT(CHANNEL_MODE_IC) },
  1197. { MP_ROM_QSTR(MP_QSTR_ENC_A), MP_ROM_INT(CHANNEL_MODE_ENC_A) },
  1198. { MP_ROM_QSTR(MP_QSTR_ENC_B), MP_ROM_INT(CHANNEL_MODE_ENC_B) },
  1199. { MP_ROM_QSTR(MP_QSTR_ENC_AB), MP_ROM_INT(CHANNEL_MODE_ENC_AB) },
  1200. { MP_ROM_QSTR(MP_QSTR_HIGH), MP_ROM_INT(TIM_OCPOLARITY_HIGH) },
  1201. { MP_ROM_QSTR(MP_QSTR_LOW), MP_ROM_INT(TIM_OCPOLARITY_LOW) },
  1202. { MP_ROM_QSTR(MP_QSTR_RISING), MP_ROM_INT(TIM_ICPOLARITY_RISING) },
  1203. { MP_ROM_QSTR(MP_QSTR_FALLING), MP_ROM_INT(TIM_ICPOLARITY_FALLING) },
  1204. { MP_ROM_QSTR(MP_QSTR_BOTH), MP_ROM_INT(TIM_ICPOLARITY_BOTHEDGE) },
  1205. };
  1206. STATIC MP_DEFINE_CONST_DICT(pyb_timer_locals_dict, pyb_timer_locals_dict_table);
  1207. const mp_obj_type_t pyb_timer_type = {
  1208. { &mp_type_type },
  1209. .name = MP_QSTR_Timer,
  1210. .print = pyb_timer_print,
  1211. .make_new = pyb_timer_make_new,
  1212. .locals_dict = (mp_obj_dict_t*)&pyb_timer_locals_dict,
  1213. };
  1214. /// \moduleref pyb
  1215. /// \class TimerChannel - setup a channel for a timer.
  1216. ///
  1217. /// Timer channels are used to generate/capture a signal using a timer.
  1218. ///
  1219. /// TimerChannel objects are created using the Timer.channel() method.
  1220. STATIC void pyb_timer_channel_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
  1221. pyb_timer_channel_obj_t *self = MP_OBJ_TO_PTR(self_in);
  1222. mp_printf(print, "TimerChannel(timer=%u, channel=%u, mode=%s)",
  1223. self->timer->tim_id,
  1224. self->channel,
  1225. qstr_str(channel_mode_info[self->mode].name));
  1226. }
  1227. /// \method capture([value])
  1228. /// Get or set the capture value associated with a channel.
  1229. /// capture, compare, and pulse_width are all aliases for the same function.
  1230. /// capture is the logical name to use when the channel is in input capture mode.
  1231. /// \method compare([value])
  1232. /// Get or set the compare value associated with a channel.
  1233. /// capture, compare, and pulse_width are all aliases for the same function.
  1234. /// compare is the logical name to use when the channel is in output compare mode.
  1235. /// \method pulse_width([value])
  1236. /// Get or set the pulse width value associated with a channel.
  1237. /// capture, compare, and pulse_width are all aliases for the same function.
  1238. /// pulse_width is the logical name to use when the channel is in PWM mode.
  1239. ///
  1240. /// In edge aligned mode, a pulse_width of `period + 1` corresponds to a duty cycle of 100%
  1241. /// In center aligned mode, a pulse width of `period` corresponds to a duty cycle of 100%
  1242. STATIC mp_obj_t pyb_timer_channel_capture_compare(size_t n_args, const mp_obj_t *args) {
  1243. pyb_timer_channel_obj_t *self = MP_OBJ_TO_PTR(args[0]);
  1244. if (n_args == 1) {
  1245. // get
  1246. return mp_obj_new_int(__HAL_TIM_GET_COMPARE(&self->timer->tim, TIMER_CHANNEL(self)) & TIMER_CNT_MASK(self->timer));
  1247. } else {
  1248. // set
  1249. __HAL_TIM_SET_COMPARE(&self->timer->tim, TIMER_CHANNEL(self), mp_obj_get_int(args[1]) & TIMER_CNT_MASK(self->timer));
  1250. return mp_const_none;
  1251. }
  1252. }
  1253. STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_channel_capture_compare_obj, 1, 2, pyb_timer_channel_capture_compare);
  1254. /// \method pulse_width_percent([value])
  1255. /// Get or set the pulse width percentage associated with a channel. The value
  1256. /// is a number between 0 and 100 and sets the percentage of the timer period
  1257. /// for which the pulse is active. The value can be an integer or
  1258. /// floating-point number for more accuracy. For example, a value of 25 gives
  1259. /// a duty cycle of 25%.
  1260. STATIC mp_obj_t pyb_timer_channel_pulse_width_percent(size_t n_args, const mp_obj_t *args) {
  1261. pyb_timer_channel_obj_t *self = MP_OBJ_TO_PTR(args[0]);
  1262. uint32_t period = compute_period(self->timer);
  1263. if (n_args == 1) {
  1264. // get
  1265. uint32_t cmp = __HAL_TIM_GET_COMPARE(&self->timer->tim, TIMER_CHANNEL(self)) & TIMER_CNT_MASK(self->timer);
  1266. return compute_percent_from_pwm_value(period, cmp);
  1267. } else {
  1268. // set
  1269. uint32_t cmp = compute_pwm_value_from_percent(period, args[1]);
  1270. __HAL_TIM_SET_COMPARE(&self->timer->tim, TIMER_CHANNEL(self), cmp & TIMER_CNT_MASK(self->timer));
  1271. return mp_const_none;
  1272. }
  1273. }
  1274. STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_channel_pulse_width_percent_obj, 1, 2, pyb_timer_channel_pulse_width_percent);
  1275. /// \method callback(fun)
  1276. /// Set the function to be called when the timer channel triggers.
  1277. /// `fun` is passed 1 argument, the timer object.
  1278. /// If `fun` is `None` then the callback will be disabled.
  1279. STATIC mp_obj_t pyb_timer_channel_callback(mp_obj_t self_in, mp_obj_t callback) {
  1280. pyb_timer_channel_obj_t *self = MP_OBJ_TO_PTR(self_in);
  1281. if (callback == mp_const_none) {
  1282. // stop interrupt (but not timer)
  1283. __HAL_TIM_DISABLE_IT(&self->timer->tim, TIMER_IRQ_MASK(self->channel));
  1284. self->callback = mp_const_none;
  1285. } else if (mp_obj_is_callable(callback)) {
  1286. self->callback = callback;
  1287. uint8_t tim_id = self->timer->tim_id;
  1288. __HAL_TIM_CLEAR_IT(&self->timer->tim, TIMER_IRQ_MASK(self->channel));
  1289. if (tim_id == 1) {
  1290. HAL_NVIC_EnableIRQ(TIM1_CC_IRQn);
  1291. #if defined(TIM8) // STM32F401 doesn't have a TIM8
  1292. } else if (tim_id == 8) {
  1293. HAL_NVIC_EnableIRQ(TIM8_CC_IRQn);
  1294. #endif
  1295. } else {
  1296. HAL_NVIC_EnableIRQ(self->timer->irqn);
  1297. }
  1298. // start timer, so that it interrupts on overflow
  1299. switch (self->mode) {
  1300. case CHANNEL_MODE_PWM_NORMAL:
  1301. case CHANNEL_MODE_PWM_INVERTED:
  1302. HAL_TIM_PWM_Start_IT(&self->timer->tim, TIMER_CHANNEL(self));
  1303. break;
  1304. case CHANNEL_MODE_OC_TIMING:
  1305. case CHANNEL_MODE_OC_ACTIVE:
  1306. case CHANNEL_MODE_OC_INACTIVE:
  1307. case CHANNEL_MODE_OC_TOGGLE:
  1308. case CHANNEL_MODE_OC_FORCED_ACTIVE:
  1309. case CHANNEL_MODE_OC_FORCED_INACTIVE:
  1310. HAL_TIM_OC_Start_IT(&self->timer->tim, TIMER_CHANNEL(self));
  1311. break;
  1312. case CHANNEL_MODE_IC:
  1313. HAL_TIM_IC_Start_IT(&self->timer->tim, TIMER_CHANNEL(self));
  1314. break;
  1315. }
  1316. } else {
  1317. mp_raise_ValueError("callback must be None or a callable object");
  1318. }
  1319. return mp_const_none;
  1320. }
  1321. STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_timer_channel_callback_obj, pyb_timer_channel_callback);
  1322. STATIC const mp_rom_map_elem_t pyb_timer_channel_locals_dict_table[] = {
  1323. // instance methods
  1324. { MP_ROM_QSTR(MP_QSTR_callback), MP_ROM_PTR(&pyb_timer_channel_callback_obj) },
  1325. { MP_ROM_QSTR(MP_QSTR_pulse_width), MP_ROM_PTR(&pyb_timer_channel_capture_compare_obj) },
  1326. { MP_ROM_QSTR(MP_QSTR_pulse_width_percent), MP_ROM_PTR(&pyb_timer_channel_pulse_width_percent_obj) },
  1327. { MP_ROM_QSTR(MP_QSTR_capture), MP_ROM_PTR(&pyb_timer_channel_capture_compare_obj) },
  1328. { MP_ROM_QSTR(MP_QSTR_compare), MP_ROM_PTR(&pyb_timer_channel_capture_compare_obj) },
  1329. };
  1330. STATIC MP_DEFINE_CONST_DICT(pyb_timer_channel_locals_dict, pyb_timer_channel_locals_dict_table);
  1331. STATIC const mp_obj_type_t pyb_timer_channel_type = {
  1332. { &mp_type_type },
  1333. .name = MP_QSTR_TimerChannel,
  1334. .print = pyb_timer_channel_print,
  1335. .locals_dict = (mp_obj_dict_t*)&pyb_timer_channel_locals_dict,
  1336. };
  1337. STATIC void timer_handle_irq_channel(pyb_timer_obj_t *tim, uint8_t channel, mp_obj_t callback) {
  1338. uint32_t irq_mask = TIMER_IRQ_MASK(channel);
  1339. if (__HAL_TIM_GET_FLAG(&tim->tim, irq_mask) != RESET) {
  1340. if (__HAL_TIM_GET_IT_SOURCE(&tim->tim, irq_mask) != RESET) {
  1341. // clear the interrupt
  1342. __HAL_TIM_CLEAR_IT(&tim->tim, irq_mask);
  1343. // execute callback if it's set
  1344. if (callback != mp_const_none) {
  1345. mp_sched_lock();
  1346. // When executing code within a handler we must lock the GC to prevent
  1347. // any memory allocations. We must also catch any exceptions.
  1348. gc_lock();
  1349. nlr_buf_t nlr;
  1350. if (nlr_push(&nlr) == 0) {
  1351. mp_call_function_1(callback, MP_OBJ_FROM_PTR(tim));
  1352. nlr_pop();
  1353. } else {
  1354. // Uncaught exception; disable the callback so it doesn't run again.
  1355. tim->callback = mp_const_none;
  1356. __HAL_TIM_DISABLE_IT(&tim->tim, irq_mask);
  1357. if (channel == 0) {
  1358. printf("uncaught exception in Timer(%u) interrupt handler\n", tim->tim_id);
  1359. } else {
  1360. printf("uncaught exception in Timer(%u) channel %u interrupt handler\n", tim->tim_id, channel);
  1361. }
  1362. mp_obj_print_exception(&mp_plat_print, MP_OBJ_FROM_PTR(nlr.ret_val));
  1363. }
  1364. gc_unlock();
  1365. mp_sched_unlock();
  1366. }
  1367. }
  1368. }
  1369. }
  1370. void timer_irq_handler(uint tim_id) {
  1371. if (tim_id - 1 < PYB_TIMER_OBJ_ALL_NUM) {
  1372. // get the timer object
  1373. pyb_timer_obj_t *tim = MP_STATE_PORT(pyb_timer_obj_all)[tim_id - 1];
  1374. if (tim == NULL) {
  1375. // Timer object has not been set, so we can't do anything.
  1376. // This can happen under normal circumstances for timers like
  1377. // 1 & 10 which use the same IRQ.
  1378. return;
  1379. }
  1380. // Check for timer (versus timer channel) interrupt.
  1381. timer_handle_irq_channel(tim, 0, tim->callback);
  1382. uint32_t handled = TIMER_IRQ_MASK(0);
  1383. // Check to see if a timer channel interrupt was pending
  1384. pyb_timer_channel_obj_t *chan = tim->channel;
  1385. while (chan != NULL) {
  1386. timer_handle_irq_channel(tim, chan->channel, chan->callback);
  1387. handled |= TIMER_IRQ_MASK(chan->channel);
  1388. chan = chan->next;
  1389. }
  1390. // Finally, clear any remaining interrupt sources. Otherwise we'll
  1391. // just get called continuously.
  1392. uint32_t unhandled = tim->tim.Instance->DIER & 0xff & ~handled;
  1393. if (unhandled != 0) {
  1394. __HAL_TIM_DISABLE_IT(&tim->tim, unhandled);
  1395. __HAL_TIM_CLEAR_IT(&tim->tim, unhandled);
  1396. printf("Unhandled interrupt SR=0x%02x (now disabled)\n", (unsigned int)unhandled);
  1397. }
  1398. }
  1399. }