GPIO_InitTypeDef GPIO_InitStructure2;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_BDTRInitTypeDef TIM_BDTRInitStructure;
//第一步:配置時鐘
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_GPIOB|RCC_APB2Periph_TIM1,ENABLE);
//第二步,配置goio口
GPIO_InitStructure2.GPIO_Pin=GPIO_Pin_8;
GPIO_InitStructure2.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_InitStructure2.GPIO_Mode=GPIO_Mode_AF_PP; //設置為復用浮空輸出
GPIO_Init(GPIOA,&GPIO_InitStructure2);
GPIO_InitStructure2.GPIO_Pin=GPIO_Pin_13;
GPIO_InitStructure2.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_InitStructure2.GPIO_Mode=GPIO_Mode_AF_PP; //設置為復用浮空輸出
GPIO_Init(GPIOB,&GPIO_InitStructure2);
//第三步,定時器基本配置
TIM_TimeBaseStructure.TIM_Period=1000-1; // 自動重裝載寄存器的值
TIM_TimeBaseStructure.TIM_Prescaler=72-1; // 時鐘預分頻數(shù)
TIM_TimeBaseStructure.TIM_ClockDivision=TIM_CKD_DIV1; // 采樣分頻
TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up; //向上計數(shù)
TIM_TimeBaseStructure.TIM_RepetitionCounter=0; //重復寄存器,用于自動更新pwm占空比
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);
//第四步pwm輸出配置
TIM_OCInitStructure.TIM_OCMode=TIM_OCMode_PWM2; //設置為pwm1輸出模式
TIM_OCInitStructure.TIM_Pulse=500; //設置占空比時間
TIM_OCInitStructure.TIM_OCPolarity=TIM_OCPolarity_Low; //設置輸出極性
TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable; //使能該通道輸出
//下面幾個參數(shù)是高級定時器才會用到,通用定時器不用配置
TIM_OCInitStructure.TIM_OCNPolarity=TIM_OCNPolarity_High; //設置互補端輸出極性
TIM_OCInitStructure.TIM_OutputNState=TIM_OutputNState_Enable;//使能互補端輸出
TIM_OCInitStructure.TIM_OCIdleState=TIM_OCIdleState_Reset; //死區(qū)后輸出狀態(tài)
TIM_OCInitStructure.TIM_OCNIdleState=TIM_OCNIdleState_Reset;//死區(qū)后互補端輸出狀態(tài)
TIM_OC1Init(TIM1,&TIM_OCInitStructure); //按照指定參數(shù)初始化
//第五步,死區(qū)和剎車功能配置,高級定時器才有的,通用定時器不用配置
TIM_BDTRInitStructure.TIM_OSSRState = TIM_OSSRState_Disable;//運行模式下輸出
TIM_BDTRInitStructure.TIM_OSSIState = TIM_OSSIState_Disable;//空閑模式下輸出選擇
TIM_BDTRInitStructure.TIM_LOCKLevel = TIM_LOCKLevel_OFF; //鎖定設置
TIM_BDTRInitStructure.TIM_DeadTime = 0x90; //死區(qū)時間設置
TIM_BDTRInitStructure.TIM_Break = TIM_Break_Disable; //剎車功能使能
TIM_BDTRInitStructure.TIM_BreakPolarity = TIM_BreakPolarity_High;//剎車輸入極性
TIM_BDTRInitStructure.TIM_AutomaticOutput = TIM_AutomaticOutput_Enable;//自動輸出使能
TIM_BDTRConfig(TIM1,&TIM_BDTRInitStructure);
//第六步,使能端的打開
TIM_OC1PreloadConfig(TIM1, TIM_OCPreload_Enable); //使能TIMx在CCR1上的預裝載寄存器
TIM_ARRPreloadConfig(TIM1, ENABLE); //使能TIMx在ARR上的預裝載寄存器
TIM_Cmd(TIM1,ENABLE); //打開TIM2
//下面這句是高級定時器才有的,輸出pwm必須打開
TIM_CtrlPWMOutputs(TIM1, ENABLE); //pwm輸出使能,一定要記得打開
// 在運行當中想要改變pwm的頻率和占空比調(diào)用:
TIM_SetAutoreload(TIM1,1000);
TIM_SetCompare1(TIM1,500);