-
Notifications
You must be signed in to change notification settings - Fork 0
/
timing.cpp
69 lines (57 loc) · 1.68 KB
/
timing.cpp
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
/*
The millis() function known from Arduino
Calling millis() will return the milliseconds since the program started
Tested on atmega328p
Using content from http://www.adnbr.co.uk/articles/counting-milliseconds
Author: Monoclecat, https://github.com/monoclecat/avr-millis-function
REMEMBER: Add sei(); after init_millis() to enable global interrupts!
*/
#include <avr/io.h>
#include <util/atomic.h>
#include <avr/interrupt.h>
#include "timing.h"
namespace timing
{
namespace
{
volatile unsigned long timer1_millis;
ISR(TIMER1_COMPA_vect)
{
timer1_millis++;
}
}
void init(void)
{
unsigned long ctc_match_overflow;
ctc_match_overflow = ((F_CPU / 1000) / 8); //when timer1 is this value, 1ms has passed
// (Set timer to clear when matching ctc_match_overflow) | (Set clock divisor to 8)
TCCR1B |= (1 << WGM12) | (1 << CS11);
// high byte first, then low byte
OCR1AH = (ctc_match_overflow >> 8);
OCR1AL = ctc_match_overflow;
// Enable the compare match interrupt
TIMSK1 |= (1 << OCIE1A);
}
unsigned long millis (void)
{
unsigned long millis_return;
// Ensure this cannot be disrupted
ATOMIC_BLOCK(ATOMIC_FORCEON)
{
millis_return = timer1_millis;
}
return millis_return;
}
void delay_us(uint16_t us)
{
for (uint16_t t = 0; t < us; t++)
{
#if F_CPU <= 20000000 && F_CPU > 10000000
__asm__ __volatile__ ("nop");
__asm__ __volatile__ ("nop");
#else
__asm__ __volatile__ ("nop");
#endif
}
}
}