Go Down

Topic: LED flashing with timer interrupt (Read 5792 times) previous topic - next topic

droeminator

Oct 31, 2014, 10:06 pm Last Edit: Oct 31, 2014, 10:13 pm by droeminator
Hi there

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.

Roman



Code: [Select]
#define ledPin 13

void setup()
{
 pinMode(ledPin, OUTPUT);

 // initialize timer1
 noInterrupts();    // disable all interrupts
 TCCR1A = 0;
 TCCR1B = 0;

 TCNT1 = 3036;    // preload timer 65536-16MHz/256/1Hz
 TCCR1B |= (1 << CS12);    // 256 prescaler
 TIMSK1 |= (1 << TOIE1);   // enable timer overflow interrupt
 interrupts();    // enable all interrupts
 
 Serial.begin(9600);
}



ISR(TIMER1_OVF_vect)
{
 digitalWrite(ledPin, digitalRead(ledPin)^1);
}



void loop()
{

}

Paul__B

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.

BulldogLowell

#2
Nov 01, 2014, 03:23 pm Last Edit: Nov 01, 2014, 06:16 pm by BulldogLowell
try it using CTC mode...

I added Direct Port Manipulation, which you can learn along the way!

Code: [Select]
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
}

Go Up