#include "stm32f10x.h"
void GPIO_TimPWM(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA , ENABLE);//
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7; //TIM_CH2 GPIOA_Pin_7输出
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure); //不解释
}
void TIM3_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); //使能TIM3
//假如我要产生50Hz占空比为50%的PWM波,方便控制舵机
//设置方法:
//系统默认时钟为72MHz,预分频71+1次,得到TIM3计数时钟为1MHz
//计数长度为19999+1=20000,可得PWM频率为1M/20000=50Hz
//具体设置可参考上面的设置方法,简单明了!
TIM_TimeBaseStructure.TIM_Prescaler = 72-1;//网上多数设置有误
TIM_TimeBaseStructure.TIM_Period = 20000-1;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
//设置时钟分割: TIM_CKD_DIV1 = 0,PWM波不延时(延时破坏占空比?待考证)
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIM向上计数模式
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
TIM_ARRPreloadConfig(TIM3, DISABLE); //禁止ARR预装载缓冲器,也可以不用设置
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2; //选择定时器模式:TIM脉冲宽度调制模式2
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //比较输出使能
//占空比设置方法:
//占空比=(TIM_Pulse+1)/(TIM_Pulse+1)-(TIM_Period+1)=10000/20000=0.5=50%
TIM_OCInitStructure.TIM_Pulse = 10000-1;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; //输出极性:TIM输出比较极性高
TIM_OC2Init(TIM3, &TIM_OCInitStructure); //根据TIM_OCInitStruct中指定的参数初始化外设TIMx
TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable); //使能TIMx在CCR2上的预装载寄存器
//上面两句中的OC2确定了是channle几,要是OC3则是channel 3
TIM_CtrlPWMOutputs(TIM3,ENABLE); //设置TIM2的PWM输出为使能
TIM_ARRPreloadConfig(TIM3, ENABLE); //使能TIMx在ARR上的预装载寄存器
TIM_Cmd(TIM3, ENABLE); //使能TIMx外设
}
int main(void)
{
GPIO_TimPWM();
TIM3_Configuration();
while(1)
{
} ;
}
利用Keil逻辑分析仪分分析PWM波形图:经过测试可以看出输出波形精度可靠!