一内贮、通用定時(shí)器TIMx功能實(shí)現(xiàn)
添加stm32f10x_tim.c打開(kāi)stm32f10x_conf.h文件,將45行/*#include
"stm32f10x_tim.h"*/兩邊注釋符去掉
基本定時(shí)功能實(shí)現(xiàn)
1.配置RCC,使能TIMx
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
2.配置NVIC,設(shè)置優(yōu)先級(jí)等
NVIC_InitTypeDefNVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel= TIM2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
3.配置TIMx
?????? TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
//設(shè)置計(jì)數(shù)器溢出周期(周期系數(shù)-1)
TIM_TimeBaseStructure.TIM_Period= 35999;
//設(shè)置分頻系數(shù)(分頻系數(shù)-1)
TIM_TimeBaseStructure.TIM_Prescaler= 1999;
//設(shè)置計(jì)數(shù)方向
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
//使能定時(shí)器中斷
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
//使能定時(shí)器
TIM_Cmd(TIM2, ENABLE);
4.寫(xiě)中斷鉤子函數(shù)(或稱(chēng)為中斷服務(wù)函數(shù),在文件stm32f10x_it.c中具钥,也可在其它文件中創(chuàng)建)
{
if (TIM_GetITStatus(TIM2,TIM_IT_Update) != RESET)
{
TIM_ClearITPendingBit(TIM2,TIM_IT_Update);
//input your code
}
}
例:用TIM定時(shí)器功能輸出周期為20ms占峰比50%pwm信號(hào)
設(shè)置定時(shí)器2的定時(shí)周期為10um
?????? 定義全局變量num
預(yù)定義
#define GPIO0_OFFGPIO_ResetBits(GPIOA,GPIO_Pin_0)
#define GPIO0_ONGPIO_SetBits(GPIOA,GPIO_Pin_0)
?
void TIM2_IRQHandler(void)
{
??? if(TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
??? {
?????????? TIM_ClearITPendingBit(TIM2,TIM_IT_Update);
?
?????????? num=(num+1)%2000;??
?????????? if(num<1000)
????????????????? GPIOA0_H;
?????????? elseGPIOA0_L;?
}
TIM硬件產(chǎn)生pwm信號(hào)
?????? 首先要使能GPIO的AFIO時(shí)鐘使
GPIO要設(shè)置為GPIO_Mode_AF_PP? 復(fù)用推挽輸出
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);
TIM_OCInitTypeDef? TIM_OCInitStructure;
/* Output Compare Timing Modeconfiguration: Channel1 */
TIM_OCInitStructure.TIM_OCMode =
TIM_OCMode_PWM1;//定時(shí)模式
TIM_OCInitStructure.TIM_Pulse =100;//比較數(shù)和TIM_TimeBaseStructure.TIM_Period的值作比
TIM_OCInitStructure.TIM_OCPolarity
= TIM_OCPolarity_High;//TIM輸出比較極性低
TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable;
TIM_OC2Init(TIM2,
&TIM_OCInitStructure);// 使能TIM2的通道2
//TIM_OC1PreloadConfig(TIM2,
TIM_OCPreload_Enable);//使能TIM2的通道1
TIM功能使用注意:
1.TIM_PrescalerConfig(TIM2,PrescalerValue, TIM_PSCReloadMode_Immediate);
和TIM_TimeBaseStructure.TIM_Prescaler = 9; 作用的是同一寄存器TIMx->PSC
?2.定時(shí)器在使能后會(huì)啟動(dòng),如果這個(gè)時(shí)候其它初始化還沒(méi)完成液兽,容易造成不可知的錯(cuò)誤骂删,所以在初始化的時(shí)候,是能定時(shí)器應(yīng)該盡量放在最后