//Timer interrupt:
#include <avr/io.h> //for timer2 interrupt to read buttons
#include <avr/interrupt.h> //for timer2 interrupt to read buttons
const byte timer2Match=249; //249 = period of 1.000 ms @prescaler 64, clock 16 MHz
volatile word counter=0;
word counterTop=300-1;
volatile bool ledOn=LOW;
//ISR(TIMER2_OVF_vect) {
ISR(TIMER2_COMPA_vect) { //called once every 1.000 ms
counter++;
if (counter==1000) counter=0;
if (counter==0) ledOn=HIGH;
if (counter==counterTop) ledOn=LOW;
digitalWrite(LED_BUILTIN,ledOn); //works well with counterTop=0
}
void setup() {
Serial.begin(9600);
pinMode(LED_BUILTIN,OUTPUT);
//Setup timer2 interrupt for buttons:
cli(); //disable interrupts
TCCR2A=0; TCCR2B=0; //reset control registers A and B
TCNT2=0; //initialize counter value to 0
OCR2A=timer2Match; //set compare match register
TCCR2A=1<<WGM21; //set mode to CTC
TCCR2B=1<<CS22; //set prescaler to 64
TIMSK2=1<<OCIE2A; //enable timer compare interrupt
//TIMSK2=1<<TOIE2; //timer2 overflow interrupt enable
sei(); //enable interrupts
}
void loop() {
while (Serial.available() > 0) {
counterTop = Serial.parseInt();
}
unsigned int counterCopy;
cli();
counterCopy=counter;
sei();
Serial.print("counter: ");
Serial.print(counterCopy);
Serial.print(", counterTop: ");
Serial.println(counterTop);
delay(100);
}