热度 20
2012-10-10 15:08
5285 次阅读|
0 个评论
1、STM32内部有8个定时器, tim1 和tim8 是高级定时器,TIM6、7 是基本定时器,TIM 2、3、4、5是通用定时器,通用定时器是可编程预分频的16位自动重装的计数器; 分频系数为1~65535 ,四个独立通道:输入捕获,输出比较,PWM波生成,单脉冲模式输出; 发生如下事故可以触发中断/DMA (1)计数器向上或向下溢出,启动、停止(2)输出捕获;(3)输出比较 2、实验任务:用stm32的通用定时器TIM2实现1s 定时,在中断服务函数中,每过1s 向串口发送“okok”字符。 3、实验程序: (1)TIM2.c : /***************** function name:void TIM2_Init(void) describe: configuration the TIM2 basetime and OC input:null ouput:null return:null *****************/ #include"TIM2.h" void TIM2_Init(void) { //基础设置,时基和比较输出设置,由于这里只需定时,所以不用OC比较输出 //RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE); TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; //TIM_OCInitTypeDef TIM_OCInitStructure; //reset TIM2 TIM_DeInit(TIM2); //a period is 10000 times TIM_TimeBaseStructure.TIM_Period=1000; //prescaler is 1200,that is 72000000/72/1000=1000Hz; TIM_TimeBaseStructure.TIM_Prescaler=72-1;//division number is 72 //set clock division TIM_TimeBaseStructure.TIM_ClockDivision=TIM_CKD_DIV1; //or TIM_CKD_DIV2 or TIM_CKD_DIV4 //count up TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up; TIM_TimeBaseInit(TIM2,TIM_TimeBaseStructure); //clear the TIM2 overflow interrupt flag TIM_ClearFlag(TIM2,TIM_FLAG_Update); //TIM2 overflow interrupt enable TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE); //enable TIM2 TIM_Cmd(TIM2,ENABLE); } void RCC_Configuration(void) { //enable the TIM2 channel2 and PA Clocks RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE); // RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE); } /***************** function name:void NVIC_Configuration(void) describe: configuration the NVIC input:null ouput:null return:null *****************/ void NVIC_Configuration(void) { NVIC_InitTypeDef NVIC_InitStructure; NVIC_InitStructure.NVIC_IRQChannel=TIM2_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=0; NVIC_InitStructure.NVIC_IRQChannelSubPriority=4; NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE; NVIC_Init(NVIC_InitStructure); } (2)TIM.h #ifndef __TIM2_H #define __TIM2_H #include"stm32f10x.h" void TIM2_Init(void); void NVIC_Configuration(void); #endif (3)在stm32f10x_it.c 中的中断服务函数: void TIM2_IRQHandler(void) { if ( TIM_GetITStatus(TIM2 , TIM_IT_Update) != RESET ) { TIM_ClearITPendingBit(TIM2 , TIM_FLAG_Update); //定时1ms time++; if(time==1000) //1s { printf("okok \r\n "); time=0; } } } 注意:由于服务函数中用到printf函数和变量time ,所以应该在stm32f10x_it.c 作如下声明: #include "stdio.h" extern volatile u32 time; 如果要调用某外部函数,也要作相应声明:extern + 函数名称; (4)主函数: #include"stm32f10x.h" #include"usart1.h" #include"TIM2.h" volatile u32 time; int main(void) { /* config the sysclock to 72m */ SystemInit(); RCC_Configuration(); NVIC_Configuration(); USART_Config(); TIM2_Init(); printf("\r\n begin \r\n"); //wait while(1) { }; } 备注:串口函数已经学过,所以这里直接添加进来即可,不必修改。