转自http://constancy.blog.51cto.com/4414209/1089395/
调试芯片:STM32F103C8T6
外部晶振:8MHz
功能介绍:使用Timer3实现两路(可四路)PWM波形的输出
代码如下:
初始化:系统时钟初始化,GPIO端口初始化,Timer初始化
系统时钟初始化:
-
- SystemInit();
GPIO端口初始化:
- ***************************************************************
- void GPIO_Config(void)
-
-
-
-
-
- void GPIO_Config(void)
- {
- GPIO_InitTypeDef GPIO_InitStructure;
-
-
- RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
-
-
- GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
- GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
- GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
- GPIO_Init(GPIOA, &GPIO_InitStructure);
- }
Timer初始化:
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- void TIM3_Config(void)
- {
- TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
- TIM_OCInitTypeDef TIM_OCInitStructure;
-
- u16 CCR1= 36000;
- u16 CCR2= 36000;
-
- RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
-
- TIM_TimeBaseStructure.TIM_Period =0xEA5F;
- TIM_TimeBaseStructure.TIM_Prescaler = 2;
- TIM_TimeBaseStructure.TIM_ClockDivision = 0;
- TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
- TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
-
- TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
- TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
- TIM_OCInitStructure.TIM_Pulse = CCR1;
- TIM_OCInitStructure.TIM_OCPolarity =TIM_OCPolarity_High;
- TIM_OC1Init(TIM3, &TIM_OCInitStructure);
- TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Enable);
-
- TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
- TIM_OCInitStructure.TIM_Pulse = CCR2;
- TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
- TIM_OC2Init(TIM3, &TIM_OCInitStructure);
- TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable);
- TIM_ARRPreloadConfig(TIM3, ENABLE);
-
- TIM_Cmd(TIM3, ENABLE);
- }
主函数代码:
- **************************************************************
-
-
-
-
-
- int main(void)
- {
- SystemInit();
- GPIO_Config();
- TIM3_Config();
- while (1)
- {
-
- }
- }
最后上结果图:
![](https://i-blog.csdnimg.cn/blog_migrate/5e9db5df4d399e31545413d85ac4a544.jpeg)
疑问:虽然不影响用,但是为什么第一个周期不正确,正确的波形是从第二个周期开始输出的?