使用CUBEMX软件配置PWM IO
PSC配置为 80-1 因为时钟为 80Mhz
重装载 设置为 1000-1
编写代码
#include "app_motor_control.h"
extern TIM_HandleTypeDef htim2;
#define motor_tim htim2
/* @brief 电机初始化
* @
*/
void app_motor_init(void)
{
HAL_TIM_PWM_Start(&motor_tim, TIM_CHANNEL_1); //开启PWM通道1
HAL_TIM_PWM_Start(&motor_tim, TIM_CHANNEL_2); //开启PWM通道2
}
/* @brief 电机运动
* @
*/
void app_motor_run(uint8_t dir,float percentum)
{
uint32_t index =0;
index = percentum /100.0f * htim2.Init.Period;
if(dir)
{
__HAL_TIM_SET_COMPARE(&motor_tim,TIM_CHANNEL_1,index);
__HAL_TIM_SET_COMPARE(&motor_tim,TIM_CHANNEL_2,0);
}
else
{
__HAL_TIM_SET_COMPARE(&motor_tim,TIM_CHANNEL_2,index);
__HAL_TIM_SET_COMPARE(&motor_tim,TIM_CHANNEL_1,0);
}
}
/* @brief 电机停止
* @
*/
void app_motor_stop(void)
{
HAL_TIM_PWM_Stop(&motor_tim, TIM_CHANNEL_1); //停止PWM通道1
HAL_TIM_PWM_Stop(&motor_tim, TIM_CHANNEL_2); //停止PWM通道2
}
使用STM32CubeIde 编译下载