STM32學(xué)習(xí)筆記(5):通用定時器PWM輸出
//等待外部高速時鐘晶振工作
HSEStartUpStatus = RCC_WaitForHSEStartUp();
if(HSEStartUpStatus == SUCCESS)
{
//設(shè)置AHB時鐘(HCLK)為系統(tǒng)時鐘
RCC_HCLKConfig(RCC_SYSCLK_Div1);
//設(shè)置高速AHB時鐘(APB2)為HCLK時鐘
RCC_PCLK2Config(RCC_HCLK_Div1);
//設(shè)置低速AHB時鐘(APB1)為HCLK的2分頻
RCC_PCLK1Config(RCC_HCLK_Div2);
//設(shè)置FLASH代碼延時
FLASH_SetLatency(FLASH_Latency_2);
//使能預(yù)取指緩存
FLASH_PrefetchBufferCmd(FLASH_PrefetchBuffer_Enable);
//設(shè)置PLL時鐘,為HSE的9倍頻8MHz * 9 = 72MHz
RCC_PLLConfig(RCC_PLLSource_HSE_Div1, RCC_PLLMul_9);
//使能PLL
RCC_PLLCmd(ENABLE);
//等待PLL準(zhǔn)備就緒
while(RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET);
//設(shè)置PLL為系統(tǒng)時鐘源
RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);
//判斷PLL是否是系統(tǒng)時鐘
while(RCC_GetSYSCLKSource() != 0x08);
}
//開啟TIM3的時鐘
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);
//開啟GPIOB的時鐘和復(fù)用功能
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB | RCC_APB2Periph_AFIO,ENABLE);
}
void GPIO_cfg()
{
GPIO_InitTypeDef GPIO_InitStructure;
//部分映射,將TIM3_CH2映射到PB5
//GPIO_PinRemapConfig(GPIO_FullRemap_TIM3, ENABLE);
GPIO_PinRemapConfig(GPIO_PartialRemap_TIM3, ENABLE);
//選擇引腳5
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
//輸出頻率最大50MHz
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
//復(fù)用推挽輸出
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOB,&GPIO_InitStructure);
}
void TIMER_cfg()
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
//重新將Timer設(shè)置為缺省值
TIM_DeInit(TIM3);
//采用內(nèi)部時鐘給TIM3提供時鐘源
TIM_InternalClockConfig(TIM3);
//預(yù)分頻系數(shù)為0,即不進(jìn)行預(yù)分頻,此時TIMER的頻率為72MHz
TIM_TimeBaseStructure.TIM_Prescaler = 0;
//設(shè)置時鐘分割
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
//設(shè)置計(jì)數(shù)器模式為向上計(jì)數(shù)模式
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
//設(shè)置計(jì)數(shù)溢出大小,每計(jì)7200個數(shù)就產(chǎn)生一個更新事件,即PWM的輸出頻率為10kHz
TIM_TimeBaseStructure.TIM_Period = 7200 - 1;
//將配置應(yīng)用到TIM3中
TIM_TimeBaseInit(TIM3,&TIM_TimeBaseStructure);
}
void PWM_cfg()
{
TIM_OCInitTypeDef TimOCInitStructure;
//設(shè)置缺省值
TIM_OCStructInit(&TimOCInitStructure);
//PWM模式1輸出
TimOCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
//設(shè)置占空比,占空比=(CCRx/ARR)*100%或(TIM_Pulse/TIM_Period)*100%
TimOCInitStructure.TIM_Pulse = dutyfactor * 7200 / 100;
//TIM輸出比較極性高
TimOCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
//使能輸出狀態(tài)
TimOCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
//TIM3的CH2輸出
TIM_OC2Init(TIM3, &TimOCInitStructure);
//設(shè)置TIM3的PWM輸出為使能
TIM_CtrlPWMOutputs(TIM3,ENABLE);
}
評論