資源簡介
利用STM32的通用定時器,通過多種方法實現互補PWM波形的輸出,并且實現頻率和占空比可任意調節,高級定時器資源有限,資源不夠又需要輸出(互補)PWM時此為有效的解決方法

代碼片段和文件信息
/**
??******************************************************************************
??*?@file???:?complementaryPWM.c
??*?@author?:?wind
??*?@version:?
??*?@date???:?20150401
??*?@brief??:
??******************************************************************************
??*/
/*?---------------------------------------------------------------------------*/
#include?“stm32f30x.h“
#include?“stm32f30x_tim.h“
#include?“stm32f30x_gpio.h“
void?PWMoutput(void);
int?main()
{
SystemInit();
PWMoutput();
while(1);
}
void?PWMoutput(void)
{
uint16_t?period=0pulsewidth=0;
GPIO_InitTypeDef??GPIO_InitStruct;
TIM_TimebaseInitTypeDef??TIM_TimebaseInitStruct;
TIM_OCInitTypeDef??TIM_OCInitStruct;
period?=?72*1000000/(100*1000);//計數周期,系統頻率72M,PWM輸出頻率100k
pulsewidth?=?45*period/100;??//脈寬,占空比45%
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOAENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3?ENABLE);
//GPIO?Init
GPIO_InitStruct.GPIO_Pin?=?(GPIO_Pin_6?|?GPIO_Pin_7);
GPIO_InitStruct.GPIO_Mode?=?GPIO_Mode_AF;
GPIO_InitStruct.GPIO_OType?=?GPIO_OType_PP;
GPIO_InitStruct.GPIO_Speed?=?GPIO_Speed_50MHz;
GPIO_InitStruct.GPIO_PuPd?=?GPIO_PuPd_NOPULL;
GPIO_Init(GPIOA?&GPIO_InitStruct);
GPIO_PinAFConfig(GPIOA?GPIO_PinSource6?GPIO_AF_2);//PA6->TIM3_CH1
GPIO_PinAFConfig(GPIOA?GPIO_PinSource7?GPIO_AF_2);//PA7->TIM2_CH2
//Timer?base?Init
TIM_TimebaseInitStruct.TIM_Prescaler?=?0;
TIM_TimebaseInitStruct.TIM_CounterMode?=?TIM_CounterMode_Up;
TIM_TimebaseInitStruct.TIM_Period?=?period?-?1; //ARR調節此參數實現頻率可調
TIM_TimebaseInitStruct.TIM_ClockDivision?=?TIM_CKD_DIV1?;
TIM_TimebaseInit(TIM3?&?TIM_TimebaseInitStruct);
//OCInit
TIM_OCStructInit(&TIM_OCInitStruct);
TIM_OCInitStruct.TIM_OCMode?=?TIM_OCMode_PWM1;
TIM_OCInitStruct.TIM_OutputState?=?TIM_OutputState_Enable;
TIM_OCInitStruct.TIM_Pulse?=?pulsewidth; //CCR1,調節此參數實現占空比可調
TIM_OCInitStruct.TIM_OCPolarity?=?TIM_OCPolarity_High;
//OC1
TIM_OC1Init(TIM3?&?TIM_OCInitStruct);
TIM_OC1PreloadConfig(TIM3?TIM_OCPreload_Enable);
//OC2?方法1?:?修改Mode
TIM_OCInitStruct.TIM_OCMode?=?TIM_OCMode_PWM2;
TIM_OCInitStruct.TIM_OCPolarity?=?TIM_OCPolarity_High;
/***********************************
//OC2?方法2?:?修改?Polarity
TIM_OCInitStruct.TIM_OCMode?=?TIM_OCMode_PWM1;
TIM_OCInitStruct.TIM_OCPolarity?=?TIM_OCPolarity_Low;
***********************************/
TIM_OC2Init(TIM3?&?TIM_OCInitStruct);
TIM_OC2PreloadConfig(TIM2?TIM_OCPreload_Enable);
TIM_Cmd(TIM3?ENABLE);
}
?屬性????????????大小?????日期????時間???名稱
-----------?---------??----------?-----??----
?????文件???????2616??2015-04-02?21:54??complementaryPWM.c
-----------?---------??----------?-----??----
?????????????????2616????????????????????1
- 上一篇:非常好用的智能排課系統
- 下一篇:STM32任意角度移相全橋PWM
評論
共有 條評論