2018-8-11 22:23
void TIM1_Config(void) //TIM1初始化 { GPIO_InitTypeDef GPIO_InitStructure; TIM_TimeBaseInitTypeDef TIMTimeBase_InitStruct; TIM_OCInitTypeDef TIM_OCInitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1,ENABLE); RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE); /* GPIO 初始化*/ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出 GPIO_Init(GPIOA, &GPIO_InitStructure); /* TIM1 初始化*/ TIMTimeBase_InitStruct.TIM_Period=399; //自动重装值 TIMTimeBase_InitStruct.TIM_Prescaler=3599; //CK_CNT = CK_INT/(3599+1) = 20000hz TIMTimeBase_InitStruct.TIM_ClockDivision=0; //时钟分频,设置死区时需要 TIMTimeBase_InitStruct.TIM_CounterMode=TIM_CounterMode_Up; //向上计数 TIM_TimeBaseInit(TIM1,&TIMTimeBase_InitStruct); //初始化TIM1 /* CH1 初始化*/ TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; TIM_OCInitStructure.TIM_Pulse = 0; //匹配值 TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; //输出比较极性高 TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable; TIM_OC1Init(TIM1,&TIM_OCInitStructure); TIM_OC1PreloadConfig(TIM1,TIM_OCPreload_Enable); //使能TIM1在CCR1上的预装载寄存器 TIM1->BDTR |= 1<<15; //OC和OCN使能,高级定时器需要设置 TIM_ARRPreloadConfig(TIM1, ENABLE); //使能TIM1在ARR上的预装载寄存器 TIM_Cmd(TIM1,ENABLE); //使能TIM1外设 TIM_CtrlPWMOutputs(TIM1, ENABLE); } void TIM2_Config(void) //TIM2初始化 { GPIO_InitTypeDef GPIO_InitStructure; TIM_TimeBaseInitTypeDef TIMTimeBase_InitStruct; TIM_OCInitTypeDef TIM_OCInitStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE); RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE); /* GPIO 初始化*/ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出 GPIO_Init(GPIOA, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1; GPIO_Init(GPIOA, &GPIO_InitStructure); /* TIM2 初始化*/ TIMTimeBase_InitStruct.TIM_Period=7199; //自动重装值 TIMTimeBase_InitStruct.TIM_Prescaler=0; //CK_CNT = CK_INT/(0+1) = 72 000 000hz TIMTimeBase_InitStruct.TIM_ClockDivision=0; //时钟分频,设置死区时需要 TIMTimeBase_InitStruct.TIM_CounterMode=TIM_CounterMode_Up; //向上计数 TIM_TimeBaseInit(TIM2,&TIMTimeBase_InitStruct); //初始化TIM2 /* CH1 初始化*/ TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; TIM_OCInitStructure.TIM_Pulse = 0; //匹配值 TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; //输出比较极性高 TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable; TIM_OC1Init(TIM2,&TIM_OCInitStructure); TIM_OC1PreloadConfig(TIM2,TIM_OCPreload_Enable); //使能TIM2在CCR1上的预装载寄存器 /* CH2 初始化*/ TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable; TIM_OCInitStructure.TIM_Pulse = 0; TIM_OC2Init(TIM2,&TIM_OCInitStructure); TIM_OC2PreloadConfig(TIM2,TIM_OCPreload_Enable); //使能TIM2在CCR2上的预装载寄存器 TIM_ARRPreloadConfig(TIM2, ENABLE); //使能TIM2在ARR上的预装载寄存器 TIM_Cmd(TIM2,ENABLE); //使能TIM2外设 } void Motor(int CCR1_Val,int CCR2_Val) //电机pwm输出 { TIM2->CCR1=CCR1_Val; TIM2->CCR2=CCR2_Val; } void Servo(int CCR1_Val) //舵机pwm输出 { TIM1->CCR1=CCR1_Val; }