stm32
keil
主函数如下,是一个简单的例子,定时切换IO口输出int main(void){ /* System Clocks Configuration */ RCC_Configuration(); /* Configure the GPIO ports */ GPIO_Configuration(); TIM_NVIC( ); TIM_Configuration(); TIM_Enable(); while(1) { GPIO_SetBits(GPIOB, GPIO_Pin_12 ); //打开 DelaySec(1); GPIO_ResetBits(GPIOB, GPIO_Pin_12); //关闭 DelaySec(1);}
RCC配置void RCC_Configuration(void){ /* Setup the microcontroller system. Initialize the Embedded Flash Interface, initialize the PLL and update the SystemFrequency variable. */ SystemInit(); /* Enable GPIOx clock */ RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE); //用到B12做输出打开GPIOB RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); //定时器中断}此处就是打开TIM2 和GPIOB的时钟
GPIO配置void GPIO_Configuration(void){ GPIO_InitTypeDef GPIO_InitStructure; GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12; //LED GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_OD; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOB, &GPIO_InitStructure);}用GPIOB 12做LED灯的控制管脚
TIM的配置//定时为1秒,1秒溢出 void TIM_Configuration(void){TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;// /* 基础设置*/ 72M除以7200分频后每10000次为1秒。TIM_TimeBaseStructure.TIM_Period = 10000-1; //计数值 TIM_TimeBaseStructure.TIM_Prescaler = 7200-1; //预分频,此值+1为分频的除数TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; //TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //向上计数TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);/* TIM2 enable counter */ TIM_Cmd(TIM2, ENABLE);}void TIM_NVIC(void){ NVIC_InitTypeDef NVIC_InitStructure; NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure);}void TIM_Enable(void){ /*预先清除所有中断位*/ TIM_ClearITPendingBit(TIM2,TIM_IT_Update); /* 4个通道和溢出都配置中断*/ TIM_ITConfig(TIM2,TIM_IT_Update, ENABLE);}此处配置TIM2的各种模式。
定时函数的实现volatile u32 sec = 0; 为全局变量void onesec(void){ if (TIM_GetITStatus(TIM2,TIM_IT_Update) != RESET) { TIM_ClearITPendingBit(TIM2,TIM_IT_Update); sec++; }}//定时的秒函数 count为传入的秒数void DelaySec(int count){ sec = 0; while(count > sec);}
TIM 2 中断函数的实现 stm32f10x_it.c文件中void TIM2_IRQHandler(void){ onesec(); }
定时器,主要设置寄存器装载那里的一些分频值和溢出值。