Debian Codegraph @

kpy/mh-timer2.c

raw symbols SCIP
1 /*
2 mh-timer.c -- Advanced functions using Timer/Counter
3 Author : Ajith Kumar, Inter-University Accelerator Centre, New Delhi.
4 License : GNU GPL version 3 or later
5 Date : 23-Oct-2013
6 */
7
8 #include <avr/io.h>
9 #include <avr/interrupt.h>
10
11 //------------------- Frequency measurement ----------------------------
12
13 #define MTIME 250 // We count 100 on TC0
14
15 uint32_t measure_freq(void)
16 {
17 DDRB &= ~(1 << PB1); // Timer/Counter1 clock in T1 (PB1) as input
18 TCCR0 = (1 << CS02) |(1 << CS00); // Normal mode , CPU Clock / 1024
19 TIFR |= (1 << OCF0); // Clear OCF flag for T0
20 TCCR1B = (1 << CS12) | (1 << CS11) | (1 << CS10); // External clock on T1 pin
21 TCNT0 = 0; // Clear TCNT0
22 TCNT1 = 0; // Clear TCNT1
23 while(TCNT0 < MTIME) ;
24 TCCR1B = 0;
25 return TCNT1;
26 }
27
28 //----------------------- Time interval measurement--------------------------
29 volatile uint16_t HIWORD;
30 ISR(TIMER1_COMPA_vect) // TIMER1 Compare Match A Interrupt
31 {
32 TCNT1 = 0;
33 ++HIWORD;
34 PORTB = 1;
35 }
36
37 void start_timer()
38 {
39 /*
40 When TCNT1 reaches OCR1A, the ISR will run. It will clear TCNT1 and increment HIWORD.
41 The total time elapsed between start_timer and get_timer = HIWORD * 50000 + TCNT1
42 */
43 TCCR1B = (1 << CS11); // Normal mode, with 1MHz clock
44 HIWORD = 0;
45 OCR1A = 50000;
46 OCR1B = 0xffff;
47 TIMSK = (1 << OCIE1A); // Enable compare match interrupt
48 TIFR = (1 << OCF1A);
49 TCNT1 = 0;
50 sei();
51 }
52
53 uint32_t read_timer()
54 {
55 uint32_t x;
56
57 TCCR1B = 0; // stop TC1 clock
58 x = HIWORD * 50000 + TCNT1;
59 cli();
60 return x;
61 }
62