关于嵌入式学习随笔->12《STM32CubeMX应用3-PWM的配置》

霸气de小男生 提交于 2020-02-01 17:04:23

以蜂鸣器为例,找到自己板子的蜂鸣器。

image

由电路可知蜂鸣器由PH6控制,在cubemx中查看该引脚含有定时器12通道1,因此,我们可以用这个定时器来做PWM的输出。

STM32CubeMX中的配置

image

点击generate code生成代码。

HAL库中相关函数

HAL_StatusTypeDef HAL_TIM_Base_Start(TIM_HandleTypeDef *htim)
{
  uint32_t tmpsmcr;

  /* Check the parameters */
  assert_param(IS_TIM_INSTANCE(htim->Instance));

  /* Set the TIM state */
  htim->State = HAL_TIM_STATE_BUSY;

  /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */
  tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS;
  if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr))
  {
    __HAL_TIM_ENABLE(htim);
  }

  /* Change the TIM state*/
  htim->State = HAL_TIM_STATE_READY;

  /* Return function status */
  return HAL_OK;
}
HAL_TIM_Base_Start(TIM_HandleTypeDef *htim)

image

/**
  * @brief  Starts the PWM signal generation.
  * @param  htim TIM handle
  * @param  Channel TIM Channels to be enabled
  *          This parameter can be one of the following values:
  *            @arg TIM_CHANNEL_1: TIM Channel 1 selected
  *            @arg TIM_CHANNEL_2: TIM Channel 2 selected
  *            @arg TIM_CHANNEL_3: TIM Channel 3 selected
  *            @arg TIM_CHANNEL_4: TIM Channel 4 selected
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_TIM_PWM_Start(TIM_HandleTypeDef *htim, uint32_t Channel)
{
  uint32_t tmpsmcr;

  /* Check the parameters */
  assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));

  /* Enable the Capture compare channel */
  TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE);

  if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET)
  {
    /* Enable the main output */
    __HAL_TIM_MOE_ENABLE(htim);
  }

  /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */
  tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS;
  if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr))
  {
    __HAL_TIM_ENABLE(htim);
  }

  /* Return function status */
  return HAL_OK;
}
HAL_TIM_PWM_Start(TIM_HandleTypeDef *htim, uint32_t Channel)

image

__HAL_TIM_PRESCALER(&htim12, psc)

设置某个定时器的预分频系数

__HAL_TIM_SetCompare(&htim12, TIM_CHANNEL_1, pwm);

设置某个定时器某个通道的比较值。

要熟悉定时器产生pwm的原理这里理解会比较简单。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!