Skip to content

Instantly share code, notes, and snippets.

@niraami
Last active July 11, 2022 18:23
Show Gist options
  • Save niraami/1012c3d5a077137caada4a6420fddf05 to your computer and use it in GitHub Desktop.
Save niraami/1012c3d5a077137caada4a6420fddf05 to your computer and use it in GitHub Desktop.
Simple method for setting PWM duty cycle on the STM32 (HAL)
static void setDutyCycle(TIM_HandleTypeDef* const htim, uint32_t channel, float duty_cycle) {
if (duty_cycle > 100) duty_cycle = 100;
if (duty_cycle < 0) duty_cycle = 0;
float pw_resolution = (((float)(*htim).Init.Period + 1.0f) / 100.0f);
uint16_t pw_desired = pw_resolution * duty_cycle;
__HAL_TIM_SET_COMPARE(htim, channel, pw_desired);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment