很多刚接触stm8的入门者不知到如何使用TIM1和TIM2的定时器作为定时功能。
下面介绍如下:
TIM1的初始化1us:
系统时钟是16M。void set_TIM1_nus(u16 nus)
{
/*1u的记数周期*/
/*TIM1_TimeBaseInit(0x0F,TIM1_COUNTERMODE_UP,nus,TIM1_RCR_RESET_VALUE);*/
/* Set the Autoreload value */
TIM1->ARRH = (u8)(nus >> 8);
TIM1->ARRL = (u8)(nus);
/* Set the Prescaler value */
TIM1->PSCRH = (u8)(0x0F >> 8);
TIM1->PSCRL = (u8)(0x0F);
/* Select the Counter Mode */
TIM1->CR1 = (u8)(((TIM1->CR1) & (u8)(~(TIM1_CR1_CMS | TIM1_CR1_DIR))) | (u8)(TIM1_COUNTERMODE_UP));
/* Set the Repetition Counter value */
TIM1->RCR = TIM1_RCR_RESET_VALUE;
/*打开1中断*/
/*TIM1_ITConfig( TIM1_IT_UPDATE , ENABLE); */
TIM1->IER |= (u8)TIM1_IT_UPDATE;
/*计时器打开*/
/*TIM1_Cmd(ENABLE); */
TIM1->CR1 |= TIM1_CR1_CEN;
/*TIM1_ClearFlag(TIM1_FLAG_UPDATE); */
/* Clear the flags (rc_w0) clear this bit by writing 0. Writing ??has no effect*/
TIM1->SR1 = (u8)(~(u8)(TIM1_FLAG_UPDATE));
TIM1->SR2 = (u8)((u8)(~((u8)((u16)TIM1_FLAG_UPDATE >> 8))) & (u8)0x1E);
}
TIM2的初始化如下:
初始化为1ms
void time2_set_1ms(void)
{
My_TIM2_TimeBaseInit(TIM2_PRESCALER_16,1000);
My_TIM2_ITConfig( TIM2_IT_UPDATE , ENABLE);
My_TIM2_SetCounter(0x0000);
/*计时器打开*/
My_TIM2_Cmd(ENABLE);
My_TIM2_ClearFlag(TIM2_FLAG_UPDATE);
}
中断处理部分,两者基本上都是一致的:
中断处理函数里面清除本次的中断就好了。其他功能自己定义。
TIMx_ClearFlag(TIM_FLAG_UPDATE);
|