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 
11 const uint16_t _bc_timer_prescaler_lut[3] =
12 {
13  2,
14  15,
15  31,
16 };
17 
18 inline void bc_timer_init(void)
19 {
20  // Enable clock for TIM22
21  RCC->APB2ENR |= RCC_APB2ENR_TIM22EN;
22 }
23 
24 inline void bc_timer_start(void)
25 {
26  TIM22->PSC = _bc_timer_prescaler_lut[bc_system_clock_get()]; // 7 instructions
27 
28  TIM22->CNT = 0;
29 
30  TIM22->EGR = TIM_EGR_UG;
31 
32  TIM22->CR1 |= TIM_CR1_CEN;
33 }
34 
35 inline uint16_t bc_timer_get_microseconds(void)
36 {
37  return TIM22->CNT;
38 }
39 
40 inline void bc_timer_delay(uint16_t microseconds)
41 {
42  uint16_t t = bc_timer_get_microseconds() + microseconds;
43 
44  while (bc_timer_get_microseconds() < t)
45  {
46  continue;
47  }
48 }
49 
50 inline void bc_timer_clear(void)
51 {
52  TIM22->CNT = 0;
53 }
54 
55 inline void bc_timer_stop(void)
56 {
57  TIM22->CR1 &= ~TIM_CR1_CEN;
58 }
59 
60 void bc_timer_clear_irq_handler(TIM_TypeDef *tim)
61 {
62  if (tim == TIM3)
63  {
64  bc_timer_tim3_irq.irq_handler = NULL;
65  }
66 }
67 
68 bool bc_timer_set_irq_handler(TIM_TypeDef *tim, void (*irq_handler)(void *), void *irq_param)
69 {
70  //application_error
71  if (tim == TIM3)
72  {
73  if (bc_timer_tim3_irq.irq_handler == NULL)
74  {
75  bc_timer_tim3_irq.irq_handler = irq_handler;
76  bc_timer_tim3_irq.irq_param = irq_param;
77  return true;
78  }
79  }
80 
81  return false;
82 }
83 
84 void TIM3_IRQHandler(void)
85 {
86  if (bc_timer_tim3_irq.irq_handler)
87  {
88  bc_timer_tim3_irq.irq_handler(bc_timer_tim3_irq.irq_param);
89  }
90 }
void bc_timer_start(void)
Start timer.
Definition: bc_timer.c:24
void bc_timer_delay(uint16_t microseconds)
Relative delay.
Definition: bc_timer.c:40
void bc_timer_stop(void)
Stop timer.
Definition: bc_timer.c:55
void bc_timer_clear(void)
Clear timer counter.
Definition: bc_timer.c:50
uint16_t bc_timer_get_microseconds(void)
Get actual tick of timer.
Definition: bc_timer.c:35
bool bc_timer_set_irq_handler(TIM_TypeDef *tim, void(*irq_handler)(void *), void *irq_param)
Register timer IRQ handler.
Definition: bc_timer.c:68
void bc_timer_clear_irq_handler(TIM_TypeDef *tim)
Unregister timer IRQ handler.
Definition: bc_timer.c:60
void bc_timer_init(void)
Initialize timer.
Definition: bc_timer.c:18