Firmware SDK
 All Data Structures Functions Variables Typedefs Enumerations Enumerator Groups Pages
bc_timer.c
1 #include <bc_timer.h>
2 
3 typedef struct bc_timer_irq_t
4 {
5  void (*irq_handler)(void *);
6  void *irq_param;
8 
9 bc_timer_irq_t bc_timer_tim3_irq;
10 bc_timer_irq_t bc_timer_tim6_irq;
11 
12 const uint16_t _bc_timer_prescaler_lut[3] =
13 {
14  2,
15  15,
16  31,
17 };
18 
19 inline void bc_timer_init(void)
20 {
21  // Enable clock for TIM22
22  RCC->APB2ENR |= RCC_APB2ENR_TIM22EN;
23 }
24 
25 inline void bc_timer_start(void)
26 {
27  TIM22->PSC = _bc_timer_prescaler_lut[bc_system_clock_get()]; // 7 instructions
28 
29  TIM22->CNT = 0;
30 
31  TIM22->EGR = TIM_EGR_UG;
32 
33  TIM22->CR1 |= TIM_CR1_CEN;
34 }
35 
36 inline uint16_t bc_timer_get_microseconds(void)
37 {
38  return TIM22->CNT;
39 }
40 
41 inline void bc_timer_delay(uint16_t microseconds)
42 {
43  uint16_t t = bc_timer_get_microseconds() + microseconds;
44 
45  while (bc_timer_get_microseconds() < t)
46  {
47  continue;
48  }
49 }
50 
51 inline void bc_timer_clear(void)
52 {
53  TIM22->CNT = 0;
54 }
55 
56 inline void bc_timer_stop(void)
57 {
58  TIM22->CR1 &= ~TIM_CR1_CEN;
59 }
60 
61 void bc_timer_clear_irq_handler(TIM_TypeDef *tim)
62 {
63  if (tim == TIM3)
64  {
65  bc_timer_tim3_irq.irq_handler = NULL;
66  }
67  if (tim == TIM6)
68  {
69  bc_timer_tim6_irq.irq_handler = NULL;
70  }
71 }
72 
73 bool bc_timer_set_irq_handler(TIM_TypeDef *tim, void (*irq_handler)(void *), void *irq_param)
74 {
75  if (tim == TIM3)
76  {
77  if (bc_timer_tim3_irq.irq_handler == NULL)
78  {
79  bc_timer_tim3_irq.irq_handler = irq_handler;
80  bc_timer_tim3_irq.irq_param = irq_param;
81  return true;
82  }
83  }
84  if (tim == TIM6)
85  {
86  if (bc_timer_tim6_irq.irq_handler == NULL)
87  {
88  bc_timer_tim6_irq.irq_handler = irq_handler;
89  bc_timer_tim6_irq.irq_param = irq_param;
90  return true;
91  }
92  }
93 
94  return false;
95 }
96 
97 void TIM3_IRQHandler(void)
98 {
99  if (bc_timer_tim3_irq.irq_handler)
100  {
101  bc_timer_tim3_irq.irq_handler(bc_timer_tim3_irq.irq_param);
102  }
103 }
104 
105 void TIM6_IRQHandler()
106 {
107  if (bc_timer_tim6_irq.irq_handler)
108  {
109  bc_timer_tim6_irq.irq_handler(bc_timer_tim6_irq.irq_param);
110  }
111 }
void bc_timer_start(void)
Start timer.
Definition: bc_timer.c:25
void bc_timer_delay(uint16_t microseconds)
Relative delay.
Definition: bc_timer.c:41
void bc_timer_stop(void)
Stop timer.
Definition: bc_timer.c:56
void bc_timer_clear(void)
Clear timer counter.
Definition: bc_timer.c:51
uint16_t bc_timer_get_microseconds(void)
Get actual tick of timer.
Definition: bc_timer.c:36
bool bc_timer_set_irq_handler(TIM_TypeDef *tim, void(*irq_handler)(void *), void *irq_param)
Register timer IRQ handler.
Definition: bc_timer.c:73
void bc_timer_clear_irq_handler(TIM_TypeDef *tim)
Unregister timer IRQ handler.
Definition: bc_timer.c:61
void bc_timer_init(void)
Initialize timer.
Definition: bc_timer.c:19