STM32学习笔记之对PWM频率和占空比都可调测试
扫描二维码
随时随地手机看文章
基于战舰开发板 修改的可以对频率和占空比同时调节的一个简单程序。
voidTIM3_PWM_Init(u16arr,u16psc)
{
GPIO_InitTypeDefGPIO_InitStructure;
TIM_TimeBaseInitTypeDefTIM_TimeBaseStructure;
TIM_OCInitTypeDefTIM_OCInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);//ê1?ü?¨ê±?÷3ê±?ó
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB|RCC_APB2Periph_AFIO,ENABLE);//ê1?üGPIOíaéèoíAFIO?′ó?1|?ü?£?éê±?ó
GPIO_PinRemapConfig(GPIO_PartialRemap_TIM3,ENABLE);//Timer32?·???ó3é?TIM3_CH2->PB5
//éè????òy???a?′ó?ê?3?1|?ü,ê?3?TIM3CH2μ?PWM??3?2¨D?GPIOB.5
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_5;//TIM_CH2
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;//?′ó?í?íìê?3?
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOB,&GPIO_InitStructure);//3?ê??ˉGPIO
//3?ê??ˉTIM3
TIM_TimeBaseStructure.TIM_Period=arr;//éè???ú??ò????üD?ê??t×°è????ˉμ?×??ˉ??×°????′??÷?ü?úμ??μ
TIM_TimeBaseStructure.TIM_Prescaler=psc;//éè??ó?à′×÷?aTIMxê±?ó?μ?ê3yêyμ??¤·??μ?μ
TIM_TimeBaseStructure.TIM_ClockDivision=0;//éè??ê±?ó·???:TDTS=Tck_tim
TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up;//TIM?òé???êy?£ê?
TIM_TimeBaseInit(TIM3,&TIM_TimeBaseStructure);//?ù?YTIM_TimeBaseInitStruct?D???¨μ?2?êy3?ê??ˉTIMxμ?ê±???ùêyμ¥??
//3?ê??ˉTIM3Channel2PWM?£ê?
TIM_OCInitStructure.TIM_OCMode=TIM_OCMode_PWM2;//?????¨ê±?÷?£ê?:TIM??3??í?èμ÷???£ê?2
TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable;//±è??ê?3?ê1?ü
TIM_OCInitStructure.TIM_Pulse=arr*50/100;
TIM_OCInitStructure.TIM_OCPolarity=TIM_OCPolarity_High;//ê?3???D?:TIMê?3?±è????D???
TIM_OC2Init(TIM3,&TIM_OCInitStructure);//?ù?YT???¨μ?2?êy3?ê??ˉíaéèTIM3OC2
TIM_OC2PreloadConfig(TIM3,TIM_OCPreload_Enable);//ê1?üTIM3?úCCR2é?μ??¤×°????′??÷
TIM_Cmd(TIM3,ENABLE);//ê1?üTIM3
}
uint32_tTIM3_PWM_FQ=0;
uint32_tTIM3_PWM_FQ_Old=80000;
uint16_tTIM3_PWM_Pulse=0;//°′?????¢?a·¢°?pwm3?ê??ˉoóμ?μ??μ?ê?a80KHZ.×??oDT??????±è?a50%
uint16_tTIM3_PWM_Pulse_Old=50;
voidTIM3_PWM_Update(uint32_tTIM3_PWM_FQ,uint16_tTIM3_PWM_Pulse)
{
uint32_ttemp32;
uint32_tTimerfrequency;
uint16_tTimerPeriod;
uint16_tTimerPrescaler;
uint16_tTimerPulse;
if((TIM3_PWM_FQ_Old!=TIM3_PWM_FQ)||(TIM3_PWM_Pulse_Old!=TIM3_PWM_Pulse))
{
TIM3_PWM_FQ_Old=TIM3_PWM_FQ;
TIM3_PWM_Pulse_Old=TIM3_PWM_Pulse;
if(TIM3_PWM_FQ>=1000){//72000000/65535=1089è?1000HZ
Timerfrequency=TIM3_PWM_FQ;
TimerPrescaler=1;//′óóú10002?Dèòa±??μ?′?éíê3é
}else{
Timerfrequency=TIM3_PWM_FQ;//D?óú1000?íDèòa±??μá?
TimerPrescaler=1000/TIM3_PWM_FQ;
}
temp32=((72000000/(TimerPrescaler))/Timerfrequency);
if(temp32>65535)temp32=65535;
TimerPeriod=(uint16_t)temp32;
if(TIM3_PWM_Pulse>100)TIM3_PWM_Pulse=100;
TimerPulse=TimerPeriod*TIM3_PWM_Pulse/100;
TIM3->ARR=TimerPeriod-1;
TIM3->PSC=TimerPrescaler-1;
TIM3->CCR1=TimerPulse;
TIM3->EGR=TIM_PSCReloadMode_Update;
}
}
不知道为什么上传注释就模糊掉了 ,反正代码就是这样大家可以看看。