STM32 PWM底層驅動

//說明:利用TIMER1的CH1即PA8端口輸出PWM驅動蜂鳴器。以下是代碼(在STM32F103上應用的)


void fn_pwm_init(INT16U _pwmFreq)
{
//ToDo: Add your code Here:
 /* Timer1 Channel 1, PA8 IO初始化*/
 GPIO_PinRemapConfig(GPIO_PartialRemap_TIM1,ENABLE);
 GPIO_InitTypeDef GPIO_InitStructure;
 
 GPIO_InitStructure.GPIO_Pin =  GPIO_Pin_8;
 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
 GPIO_Init(GPIOA, &GPIO_InitStructure);

 //RCC的TIM1及IO時鐘開啓
 RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
 RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO,ENABLE);

 //以下爲TIM1初始化
 TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;    
 //重新將Timer設置爲缺省值  
 TIM_DeInit(TIM1);  
 //採用內部時鐘給TIM1提供時鐘源  
 TIM_InternalClockConfig(TIM1);  
 //預分頻係數爲0即不進行預分頻此時TIMER的頻率爲48MHz  
 TIM_TimeBaseStructure.TIM_Prescaler = 1-1;//1分頻,即不分頻  
 //設置時鐘分割  
 TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;  
 //設置計數器模式爲向上計數模式  
 TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;  
 //設置計數溢出大小48000000爲系統時鐘  
 TIM_TimeBaseStructure.TIM_Period = (48000000/_pwmFreq)- 1;  
 //將配置應用到TIM1中  
 TIM_TimeBaseInit(TIM1,&TIM_TimeBaseStructure);
 
 //pwm初始化
 TIM_OCInitTypeDef TimOCInitStructure;   //設置缺省值  
 TIM_OCStructInit(&TimOCInitStructure);   //PWM模式1輸出  
 TimOCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;   //設置佔空比佔空比=(CCRx/ARR)*100%或(TIM_Pulse/TIM_Period)*100%  
 TimOCInitStructure.TIM_Pulse = 50 * 4800 / 100;   //50爲100分比,1-100
 TimOCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;   //使能輸出狀態  
 TimOCInitStructure.TIM_OutputState = TIM_OutputState_Enable;   //TIM1的CH1輸出  
 TIM_OC1Init(TIM1, &TimOCInitStructure);   //設置TIM1的PWM輸出爲使能  
 TIM_CtrlPWMOutputs(TIM1,DISABLE);
}

void fn_pwm_Cmd(FunctionalState NewState)
{
//ToDo: Add your code Here:
 TIM_CtrlPWMOutputs(TIM1, NewState);
 TIM_Cmd(TIM1, NewState);
 
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章