目录
原理简介
定时时间
具体代码
定时函数取值范围
原理简介
定时器就是一直隔一段时间会进来处理数据,如果处理串口例如9600波特率,那么就需要每过104us进行检测,定时检测的时间只能比104us时间小,不能大。
如果连续检测到gpio的变化就开始执行别的函数。
(为什么我不用串口中断检测,因为我这边是gpio模拟的串口,工作中很多地方都需要扩展串口)
定时时间
1s = 1000ms = 1000000us |
1 / 72MHz = 13. 89ns,72Mhz,
72MHz=72000KHz=72000000Hz相当于1秒中可以记72000000次数
波特率9600 即1s能传输9600个二进制位,即1s = 1000000us ,100000 / 9600 = 104us
(103+1)*(71+1)/72Mhz = 104us ,9600
TIM2_Int_Init(103,71); //(103+1)*(71+1)/72Mhz = 104us ,9600
TIM3_Int_Init(9999,71); //(100)*(71+1)/72Mhz = 100us,T
// 1s = 1000000us
具体代码
void TIM2_Int_Init(unsigned short int arr,unsigned short int psc)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
NVIC_InitTypeDef NVIC_InitStructure;RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); TIM_TimeBaseStructure.TIM_Period = arr - 1;
TIM_TimeBaseStructure.TIM_Prescaler =psc - 1;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure); TIM_ClearITPendingBit(TIM2, TIM_FLAG_Update);TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE ); NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn ;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure);
}
void TIM2_IRQHandler(void)
{if(TIM_GetFlagStatus(TIM2, TIM_IT_Update) != RESET)//TIM_FLAG_Update { TIM_ClearITPendingBit(TIM2, TIM_IT_Update); if(GPIO_ReadInputDataBit(GPIOB,Gpio_Usart_Rx)){
gpio_uart_cnt++;if(gpio_uart_cnt >20000) //计数超过2s一直检测到gpio的高电平,即没有低电平输入{TIM_Cmd(TIM2, DISABLE); //关闭定时器
gpio_uart_cnt = 0; //计时器清零System_reboot(); //系统重启,模块重启等等(这块地方随便放其他函数)}}else {
gpio_uart_cnt = 0; //检测到低电平,就清零计数} } }/*初始化函数,初始化gpio和定时器,该函数放main里面*/void Gpio_Usart_Init(void)
{GPIO_Configuration(); //gpio函数初始化自定义这块TIM2_Int_Init(104,72); //(103+1)*(71+1)/72Mhz = 104us ,9600
}
定时函数取值范围
uint16_t TIM_Period; /*!< Specifies the period value to be loaded into the active
Auto-Reload Register at the next update event.
This parameter must be a number between 0x0000 and 0xFFFF. */
0xFFF (hex)= 65535(dec) 即取值范围0~65535