-
Notifications
You must be signed in to change notification settings - Fork 13
/
timer.c
executable file
·66 lines (54 loc) · 1.76 KB
/
timer.c
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
/*
* EGG Electric Unicycle firmware
*
* Copyright (C) Casainho, 2015, 2106.
*
* Released under the GPL License, Version 3
*/
#include "stm32f10x.h"
#include "stm32f10x_tim.h"
#include "stm32f10x_rcc.h"
#include "main.h"
unsigned int overflow_counter = 0;
unsigned int micros (void)
{
return ((TIM_GetCounter (TIM2)) + (overflow_counter * 65536));
}
void micros_reset (void)
{
TIM_SetCounter (TIM2, 0);
overflow_counter = 0;
}
// Used for implementation of micros()
// This interrupt fire after each TIM2 overflow, 65536us
void TIM2_IRQHandler (void)
{
overflow_counter++;
/* Clear TIMx TIM_IT_Update pending interrupt bit */
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
}
void TIM2_init(void)
{
// enable TIMx clock
RCC_APB1PeriphClockCmd (RCC_APB1Periph_TIM2, ENABLE);
// reset TIMx
TIM_DeInit (TIM2);
/* Time base configuration */
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructure.TIM_Period = 65535;
TIM_TimeBaseStructure.TIM_Prescaler = (72 - 1); // 72MHz clock (PCLK1), 72MHz/72 = 1MHz --> 1us each increment of the counter/timer
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit (TIM2, &TIM_TimeBaseStructure);
/* Enable the TIMx global Interrupt */
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = TIM2_PRIORITY;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init (&NVIC_InitStructure);
/* TIMx TIM_IT_Update enable */
TIM_ITConfig (TIM2, TIM_IT_Update, ENABLE);
/* TIM2 counter enable */
TIM_Cmd (TIM2, ENABLE);
}