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