利用tim3生成ev1527编码(270K,1200us) TIM3_PWM_Init(1199,71); //分频后1us,窄脉冲4LCK,宽脉冲12LCK,脉冲周期16LCK;同步周期128LCK(4LCK脉冲,124LCK空白);待生成脉冲周期为1200us //通过改变TIM3->CCR2的值来改变占空比 #define LED0_PWM_DUTY TIM3->CCR2 #define PULSE_CODE 0xD2F672 unsigned int pulse_count=0; void TIM3_PWM_Init(u16 arr,u16 psc) { GPIO_InitTypeDef GPIO_InitStructure; TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; TIM_OCInitTypeDef TIM_OCInitStructure; NVIC_InitTypeDef NVIC_InitStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE); //①使能定时器 3时钟 RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB| RCC_APB2Periph_AFIO, ENABLE); //①使能 GPIO 和 AFIO 复用功能时钟 GPIO_PinRemapConfig(GPIO_PartialRemap_TIM3,ENABLE); //②重映射 TIM3_CH2->PB5 //设置该引脚为复用输出功能,输出 TIM3 CH2的 PWM 脉冲波形 GPIOB.5 GPIO_InitStructure.GPIO_Pin =GPIO_Pin_5; //TIM_CH2 GPIO_InitStructure.GPIO_Mode =GPIO_Mode_AF_PP; //复用推挽输出 GPIO_InitStructure.GPIO_Speed =GPIO_Speed_50MHz; GPIO_Init(GPIOB,&GPIO_InitStructure); //①初始化 GPIO //初始化 TIM3 TIM_TimeBaseStructure.TIM_Period =arr; //设置在自动重装载周期值 TIM_TimeBaseStructure.TIM_Prescaler=psc; //设置预分频值 TIM_TimeBaseStructure.TIM_ClockDivision =0; //设置时钟分割:TDTS = Tck_tim TIM_TimeBaseStructure.TIM_CounterMode =TIM_CounterMode_Up; //TIM 向上计数模式 TIM_TimeBaseInit(TIM3,&TIM_TimeBaseStructure); //③初始化 TIMx //初始化 TIM3 Channel2 PWM模式 TIM_OCInitStructure.TIM_OCMode =TIM_OCMode_PWM1; //选择 PWM 模式 1 TIM_OCInitStructure.TIM_OutputState =TIM_OutputState_Enable; //比较输出使能 TIM_OCInitStructure.TIM_OCPolarity =TIM_OCPolarity_High; //输出极性高 TIM_OCInitStructure.TIM_Pulse = 1200; TIM_OC2Init(TIM3,&TIM_OCInitStructure); //④初始化外设 TIM3 OC2 TIM_OC2PreloadConfig(TIM3,TIM_OCPreload_Enable); //使能预装载寄存器 NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); TIM_ClearFlag(TIM3,TIM_IT_Update); TIM_ITConfig(TIM3,TIM_IT_Update, ENABLE); TIM_Cmd(TIM3, ENABLE); //⑤使能 TIM3 } void TIM3_IRQHandler(void) { if(TIM_GetITStatus(TIM3, TIM_IT_Update) == SET) { TIM_ClearITPendingBit(TIM3,TIM_IT_Update); if(pulse_count<24) //编码部分 { if(PULSE_CODE&(1<<(23-pulse_count))) //按位判断PULSE_CODE的二进制从前面开始,如果当前位==1,宽脉冲900,==,窄脉冲300 { LED0_PWM_DUTY = 900; pulse_count++; } else { LED0_PWM_DUTY= 300; pulse_count++; } } elseif(pulse_count == 24) //同步头 { LED0_PWM_DUTY= 300; pulse_count++; } elseif(pulse_count<31) //同步低电平部分 { LED0_PWM_DUTY= 0; pulse_count++; } else { LED0_PWM_DUTY= 0; pulse_count= 0; } } }
|