以蜂鸣器为例,找到自己板子的蜂鸣器。
由电路可知蜂鸣器由PH6控制,在cubemx中查看该引脚含有定时器12通道1,因此,我们可以用这个定时器来做PWM的输出。
STM32CubeMX中的配置
点击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; }
/** * @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_PRESCALER(&htim12, psc)
设置某个定时器的预分频系数
__HAL_TIM_SetCompare(&htim12, TIM_CHANNEL_1, pwm);
设置某个定时器某个通道的比较值。
要熟悉定时器产生pwm的原理这里理解会比较简单。
来源:https://www.cnblogs.com/vcan123/p/12248800.html