STMM32了51TIM3 ch2 通道
void PWM_MOTOA_Init(u8 level )//PC7
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
NVIC_InitTypeDef NVIC_InitStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_ClocksTypeDef RCC_ClocksStatus;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE); //TIM2时钟使能
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOC, ENABLE); //使能PORTA时钟?
RCC_GetClocksFreq(&RCC_ClocksStatus);
/*GPIO init*/
GPIO_PinAFConfig(GPIOC,GPIO_PinSource7,GPIO_AF_TIM3); //GPIOA1复用为定时器3
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; //复用功能
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_40MHz;//速度40MHz
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; //推挽复用输出
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; //上拉
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7; //GPIOA1
GPIO_Init(GPIOC,&GPIO_InitStructure); //初始化PA1
/*timer init
TIM2CLK = SystemCoreClock
timer2 OC2 out period is 2ms
*/
TIM_TimeBaseStructure.TIM_Prescaler = RCC_ClocksStatus.PCLK1_Frequency/1000000 - 1; //定时器分频
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //向上计数模式
TIM_TimeBaseStructure.TIM_Period = 50; //自动重装载值
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInit(TIM3,&TIM_TimeBaseStructure);//初始化定时器2
/*PWM config*/
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
/*TIM2 OC2*/
TIM_OCInitStructure.TIM_Pulse = 35;
TIM_OC2Init(TIM3, &TIM_OCInitStructure); //根据T指定的参数初始化外设TIM2 OC2
TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable);
TIM_ARRPreloadConfig(TIM3,ENABLE);//ARPE使能
TIM_ClearFlag(TIM3, TIM_IT_CC2);
TIM_ITConfig(TIM3, TIM_IT_CC2, ENABLE);
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_Cmd(TIM3, ENABLE); //使能TIM3
// SetCompare(2,level);
}
void TIM3_IRQHandler(void)
{
static uint16_t count = 0;
uint16_t capture = 0;
if(TIM_GetITStatus(TIM3, TIM_IT_CC2) != RESET)
{
TIM_ClearITPendingBit(TIM3, TIM_IT_CC2);
TIM_ClearFlag(TIM3, TIM_IT_CC2);
if(++count>20)
{
count=0;
capture = TIM_GetCapture2(TIM3);
if(capture>0&&capture<=50)
{ capture++;
TIM_SetCompare2(TIM3, capture);
}
}
}
}