Rev Author Line No. Line
3461 miho 1 // timer_demo1.c
2 // -------------
3 //
4 // Example file for ATmega88 (and similar AVR chips) demonstrating how to use
5 // timer interrupt just to blink by LED.
6 //
7 // The program uses TIMER1 to generate interrupts and the interrupt routine
8 // toogles the LED state. Connect LED to ground with apropriate serial resistor
9 // (value about 330 OHM).
10 //
11 // (c) miho 2014 http://www.mlab.cz
12 //
13 // History
14 // 2014 01 29 - First demo
15  
16  
17 // System Configuration
18 #define F_CPU 4000000 // Do not forget to set FUSEs to external XTAL osc with DIV/8 off and connect xtal
19  
20  
21 // LED Ports Configuration
22 #define LED_S_PORT C
23 #define LED_S_PIN 4
24 #define LED_M_PORT C
25 #define LED_M_PIN 5
26  
27  
28 // -------------- DO NOT EDIT BELOW THIS LINE --------------
29  
30  
31 // Library Headers
32 #include <avr/interrupt.h>
33  
34  
35 // Comaptibility ATmega8 / ATmega88
36 #ifndef TIMSK
37 #define TIMSK TIMSK1
38 #endif
39  
40  
41 // Macro for Port (enables to easily define IO signals)
42 #define GLUE(A,B) A##B
43 #define DDR(PORT_LETTER) GLUE(DDR, PORT_LETTER) // Makes DDRC from DDR(C)
44 #define PORT(PORT_LETTER) GLUE(PORT,PORT_LETTER) // Makes PORTC from PORT(C)
45 #define PIN(PORT_LETTER) GLUE(PIN, PORT_LETTER) // Makes PINC from PIN(C)
46  
47  
48 // Global Variable
49 volatile int Seconds;
50  
51 // Interrupt Routine for TIMER1 Output Compare A
52 ISR(TIMER1_COMPA_vect)
53 {
54 // LED on/off
55 PORT(LED_S_PORT) ^= (1<<LED_S_PIN);
56 if (Seconds<59)
57 {
58 Seconds++;
59 }
60 else
61 {
62 Seconds=0;
63 // Toogle Minute LED
64 PORT(LED_M_PORT) ^= (1<<LED_M_PIN);
65 }
66 }
67  
68  
69 // Main
70 int main()
71 {
72 // Enable LED Output
73 DDR(LED_S_PORT) |= (1<<LED_S_PIN);
74 DDR(LED_M_PORT) |= (1<<LED_M_PIN);
75  
76 // Set MAX value for Timer1
77 OCR1A = F_CPU/256/2-1; // 1/2s
78  
79 // Set Timer1 to CTC with presacaller 1/256
80 // CTC Mmode counts from 0 to value stored in OCR1A
81 // and generates interrupt every time it goes back to 0
82 // CS12 CS11 CS10 Prescaller
83 // 0 0 1 clkI/O/1 (No prescaling)
84 // 0 1 0 clkI/O/8 (From prescaler)
85 // 0 1 1 clkI/O/64 (From prescaler)
86 // 1 0 0 clkI/O/256 (From prescaler)
87 // 1 0 1 clkI/O/1024 (From prescaler)
88 TCCR1B |= (1<<CS12) | (1<<WGM12);
89  
90 // Enable Interrupt for Timer1 OCRA
91 TIMSK |= (1<<OCIE1A);
92  
93 // Enable Global (CPU) Interrupt
94 sei();
95  
96 // Main Loop
97 for(;;)
98 {
99 // Do any job here
100 }
101  
102 return 0;
103 }