Project

General

Profile

Statistics
| Revision:

root / branches / charging_station / code / projects / recharging / charging_station / time.c @ 85

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

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

    
19
/*
20
delay_ms
21

22
delays for ms milliseconds
23

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

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

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

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

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

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

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

61
uses TIMER0 on asynchronous mode
62
*/
63

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

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

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

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