简介:该定时器由一个带可编程预分频器的8位自动重载的向上计数器所组成,它可以用来作为时基发生器,具有溢出中断功能。

8位基本定时器(TIM4)-LMLPHP

主要功能:

(1)8位向上计数的自动重载计数器;

(2)3位可编程的预分配器(可在运行中修改),提供1、2、4、8、16、32、64、128这8种分频比例;

(3)中断产生:更新中断(溢出,计数器初始化)。

代码实现:

 /* Includes ------------------------------------------------------------------*/
#include "stm8s.h" /* Private define ------------------------------------------------------------*/
#define TIM4_PERIOD 124
/* Private variables ---------------------------------------------------------*/
__IO uint32_t TimingDelay = ;
/* Private function prototypes -----------------------------------------------*/
void Delay(__IO uint32_t nTime);
void TimingDelay_Decrement(void);
static void TIM4_Config(void); /**
* @brief Main program.
* @param None
* @retval None
*/
void main(void)
{
/* TIM4 configuration -----------------------------------------*/
TIM4_Config(); /* Insert 50 ms delay */
Delay();
}
} /**
* @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);
} /**
* @brief Inserts a delay time.
* @param nTime: specifies the delay time length, in milliseconds.
* @retval None
*/
void Delay(__IO uint32_t nTime)
{
TimingDelay = nTime; while (TimingDelay != );
} /**
* @brief Decrements the TimingDelay variable.
* @param None
* @retval None
*/
void TimingDelay_Decrement(void)
{
if (TimingDelay != 0x00)
{
TimingDelay--;
}
}

TIM4

04-28 01:35