-
Notifications
You must be signed in to change notification settings - Fork 0
/
millis.c
76 lines (63 loc) · 1.3 KB
/
millis.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
67
68
69
70
71
72
73
74
75
76
/*********************************
millis.c - sample Arduino millis()
on an ATTiny85 (use timer0 overflow
interrupt do to it)
Code in public domain
**********************************/
#define F_CPU 8000000UL
#include <avr/io.h>
#include <inttypes.h>
#include <avr/interrupt.h>
/* prototypes */
void setup(void);
void loop(void);
int main(void);
/* some vars */
uint64_t _millis = 0;
uint16_t _1000us = 0;
uint64_t old_millis = 0;
/* interrupts routines */
// timer overflow occur every 0.256 ms
ISR(TIM0_OVF_vect) {
_1000us += 256;
while (_1000us > 1000) {
_millis++;
_1000us -= 1000;
}
}
// safe access to millis counter
uint64_t millis() {
uint64_t m;
cli();
m = _millis;
sei();
return m;
}
void setup(void) {
// LED IO
DDRB |= _BV(PB3); // set LED pin as output
PORTB |= _BV(PB3); // turn the LED on
/* interrup setup */
// prescale timer0 to 1/8th the clock rate
// overflow timer0 every 0.256 ms
TCCR0B |= (1<<CS01);
// enable timer overflow interrupt
TIMSK |= 1<<TOIE0;
// Enable global interrupts
sei();
}
void loop(void) {
// every 1000ms toggle LED
if ((millis() - old_millis) > 100) {
// Toggle Port B pin 3 output state
PORTB ^= 1<<PB3;
old_millis = millis();
}
}
// Arduino like
int main(void) {
setup();
for(;;) {
loop();
}
};