1、TIM初始化基本过程及源码
(a)GPIO、TIM结构体变量申明
(b)GPIO、TIM时钟使能
(c)GPIO基本配置
(d)TIM配置、通道设置
(e)TIM使能
源码如下:
/**
* @brief void TIM_Configuration(void)
* @describe TIM配置 PWM输出初始化
TIM1 CH1 PA8
TIM1 CH2 PA9
TIM15 CH1 PB14
TIM15 CH2 PB15
* @param void
* @retval void
*/
void TIM_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
//时钟使能
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA|RCC_AHBPeriph_GPIOB, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1|RCC_APB2Periph_TIM15, ENABLE);
//GPIOA配置
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_InitStructure.GPIO_Pin =GPIO_Pin_8|GPIO_Pin_9;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource8, GPIO_AF_2);//PA8选择备用功能 电机1 TIM1 CH1
GPIO_PinAFConfig(GPIOA, GPIO_PinSource9, GPIO_AF_2);//PA9选择备用功能 电机1 TIM1 CH2
//GPIOB配置
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_14|GPIO_Pin_15;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_PinAFConfig(GPIOB, GPIO_PinSource14, GPIO_AF_1);//PB14选择备用功能 电机2 TIM15 CH1
GPIO_PinAFConfig(GPIOB, GPIO_PinSource15, GPIO_AF_1);//PB15选择备用功能 电机2 TIM15 CH2
//TIM配置
TIM_TimeBaseStructure.TIM_Period = fill_value;//480 最大计数值 决定PWM频率
TIM_TimeBaseStructure.TIM_Prescaler = 0;//时钟预分频数
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;//时钟0分割 1次时钟频率 1次计数
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;//向上计数
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);
TIM_TimeBaseInit(TIM15, &TIM_TimeBaseStructure);
//TIM通道配置
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse =fill_value*0.5;//通道占空比系数
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM1, &TIM_OCInitStructure);//TIM1通道1 电机1
TIM_OC2Init(TIM1, &TIM_OCInitStructure);//TIM1通道2 电机1
TIM_OC1Init(TIM15, &TIM_OCInitStructure);//TIM15通道1 电机2
TIM_OC2Init(TIM15, &TIM_OCInitStructure);//TIM15通道2 电机2
//通道CH3 调用 TIM_OC3Init 函数
//通道CH4 调用 TIM_OC4Init 函数
//使能TIM1 TIM15
TIM_Cmd(TIM1, ENABLE);
TIM_Cmd(TIM15, ENABLE);
TIM1->BDTR|=1<<15;//TIM1输出使能 其他定时器没有该寄存器 不需要此项配置
TIM15->BDTR|=1<<15;//TIM15输出使能 其他定时器没有该寄存器 不需要此项配置
}
在主函数调用
//1号电机正转
TIM_SetCompare1(TIM1,0.5*fill_value);
TIM_SetCompare2(TIM1,0);
//2号电机反转
TIM_SetCompare1(TIM15,0);
TIM_SetCompare2(TIM15,fill_value);
即可设置对应通道输出PWM
2、PWM输出验证
3、重要的相关配置
GPIO_PinAFConfig(GPIOB, GPIO_PinSource14, GPIO_AF_1);
该函数配置对应GPIO引脚的功能,具体的引脚功能参数GPIO_AF_x 找对应的芯片数据手册 查看
下图为STM32F051C8T6相关引脚功能
与其他普通定时器不同的是 特别注意TIM1、TIM15的BDTR寄存器 需要将MOD置位(寄存器第15位) 才能输出PWM
TIM1->BDTR|=1<<15;
TIM15->BDTR|=1<<15;