环境:
主机:WIN7
开发环境:MDK4.23
MCU:STM32F103CBT6
源代码1:
阐明:守时器选用TIM2,时钟源为内部8M晶振,向上溢出方式.此守时器用在延时函数,最小能够延时1us,故没有选用中止方式守时.
初始化代码:
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);//从头将Timer设置为缺省值TIM_DeInit(TIM2);//选用内部时钟给TIM2供给时钟源TIM_InternalClockConfig(TIM2);timInitStruct.TIM_ClockDivision = TIM_CKD_DIV2; //守时器基准频率8MHztimInitStruct.TIM_Prescaler = 8 - 1; //计数频率为1us跳转1次timInitStruct.TIM_CounterMode = TIM_CounterMode_Up; //向上计数timInitStruct.TIM_RepetitionCounter = 0;timInitStruct.TIM_Period = 0; //这个值实际上便是TIMX->ARR,延时开始时从头设定即可TIM_TimeBaseInit(TIM2, &timInitStruct);TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE); //计数溢出时触发中止TIM_Cmd(TIM2, ENABLE); //舱位计数器
延时函数代码:
//延时1us//最大65536usvoid _delay_us(uint16_t t){TIM_SetCounter(TIM2,0);TIM_SetAutoreload(TIM2,t - 1);//等待时间到while (TIM_GetITStatus(TIM2,TIM_FLAG_Update) == 0);//中止计数TIM_SetAutoreload(TIM2,0);//清中止标志TIM_ClearITPendingBit(TIM2,TIM_FLAG_Update);}//推迟1ms//最大65msvoid _delay_ms(uint8_t t){if (t > 65){t = 65;}_delay_us(t * 1000);}
源代码2:
阐明:守时器选用TIM3,时钟源为内部8M晶振,向上溢出方式.此守时器用在长期计时,最小计时距离为100us,故选用中止方式守时.
初始化代码:
//中止NVIC设置:答应中止,设置优先级NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn; //更新事情NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; //抢占优先级0NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; //呼应优先级1NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //答应中止NVIC_Init(&NVIC_InitStructure); //写入设置RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);//从头将Timer设置为缺省值TIM_DeInit(TIM3);//选用内部时钟给TIM3供给时钟源TIM_InternalClockConfig(TIM3);timInitStruct.TIM_ClockDivision = TIM_CKD_DIV2; //守时器基准频率8MHztimInitStruct.TIM_Prescaler = 800 - 1; //计数频率为100us跳转1次timInitStruct.TIM_CounterMode = TIM_CounterMode_Up; //向上计数timInitStruct.TIM_RepetitionCounter = 0;timInitStruct.TIM_Period = 0; //这个值实际上便是TIMX->ARR,延时开始时从头设定即可TIM_TimeBaseInit(TIM3, &timInitStruct);//清溢出中止标志TIM_ClearFlag(TIM3, TIM_FLAG_Update);//制止ARR预装载缓冲器TIM_ARRPreloadConfig(TIM3, DISABLE);//舱位中止TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE); TIM_Cmd(TIM3, ENABLE); //舱位计数器
中止函数代码:
//TIM3中止void TIM3_IRQHandler(void){if(TIM_GetITStatus(TIM3, TIM_IT_Update) == SET){TIM3->ARR = 0;//清中止溢出标志TIM_ClearITPendingBit(TIM3,TIM_FLAG_Update);//发送信号Sig_Table.stop_require = 1;}}