8位基本定时器(TIM4)

Posted Christal_R

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了8位基本定时器(TIM4)相关的知识,希望对你有一定的参考价值。

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

主要功能:

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

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

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

代码实现:

 1 /* Includes ------------------------------------------------------------------*/
 2 #include "stm8s.h"
 3 
 4 /* Private define ------------------------------------------------------------*/
 5 #define TIM4_PERIOD       124
 6 /* Private variables ---------------------------------------------------------*/
 7 __IO uint32_t TimingDelay = 0;
 8 /* Private function prototypes -----------------------------------------------*/
 9 void Delay(__IO uint32_t nTime);
10 void TimingDelay_Decrement(void);
11 static void TIM4_Config(void);
12 
13 /**
14   * @brief  Main program.
15   * @param  None
16   * @retval None
17   */
18 void main(void)
19 {
20   /* TIM4 configuration -----------------------------------------*/
21   TIM4_Config();    
22   
23   /* Insert 50 ms delay */
24   Delay(50);
25   }
26 }
27 
28 /**
29   * @brief  Configure TIM4 to generate an update interrupt each 1ms 
30   * @param  None
31   * @retval None
32   */
33 static void TIM4_Config(void)
34 {
35   /* TIM4 configuration:
36    - TIM4CLK is set to 16 MHz, the TIM4 Prescaler is equal to 128 so the TIM1 counter
37    clock used is 16 MHz / 128 = 125 000 Hz
38   - With 125 000 Hz we can generate time base:
39       max time base is 2.048 ms if TIM4_PERIOD = 255 --> (255 + 1) / 125000 = 2.048 ms
40       min time base is 0.016 ms if TIM4_PERIOD = 1   --> (  1 + 1) / 125000 = 0.016 ms
41   - In this example we need to generate a time base equal to 1 ms
42    so TIM4_PERIOD = (0.001 * 125000 - 1) = 124 */
43 
44   /* Time base configuration */
45   TIM4_TimeBaseInit(TIM4_PRESCALER_128, TIM4_PERIOD);
46   /* Clear TIM4 update flag */
47   TIM4_ClearFlag(TIM4_FLAG_UPDATE);
48   /* Enable update interrupt */
49   TIM4_ITConfig(TIM4_IT_UPDATE, ENABLE);
50   
51   /* enable interrupts */
52   enableInterrupts();
53 
54   /* Enable TIM4 */
55   TIM4_Cmd(ENABLE);
56 }
57 
58 
59 /**
60   * @brief  Inserts a delay time.
61   * @param  nTime: specifies the delay time length, in milliseconds.
62   * @retval None
63   */
64 void Delay(__IO uint32_t nTime)
65 {
66   TimingDelay = nTime;
67 
68   while (TimingDelay != 0);
69 }
70 
71 /**
72   * @brief  Decrements the TimingDelay variable.
73   * @param  None
74   * @retval None
75   */
76 void TimingDelay_Decrement(void)
77 {
78   if (TimingDelay != 0x00)
79   {
80     TimingDelay--;
81   }
82 }
TIM4

 

以上是关于8位基本定时器(TIM4)的主要内容,如果未能解决你的问题,请参考以下文章

STM32F103ZET6 PWM输出

STM32 PWM设定输出

stm8S毫秒定时器

暂时禁用定时器中断

四个通用定时器(TIM2 TIM3 TIM4 TIM5)的四通道调用

STM32-HAL库-TIMx学习