#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; //復(fù)用推挽輸出
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
//假如我要產(chǎn)生50Hz占空比為50%的PWM波,方便控制舵機
//設(shè)置方法:
//系統(tǒng)默認時鐘為72MHz,預(yù)分頻71+1次,得到TIM3計數(shù)時鐘為1MHz
//計數(shù)長度為19999+1=20000,可得PWM頻率為1M/20000=50Hz
//具體設(shè)置可參考上面的設(shè)置方法,簡單明了!
TIM_TimeBaseStructure.TIM_Prescaler =72-1;//網(wǎng)上多數(shù)設(shè)置有誤
TIM_TimeBaseStructure.TIM_Period =20000-1;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
//設(shè)置時鐘分割:TIM_CKD_DIV1 = 0,PWM波不延時(延時破壞占空比?待考證)
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIM向上計數(shù)模式
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
TIM_ARRPreloadConfig(TIM3, DISABLE); //禁止ARR預(yù)裝載緩沖器,也可以不用設(shè)置
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2; //選擇定時器模式:TIM脈沖寬度調(diào)制模式2
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //比較輸出使能
//占空比設(shè)置方法:
//占空比=(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); //根據(jù)TIM_OCInitStruct中指定的參數(shù)初始化外設(shè)TIMx
TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable); //使能TIMx在CCR2上的預(yù)裝載寄存器
//上面兩句中的OC2確定了是channle幾,要是OC3則是channel 3
TIM_CtrlPWMOutputs(TIM3,ENABLE); //設(shè)置TIM2的PWM輸出為使能
TIM_ARRPreloadConfig(TIM3, ENABLE); //使能TIMx在ARR上的預(yù)裝載寄存器
TIM_Cmd(TIM3, ENABLE); //使能TIMx外設(shè)
}
int main(void)
{
GPIO_TimPWM();
TIM3_Configuration();
while(1)
{
} ;
}
利用Keil
邏輯分析儀分分析PWM波形圖:經(jīng)過測試可以看出輸出波形精度可靠!
評論