When I run following code, the on board LED (Arduino UNO) changes its state every second (one second on, one second off). If I change timing (e.g. 34286 for 2Hz) and upload the code again, the led stays in "1 second mode". What am I doing wrong?
Thank you in advance for your help.
I have no experience at all with the timer so far, but my guess is that you are loading the count into the timer itself once, rather than setting its pre-load register, so in fact it simply loops at 65536 every time.
That said, I have to wonder why you want to use a timer interrupt to blink a LED. "Just because", I presume.
I added Direct Port Manipulation, which you can learn along the way!
void setup()
{
DDRB |= B00100000; // set pin13 to output without affecting other pins
// above is identical to pinMode(LEDPIN, OUTPUT); using Direct Port Manipulation
cli();
TCCR1A = 0;
TCCR1B = 0;
OCR1A = 15624; // = (target time / timer resolution) - 1 or 1 / 6.4e-5 - 1 = 15624
//OCR1A = 15624>>1; // divide by two >>EDIT added this line<<
TCCR1B |= (1 << WGM12);// CTC mode on
TCCR1B |= (1 << CS10);// Set CS10 and CS12 bits for 1024 prescaler:
TCCR1B |= (1 << CS12);
TIMSK1 |= (1 << OCIE1A);// timer compare intrupt
sei();
}
void loop()
{
// do something here unaffected by your blinking led
}
ISR(TIMER1_COMPA_vect)
{
PORTB ^= B00100000;// toggles bit which affects pin13
}