led2.c


1
#include <avr/io.h>
2
#include <stdio.h>
3
#include <avr/interrupt.h>
4
////////////////////////////////////////////////////////////////////////////////////////////
5
#ifndef F_CPU
6
#define F_CPU 8000000UL
7
#endif
8
////////////////////////////////////////////////////////////////////////////////////////////
9
#define  LED_DDR_REG   DDRB
10
#define LED_PORT_REG  PORTB
11
#define LED_PIN      0
12
13
#define LED_ON      LED_PORT_REG |=  (1 << LED_PIN);
14
#define LED_OFF      LED_PORT_REG &= ~(1 << LED_PIN);
15
16
17
/*****************AB HIER KOMMENTIEREN******************************/
18
////////////////////////////////////////////////////////////////////////////////////////////
19
// reload value(2^16-(t*fosz/1024)): 2^16-(0,0001 * 8000000/1024)
20
#define  REL_H   0xFF
21
#define  REL_L   0xFF 
22
////////////////////////////////////////////////////////////////////////////////////////////
23
volatile unsigned int   cnt_1 = 0;
24
volatile unsigned int   cnt_2 = 0;
25
volatile unsigned char   limit = 0;
26
volatile unsigned char   direction = 1;
27
28
#define  FADE_DURATION  500
29
////////////////////////////////////////////////////////////////////////////////////////////
30
ISR (TIMER1_OVF_vect) { 
31
  
32
  TCNT1H = REL_H;
33
  TCNT1L = REL_L; 
34
35
  
36
  if (cnt_1 == 100) {
37
    cnt_1 = 0;
38
  }
39
  if (cnt_1 == 0) {
40
    LED_ON;
41
  }
42
43
  if (cnt_2 == FADE_DURATION) { 
44
    cnt_2 = 0; 
45
  }
46
  cnt_2++;  
47
48
  if (cnt_2 == FADE_DURATION) {
49
50
    if (direction == 1) {
51
      if (limit < 100) {
52
        limit++; 
53
      }
54
      else {
55
        direction = 0;
56
      }
57
    }
58
59
    if (direction == 0) {
60
      if (limit > 1) { 
61
        limit--; 
62
      }
63
      else {
64
        direction = 1;
65
      }
66
    }
67
  }
68
69
  if (cnt_1 == limit) {
70
    LED_OFF;
71
  }
72
  cnt_1++;
73
}
74
////////////////////////////////////////////////////////////////////////////////////////////
75
void init_led_hw (void) {
76
  LED_DDR_REG   |= (1 << LED_PIN);  // set led pin as output
77
}
78
////////////////////////////////////////////////////////////////////////////////////////////
79
void timer1_init(void) {
80
81
  TCCR1A    = 0;            // normal timer mode
82
  TCCR1B   |= (1<<CS10)|(1<<CS12);    // set prescaler 
83
84
  TCNT1H = REL_H;  
85
  TCNT1L = REL_L;
86
    
87
  TIMSK1   |= (1<<TOIE1);
88
}
89
90
/**************************KOMMENTIERUNG BIS HIER************************/
91
////////////////////////////////////////////////////////////////////////////////////////////
92
int main (void) {
93
  
94
  init_led_hw();
95
  timer1_init();
96
  sei();
97
98
  do {} while (1);
99
}