STM8S003F定时器延时
文章目录
- 一、前言
- 二、定时器初始化
- 三、定时器函数与中断处理
一、前言
本次使用STM8S003F芯片,编译环境为IAR,至于新建工程什么的教程很多,这里就不多叙述了。其实官方例程里是有定时器延时的,使用定时器4固定频率,在中断里运行,就可以像系统一样按毫秒延时。
二、定时器初始化
#define TIM4_PERIOD 124
__IO uint32_t TimingDelay = 0;
/**
* @brief Configure TIM4 to generate an update interrupt each 1ms
* @param None
* @retval None
*/
static void TIM4_Config(void)
{
/* TIM4 configuration:
- TIM4CLK is set to 16 MHz, the TIM4 Prescaler is equal to 128 so the TIM1 counter
clock used is 16 MHz / 128 = 125 000 Hz
- With 125 000 Hz we can generate time base:
max time base is 2.048 ms if TIM4_PERIOD = 255 --> (255 + 1) / 125000 = 2.048 ms
min time base is 0.016 ms if TIM4_PERIOD = 1 --> ( 1 + 1) / 125000 = 0.016 ms
- In this example we need to generate a time base equal to 1 ms
so TIM4_PERIOD = (0.001 * 125000 - 1) = 124 */
/* Time base configuration */
TIM4_TimeBaseInit(TIM4_PRESCALER_128, TIM4_PERIOD);
/* Clear TIM4 update flag */
TIM4_ClearFlag(TIM4_FLAG_UPDATE);
/* Enable update interrupt */
TIM4_ITConfig(TIM4_IT_UPDATE, ENABLE);
/* enable interrupts */
enableInterrupts();
/* Enable TIM4 */
TIM4_Cmd(ENABLE);
}
三、定时器函数与中断处理
定时器函数初始化定时时间:
void Delay(__IO uint32_t nTime)
{
TimingDelay = nTime;
while (TimingDelay != 0)
;
}
中断函数:
void TimingDelay_Decrement(void)
{
if (TimingDelay != 0x00)
{
TimingDelay--;
}
}
在中断里增加中断函数:
extern void TimingDelay_Decrement(void);
INTERRUPT_HANDLER(TIM4_UPD_OVF_IRQHandler, 23)
{
TimingDelay_Decrement();
/* Cleat Interrupt Pending bit */
TIM4_ClearITPendingBit(TIM4_IT_UPDATE);
}