//Arduino timer CTC interrupt example
//
//avr-libc library includes
//#include <arduino.h>
//#include <avr/io.h>
//include <avr/interrupt.h>
#define LEDPIN 13
#define LEDPIN2 12
#define LEDPIN3 11
void setup()
{
Serial.begin(57600);
pinMode(LEDPIN, OUTPUT);
pinMode(LEDPIN2, OUTPUT);
pinMode(LEDPIN3, OUTPUT);
//initialize Timer1
cli(); //disable global interrupts
TCCR1A = 0; //set entire TCCR1A register to 0
TCCR1B = 0; //set entire TCCR1B register to 0
// Annahme: Prozessorfrequenz 1MHz
// Zähler wird all 1us um 1 erhöht
// 1s -> auf 1,000,000 zählen.
// 16 Bit Zahlen -> maximal auf 65,536 zählen.
// Prescaler: statt jeden Zyklus (1us) um eins erhöhen
// Nur jeden n. Zyklus um 1 erhöhen
// Prescaler = 1024 -> ~jede 1ms (alle 1024us)
// um eins weiter zählen
// Timer INterrupt wird ausgelöst wenn das Timerregister
// überläuft
// 1111 1111 1111 1110
// 1111 1111 1111 1111
// 0000 0000 0000 0000 -> Überlauf
// Wenn ich auf 500 zählen will
// (500us -> Prescaler, Starte bei 65036)
// Beispiel Code:
// Prescaler 1024, 15624~1s -> 15,998,976 zyklen pro sekunde
// Frequenz des Arduino: 16MHz
// 800*1024 = 819,200 /16 MHz~ 0,0512 s~50ms
//set compare match register to desired timer count:
OCR1A = 15; //15624 = 1s
//turn on CTC mode:
TCCR1B |= (1 << WGM12);
//set CS10 and CS12 bits for 1024 prescaler:
TCCR1B |= (1 << CS10);
TCCR1B |= (1 << CS12);
//enable timer compare interrupt:
TIMSK1 |= (1 << OCIE1A);
//enable global interrupts
sei();
}
void loop()
{
Serial.print("LED 1 is :" );
if(digitalRead(LEDPIN)==HIGH) {
Serial.println("On");
}
else {
Serial.println("Off");
}
Serial.print("LED 2 is :" );
if(digitalRead(LEDPIN2)==HIGH) {
Serial.println("On");
}
else {
Serial.println("Off");
}
Serial.print("LED 3 is :" );
if(digitalRead(LEDPIN3)==HIGH) {
Serial.println("On");
}
else {
Serial.println("Off");
}
delay(1);
}
ISR(TIMER1_COMPA_vect)
{
static int tick=0;
if(tick % 2 == 1){ //ungerade zahlen 1,3,5,7,9
digitalWrite(LEDPIN, !digitalRead(LEDPIN));
}
else if(tick % 4 == 2){ //2,6,10,
digitalWrite(LEDPIN2,!digitalRead(LEDPIN2));
}
else if(tick % 8 == 4){ //4,12,20,
digitalWrite(LEDPIN3,!digitalRead(LEDPIN3));
}
tick++;
}