-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimer2.c
More file actions
104 lines (79 loc) · 1.87 KB
/
timer2.c
File metadata and controls
104 lines (79 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/*
* timer2.c
*
* Created on: Feb 20, 2026
* Author: Rubin Khadka
*/
#include "stm32f103xb.h"
#include "timer2.h"
// Millisecond counter
static volatile uint32_t system_millis = 0;
void TIMER2_Init(void)
{
// Enable TIM2 clock
RCC->APB1ENR |= RCC_APB1ENR_TIM2EN;
// Small delay for clock to stabilize
for(volatile int i = 0; i < 10; i++);
// Configure for 1ms resolution at 72MHz
TIM2->PSC = 7200 - 1; // Prescaler = 7199
// Auto-reload for 1ms (10 ticks at 10kHz = 1ms)
TIM2->ARR = 10 - 1;
// Clear counter
TIM2->CNT = 0;
// Clear update flag
TIM2->SR &= ~TIM_SR_UIF;
// Enable update interrupt
TIM2->DIER |= TIM_DIER_UIE;
// Enable TIM2 interrupt in NVIC
NVIC_EnableIRQ(TIM2_IRQn);
NVIC_SetPriority(TIM2_IRQn, 1);
// Start timer
TIM2->CR1 |= TIM_CR1_CEN;
}
// TIM2 Interrupt Handler
void TIM2_IRQHandler(void)
{
// Check if update interrupt flag is set
if(TIM2->SR & TIM_SR_UIF)
{
// Clear the interrupt flag
TIM2->SR &= ~TIM_SR_UIF;
// Increment millisecond counter
system_millis++;
}
}
// Get current system time in milliseconds
uint32_t TIMER2_GetMillis(void)
{
uint32_t ms;
// Disable interrupts to read consistent value
__disable_irq();
ms = system_millis;
__enable_irq();
return ms;
}
// Blocking Delay
void TIMER2_Delay_ms(uint16_t ms)
{
uint32_t start = TIMER2_GetMillis();
// Wait until required milliseconds have passed
while((TIMER2_GetMillis() - start) < ms);
}
// For reference
/*void TIMER2_Delay_ms(uint16_t ms)
{
// Stop timer if running
TIM2->CR1 &= ~TIM_CR1_CEN;
// Set auto-reload value
TIM2->ARR = (uint16_t) (ms - 1) * 10;
// Reset counter
TIM2->CNT = 0;
// Start timer
TIM2->CR1 |= TIM_CR1_CEN;
// Wait until counter reaches ARR
while(!(TIM2->SR & TIM_SR_UIF));
// Clear update flag
TIM2->SR &= ~TIM_SR_UIF;
// Stop timer
TIM2->CR1 &= ~TIM_CR1_CEN;
}*/