论坛元老
- 积分
- 3071
- 金钱
- 3071
- 注册时间
- 2018-2-7
- 在线时间
- 285 小时
|
发表于 2019-11-22 19:05:32
|
显示全部楼层
可以考虑用PWM比较模式
- void TIM3_CMP_Init(u16 arr, u16 psc)
- {
- GPIO_InitTypeDef GPIO_InitStructure;
- TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
- TIM_OCInitTypeDef TIM_OCInitStructure;
- RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); //使能定时器3时钟
- RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC | RCC_APB2Periph_AFIO, ENABLE); //使能GPIOC时钟
- GPIO_PinRemapConfig(GPIO_FullRemap_TIM3, ENABLE); //Timer3全部重映射 TIM3_CH2(PA7)--->PB5 TIM3_CH1(PA6)-->PB4
-
- GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7 | GPIO_Pin_8 | GPIO_Pin_9;
- GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
- GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
- GPIO_Init(GPIOC, &GPIO_InitStructure);
- //初始化TIM3
- TIM_TimeBaseInitStructure.TIM_Period = arr;
- TIM_TimeBaseInitStructure.TIM_Prescaler = psc;
- TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
- TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
- TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStructure);
-
- //初始化TIM3 比较 模式
- TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Toggle;
- TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
- TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
-
- TIM_OC1Init(TIM3, &TIM_OCInitStructure);
- TIM_OC2Init(TIM3, &TIM_OCInitStructure);
- TIM_OC3Init(TIM3, &TIM_OCInitStructure);
- TIM_OC4Init(TIM3, &TIM_OCInitStructure);
-
- TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Enable);
- TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable);
- TIM_OC3PreloadConfig(TIM3, TIM_OCPreload_Enable);
- TIM_OC4PreloadConfig(TIM3, TIM_OCPreload_Enable);
-
- //使能TIM3
- TIM_Cmd(TIM3, ENABLE);
- }
- int main(void)
- {
- u16 led_pwm_val=0;
- u8 dir=1;
- delay_init(); //延时函数初始化
- NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
- LED_Init();
-
-
- LED0 = 1;
- LED1 = 1;
- delay_ms(500);
- LED0 = 0;
- LED1 = 0;
- //比较输出模式下: ARR 决定输出频率 CCRx 决定每个通道的初始相位
- //PWM模式: ARR 决定输出频率 CCRx 决定输出 的高电平时长
-
- TIM3_CMP_Init(500-1,72-1);
- TIM_SetCompare1(TIM3,100);
- TIM_SetCompare2(TIM3,200);
- TIM_SetCompare3(TIM3,300);
- TIM_SetCompare4(TIM3,400);
- while(1)
- {
- delay_ms(200);
- LED0 = !LED0;
-
-
- }
- }
复制代码 |
|