You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
2.0 KiB

2 years ago
  1. #include "zpwm_generator.hpp"
  2. #include "zirq_dispatcher.hpp"
  3. using namespace iflytop;
  4. void ZPWMGenerator::initialize(zchip_tim_t *htim, uint32_t channel, float freq, bool polarity) {
  5. m_htim = htim;
  6. m_polarity = polarity;
  7. m_channel = channel;
  8. m_freq = freq;
  9. ZASSERT(m_htim->Init.AutoReloadPreload == TIM_AUTORELOAD_PRELOAD_ENABLE);
  10. ZASSERT(m_htim->Init.CounterMode == TIM_COUNTERMODE_UP);
  11. }
  12. /******************************************************
  13. * kTimMode_timer *
  14. ******************************************************/
  15. void ZPWMGenerator::startPWM(float duty) { startPWM(m_freq, duty); }
  16. void ZPWMGenerator::startPWM(float freq, float duty) {
  17. if (!m_polarity) {
  18. duty = 100.0 - duty;
  19. }
  20. m_freq = freq;
  21. uint32_t prescaler = 0;
  22. uint32_t autoreload = 0;
  23. uint32_t timClkFreq = chip_get_timer_clock_sorce_freq(m_htim);
  24. ZASSERT(chip_calculate_prescaler_and_autoreload_by_expect_freq(timClkFreq, freq, &prescaler, &autoreload));
  25. __HAL_TIM_SET_AUTORELOAD(m_htim, autoreload);
  26. __HAL_TIM_SET_PRESCALER(m_htim, prescaler);
  27. // printf("auto reload %d %f %f\n", autoreload, duty, duty / 100.0 * __HAL_TIM_GET_AUTORELOAD(m_htim));
  28. /**
  29. * @brief
  30. */
  31. TIM_OC_InitTypeDef sConfigOC = {0};
  32. sConfigOC.OCMode = TIM_OCMODE_PWM1;
  33. sConfigOC.Pulse = duty / 100.0 * __HAL_TIM_GET_AUTORELOAD(m_htim);
  34. sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
  35. sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
  36. sConfigOC.OCIdleState = TIM_OCIDLESTATE_RESET;
  37. sConfigOC.OCNIdleState = TIM_OCNIDLESTATE_RESET;
  38. if (HAL_TIM_PWM_ConfigChannel(m_htim, &sConfigOC, m_channel) != HAL_OK) {
  39. Error_Handler();
  40. }
  41. HAL_TIM_PWM_Stop(m_htim, m_channel);
  42. if (HAL_TIM_PWM_Start(m_htim, m_channel) != HAL_OK) {
  43. Error_Handler();
  44. }
  45. }
  46. void ZPWMGenerator::stopPWM() {
  47. float duty = 0;
  48. if (!m_polarity) {
  49. duty = 100.0 - duty;
  50. }
  51. // HAL_TIM_PWM_Stop(m_htim, m_channel);
  52. startPWM(duty);
  53. }