root / trunk / code / projects / colonet / robot / wl_network_colonet / time.c @ 481
History | View | Annotate | Download (1.81 KB)
1 | 13 | emarinel | /*
|
---|---|---|---|
2 | time.c
|
||
3 | anything that requires a delay
|
||
4 | mostly delay_ms
|
||
5 | |||
6 | author: Robotics Club, Colony Project
|
||
7 | |||
8 | */
|
||
9 | #include <avr/interrupt.h> |
||
10 | #include <avr/signal.h> |
||
11 | #include <avr/delay.h> |
||
12 | #include "time.h" |
||
13 | //#include "help.h"
|
||
14 | #include "serial.h" |
||
15 | |||
16 | |||
17 | static volatile int _rtc_val = 0; |
||
18 | static void (*_rtc_f)(void) = 0; |
||
19 | |||
20 | /*
|
||
21 | delay_ms
|
||
22 | |||
23 | delays for ms milliseconds
|
||
24 | |||
25 | accuracy is unknown (off by tens of nanoseconds every 15 ms)
|
||
26 | */
|
||
27 | void delay_ms(int ms) |
||
28 | { |
||
29 | for(; ms > 15; ms-=15) |
||
30 | _delay_ms(15);
|
||
31 | _delay_ms(ms); |
||
32 | } |
||
33 | |||
34 | void pause_ms(int ms) |
||
35 | { |
||
36 | delay_ms(ms); |
||
37 | } |
||
38 | |||
39 | void pause(int ms) |
||
40 | { |
||
41 | delay_ms(ms); |
||
42 | } |
||
43 | |||
44 | void sleep_ms(int ms) |
||
45 | { |
||
46 | delay_ms(ms); |
||
47 | } |
||
48 | |||
49 | void sleep(int ms) |
||
50 | { |
||
51 | delay_ms(ms); |
||
52 | } |
||
53 | |||
54 | /*
|
||
55 | void rtc_init(void)
|
||
56 | call this function to start the real time timer
|
||
57 | use rtc() to get the time value and rtc_resest() to reset
|
||
58 | |||
59 | requires global interrupts to be enabled for proper use
|
||
60 | (I bit of SREG register should be set)
|
||
61 | |||
62 | uses TIMER0 on asynchronous mode
|
||
63 | */
|
||
64 | |||
65 | void rtc_init(int prescale_opt, unsigned char ocr_val, void (*rtc_func)(void)){ |
||
66 | int mask = _BV(TCN0UB) + _BV(OCR0UB) + _BV(TCR0UB);
|
||
67 | char tmp;
|
||
68 | |||
69 | TIMSK &= ~(_BV(OCIE0) + _BV(TOIE0)); //1. disable interrupts
|
||
70 | ASSR |= _BV(AS0); //2. selecting clock source (external)
|
||
71 | |||
72 | //3. writing new values to TCCR, TCNT, OCR
|
||
73 | TCNT0 = 0;
|
||
74 | OCR0 = ocr_val; |
||
75 | TCCR0 = (0x01 << 3) + (prescale_opt & 0x07); //setting CTC mode, prescaler is lowest 3 bits |
||
76 | |||
77 | //4. waiting for busy bits to clear
|
||
78 | tmp = ASSR; |
||
79 | while( tmp & mask ){
|
||
80 | tmp = ASSR; |
||
81 | } |
||
82 | |||
83 | TIFR &= ~(_BV(OCF0) + _BV(TOV0)); //5. clearing the interrupt flags
|
||
84 | TIMSK |= _BV(OCIE0); // + _BV(TOIE0); //6. enabling interrupts
|
||
85 | |||
86 | _rtc_f = rtc_func; |
||
87 | } |
||
88 | |||
89 | int rtc(void){ |
||
90 | return _rtc_val;
|
||
91 | } |
||
92 | |||
93 | void rtc_reset(void){ |
||
94 | _rtc_val = 0;
|
||
95 | } |
||
96 | |||
97 | SIGNAL (SIG_OUTPUT_COMPARE0){ |
||
98 | _rtc_val++; |
||
99 | |||
100 | if(_rtc_f != 0) |
||
101 | _rtc_f(); |
||
102 | } |