Project

General

Profile

Statistics
| Revision:

root / trunk / code / projects / colonet / utilities / robot_wireless_relay / time.c @ 13

History | View | Annotate | Download (1.79 KB)

1
/*
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 <util/delay.h>
11
#include <time.h>
12
#include <help.h>
13
#include <serial.h>
14

    
15
static volatile int _rtc_val = 0;
16
static void (*_rtc_f)(void) = 0;
17

    
18
/*
19
delay_ms
20

21
delays for ms milliseconds
22

23
accuracy is unknown (off by tens of nanoseconds every 15 ms)
24
*/
25
void delay_ms(int ms) 
26
{
27
        for(; ms > 15; ms-=15)
28
                _delay_ms(15);
29
        _delay_ms(ms);
30
}
31

    
32
void pause_ms(int ms)
33
{
34
        delay_ms(ms);
35
}
36

    
37
void pause(int ms)
38
{
39
        delay_ms(ms);
40
}
41

    
42
void sleep_ms(int ms)
43
{
44
        delay_ms(ms);
45
}
46

    
47
void sleep(int ms)
48
{
49
        delay_ms(ms);
50
}
51

    
52
/*
53
void rtc_init(void)
54
call this function to start the real time timer
55
use rtc() to get the time value and rtc_resest() to reset
56

57
requires global interrupts to be enabled for proper use
58
(I bit of SREG register should be set)
59

60
uses TIMER0 on asynchronous mode
61
*/
62

    
63
void rtc_init(int prescale_opt, unsigned char ocr_val, void (*rtc_func)(void)){
64
        int mask = _BV(TCN0UB) + _BV(OCR0UB) + _BV(TCR0UB);
65
        char tmp;
66
        
67
        TIMSK &= ~(_BV(OCIE0) + _BV(TOIE0)); //1. disable interrupts
68
        ASSR |= _BV(AS0); //2. selecting clock source (external)
69
        
70
        //3. writing new values to TCCR, TCNT, OCR
71
        TCNT0 = 0;
72
        OCR0 = ocr_val;
73
        TCCR0 = (0x01 << 3) + (prescale_opt & 0x07); //setting CTC mode, prescaler is lowest 3 bits
74
        
75
        //4. waiting for busy bits to clear
76
        tmp = ASSR;
77
        while( tmp & mask ){
78
                tmp = ASSR;
79
        }
80
        
81
        TIFR &= ~(_BV(OCF0) + _BV(TOV0)); //5. clearing the interrupt flags
82
        TIMSK |= _BV(OCIE0); // + _BV(TOIE0); //6. enabling interrupts
83
        
84
        _rtc_f = rtc_func;
85
}
86

    
87
int rtc(void){
88
        return _rtc_val;
89
}
90

    
91
void rtc_reset(void){
92
        _rtc_val = 0;
93
}
94

    
95
SIGNAL (SIG_OUTPUT_COMPARE0){
96
        _rtc_val++;
97
        
98
        if(_rtc_f != 0)
99
                _rtc_f();
100
}