{ GPIO_InitTypeDef GPIO_InitStructure; TIM_OCInitTypeDef TIM_OCInitStructure; TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct; RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);//使能時鍾 RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE); /* GPIOA Configuration: Channel 1, 2, 3 and 4 as alternate function push-pull */ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_11; 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_DOWN; GPIO_Init(GPIOA, &GPIO_InitStructure); GPIO_PinAFConfig(GPIOA, GPIO_PinSource8, GPIO_AF_2);//開啟復用 GPIO_PinAFConfig(GPIOA, GPIO_PinSource11, GPIO_AF_2); TIM_TimeBaseInitStruct.TIM_Prescaler = 0;//5k TIM_TimeBaseInitStruct.TIM_ClockDivision = 0; TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInitStruct.TIM_Period = MOTOR_COUNT;//這里設置的是5k的頻率,value =(48000000/你想要的頻率)-1 TIM_TimeBaseInitStruct.TIM_RepetitionCounter = 0; TIM_TimeBaseInit(TIM1,&TIM_TimeBaseInitStruct); /* 頻道1,2,3,4的PWM 模式設置 */ TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable; TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;//輸出極性 TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_Low;//輸出極性 TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set; TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCIdleState_Reset; TIM_OCInitStructure.TIM_Pulse = (MOTOR_COUNT>>1);//使能頻道1配置 TIM_OC1Init(TIM1, &TIM_OCInitStructure); TIM_OCInitStructure.TIM_Pulse = (MOTOR_COUNT>>1);//使能頻道1配置 TIM_OC4Init(TIM1, &TIM_OCInitStructure); //值為0~MOTOR_COUNT,這里MOTOR_COUNT的值已經減一了 TIM_SetCompare1(TIM1,(MOTOR_COUNT>>1));//輸出波形的1/2 TIM_SetCompare4(TIM1,(MOTOR_COUNT>>1));//輸出波形的1/2 /* TIM1 計算器使能*/ TIM_Cmd(TIM1, ENABLE); /* TIM1 主輸出使能 */ TIM_CtrlPWMOutputs(TIM1, ENABLE); }