新手入门
- 积分
- 4
- 金钱
- 4
- 注册时间
- 2024-5-29
- 在线时间
- 1 小时
|
void TIM2_PWM_Init( int frequency1,int frequency2)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitTypeStrue;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); //使能定时器2时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO|RCC_APB2Periph_GPIOB, ENABLE); //使能GPIO外设和AFIO复用功能模块时钟
GPIO_PinRemapConfig(GPIO_Remap_SWJ_JTAGDisable , ENABLE); //禁止JTAG功能
GPIO_PinRemapConfig(GPIO_FullRemap_TIM2, ENABLE); //Timer2完全重映射
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_15; //PA15端口配置
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //IO口速度为50MHz
GPIO_Init(GPIOA, &GPIO_InitStructure); //根据设定参数初始化GPIOA15
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10| GPIO_Pin_11|GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //IO口速度为50MHz
GPIO_Init(GPIOB, &GPIO_InitStructure); //根据设定参数初始化GPIOB10,11
//定时器TIM2初始化
TIM_TimeBaseStructure.TIM_Period = frequency1-1; //设置在下一个更新事件装入活动的自动重装载寄存器周期的值
TIM_TimeBaseStructure.TIM_Prescaler =72-1; //设置用来作为TIMx时钟频率除数的预分频值
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; //设置时钟分割:TDTS = Tck_tim
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_CenterAligned1; //TIM中央对其模式1
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure); //根据指定的参数初始化TIMx的时间基数单位
//PWM初始化 TIM_CH1,4
TIM_OCInitTypeStrue.TIM_OCMode=TIM_OCMode_PWM1 ;
TIM_OCInitTypeStrue.TIM_OCPolarity=TIM_OCPolarity_Low ;
TIM_OCInitTypeStrue.TIM_Pulse=frequency1-1;
TIM_OCInitTypeStrue.TIM_OutputState=TIM_OutputState_Enable ;
TIM_OC1Init(TIM2,&TIM_OCInitTypeStrue);
TIM_OC4Init(TIM2,&TIM_OCInitTypeStrue);
TIM_OC1PreloadConfig(TIM2,TIM_OCPreload_Enable);
TIM_OC4PreloadConfig(TIM2,TIM_OCPreload_Enable);
//PWM初始化 TIM_CH2,3
TIM_OCInitTypeStrue.TIM_OCMode=TIM_OCMode_PWM1 ;
TIM_OCInitTypeStrue.TIM_OCPolarity=TIM_OCPolarity_High ;
TIM_OCInitTypeStrue.TIM_Pulse=2;
TIM_OCInitTypeStrue.TIM_OutputState=TIM_OutputState_Enable ;
TIM_OC2Init(TIM2,&TIM_OCInitTypeStrue);
TIM_OC3Init(TIM2,&TIM_OCInitTypeStrue);
TIM_OC2PreloadConfig(TIM2,TIM_OCPreload_Enable);
TIM_OC3PreloadConfig(TIM2,TIM_OCPreload_Enable);
TIM_Cmd(TIM2,ENABLE);
}
主函数中初始化:TIM2_PWM_Init(5000,5000);//con1,con2,con3,con4初始化
|
|