Hi
To understand the timer usage I created a simple circuit, and a basic code. The circuit is two leds, one on output 9, and the other is on output 10.
The code is try to use timer2, and the two compare registers in CTC mode.
Here is the code:
#define ledPin 9
void setup()
{
pinMode(ledPin, OUTPUT);
pinMode(ledPin+1, OUTPUT);
digitalWrite(ledPin,LOW);
digitalWrite(ledPin+1,LOW);
// initialize Timer2
noInterrupts(); // disable all interrupts
TCCR2A = 0;
TCCR2B = 0;
TCNT2 = 0;
OCR2A = 250; // compare match register A
OCR2B = 250; // compare match register B
TCCR2B |= (1 << WGM22); // CTC mode
TCCR2B |= (1 << CS22) | (1 << CS21) | (1 << CS20);// 1024 prescaler
TCCR2A |= (1 << WGM22); // CTC mode
TCCR2A |= (1 << CS22) | (1 << CS21) | (1 << CS20);// 1024 prescaler
TIMSK2 |= (1 << OCIE2B | 1 << OCIE2A); // enable timer compare interrupt
interrupts(); // enable all interrupts
}
ISR(TIMER2_COMPA_vect) // timer compare interrupt service routine
{
digitalWrite(ledPin, digitalRead(ledPin) ^ 1); // toggle LED pin
}
ISR(TIMER2_COMPB_vect) // timer compare interrupt service routine
{
digitalWrite(ledPin+1, digitalRead(ledPin+1) ^ 1); // toggle LED pin
}
void loop()
{
// digitalWrite(ledPin+1, digitalRead(ledPin) ^ 1); // toggle LED pin
}
I recognized, that when I set OCR2A lower than OCR2B, only led on output 9 blinks. Otherwise both led blinks, but depending on the value of OCR2B the phase of the two signals differ, and the frequency is determined by OCR2A.
Is it normal, or I did something wrong?