STM32-高級(jí)定時(shí)器TIM1的應(yīng)用
void GPIO_Configuration(void)//配置IO腳
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
}
void TIM1_Configuration(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_DeInit(TIM1); //重設(shè)為缺省值
TIM_TimeBaseStructure.TIM_Prescaler = 4000; //預(yù)分頻(時(shí)鐘分頻)72M/4000=18K
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //向上計(jì)數(shù)
TIM_TimeBaseStructure.TIM_Period = 144; //裝載值 18k/144=125hz 就是說(shuō)向上加的144便滿了
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; //設(shè)置了時(shí)鐘分割 不懂得不管
TIM_TimeBaseStructure.TIM_RepetitionCounter = 0x0; //周期計(jì)數(shù)器值 不懂得不管
TIM_TimeBaseInit(TIM1,&TIM_TimeBaseStructure); //初始化TIMx的時(shí)間基數(shù)單位
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2; //PWM模式2
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //正向通道有效 PA8
TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable; //反向通道也有效 PB13
TIM_OCInitStructure.TIM_Pulse = 40; //占空時(shí)間 144 中有40的時(shí)間為高,互補(bǔ)的輸出正好相反
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low; //輸出極性
TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_Low; //互補(bǔ)端的極性
TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Reset; //空閑狀態(tài)下的非工作狀態(tài) 不管
TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCIdleState_Reset; //先不管
TIM_OC1Init(TIM1,&TIM_OCInitStructure); //數(shù)初始化外設(shè)TIMx通道1這里2.0庫(kù)為T(mén)IM_OCInit
TIM_Cmd(TIM1,ENABLE);
TIM_CtrlPWMOutputs(TIM1,ENABLE);
}
void SetT1Pwm1(u16 pulse)//設(shè)置捕獲寄存器1
{
TIM1->CCR1=pulse;
}
/*TIM1的定時(shí)器通道時(shí)間 1到4 分別為 PB8 PA9 PA10 PA11 而互補(bǔ)輸出分別為 PB13 、PB14 、PB15、 PB12
如果輸出與互補(bǔ)輸出極性相同的話 就剛好輸出高 互補(bǔ)低 至于PWM模式1 與模式2的區(qū)別。如下圖模式一:
模式2與模式1互補(bǔ),144中有40 為高 互補(bǔ)的有40為低。