int timer_set_pwm_duty(hacs_pwm_chan_t pwm, float percent) { hacs_timer_t tim = (pwm > HACS_PWM_CHAN_4) ? HACS_PWM_TIMER_1 : HACS_PWM_TIMER_0; TIM_HandleTypeDef *htim = &tim_handles[tim]; uint32_t period = __HAL_TIM_GetAutoreload(htim); uint32_t compare = (uint32_t)((float)period*percent); __HAL_TIM_SetCompare(htim, pwm_chan_to_tim_chan[pwm], compare); return HACS_NO_ERROR; }
// Helper function for determining the period used for calculating percent STATIC uint32_t compute_period(pyb_timer_obj_t *self) { // In center mode, compare == period corresponds to 100% // In edge mode, compare == (period + 1) corresponds to 100% uint32_t period = (__HAL_TIM_GetAutoreload(&self->tim) & TIMER_CNT_MASK(self)); if (period != 0xffffffff) { if (self->tim.Init.CounterMode == TIM_COUNTERMODE_UP || self->tim.Init.CounterMode == TIM_COUNTERMODE_DOWN) { // Edge mode period++; } } return period; }
STATIC void pyb_timer_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) { pyb_timer_obj_t *self = self_in; if (self->tim.State == HAL_TIM_STATE_RESET) { print(env, "Timer(%u)", self->tim_id); } else { print(env, "Timer(%u, prescaler=%u, period=%u, mode=%s, div=%u)", self->tim_id, self->tim.Instance->PSC & 0xffff, __HAL_TIM_GetAutoreload(&self->tim) & TIMER_CNT_MASK(self), self->tim.Init.CounterMode == TIM_COUNTERMODE_UP ? "UP" : self->tim.Init.CounterMode == TIM_COUNTERMODE_DOWN ? "DOWN" : "CENTER", self->tim.Init.ClockDivision == TIM_CLOCKDIVISION_DIV4 ? 4 : self->tim.Init.ClockDivision == TIM_CLOCKDIVISION_DIV2 ? 2 : 1); } }