Counter/timer 0 - CTC mode

Hi every one,

This time, I am trying to use the timer/counter 0 in CTC mode using the following code :

// Set PD6 as output
DDRD |= (1<<PD6);

//Set Initial Timer value
TCNT0=0;

//Place TOP timer value to Output compare register A
OCR0A=111;

// Set CTC mode (Clear Timer on Compare Match) → mode 2 (010)
// and make toggle PD6/OC0A pin on compare match (debugging purpose)
TCCR0A &=~(1<<COM0A1);
TCCR0A |=(1<<COM0A0)|(1<<WGM01);
TCCR0A &=~(1<<WGM00);
TCCR0B &=~(1<<WGM02);

// Set prescaler 8 and start timer (010)
// Frequency = 16 000 000 / 8 / 112 approx.: 17 857 hz)
TCCR0B &=~(1<<CS02);
TCCR0B |=(1<<CS01);
TCCR0B &=~(1<<CS00);

The oscilloscope shows a signal on pin PD6 with a very low frequency (approx.: 50 hz) :frowning:

I want to produce a timer frequency of 17 857 hz.

What is wrong or missing with ma code ?

Thank you for your help.

I’m not sure what is wrong with the posted code, but if you initialized the TCCR0A and TCCR0B registers to 0 and then just set the bits you want and don’t try all the clearing of bits with &=~ you get what you want. I’ve looked at the final register settings with both approaches and can’t see any difference so I don’t know the root cause.

void setup() {
  // Set PD6 as output
    DDRD |= (1<<PD6);
    
    TCCR0A = 0;
    TCCR0B = 0;
  
    //Set Initial Timer value
    TCNT0=0;
    
    //Place TOP timer value to Output compare register A 
    OCR0A=111;

    // Set CTC mode (Clear Timer on Compare Match) --> mode 2 (010)
    // and make toggle PD6/OC0A pin on compare match (debugging purpose)
   // TCCR0A &=~(1<<COM0A1);
    TCCR0A |=(1<<COM0A0)|(1<<WGM01);
    //TCCR0A &=~(1<<WGM00);
    //TCCR0B &=~(1<<WGM02);

    // Set prescaler 8 and start timer (010)
    // Frequency = 16 000 000 / 8 / 112 approx.: 17 857 hz)
   // TCCR0B &=~(1<<CS02);
    TCCR0B |=(1<<CS01);
   // TCCR0B &=~(1<<CS00);
}

void loop() {
}

Your code works perfectly ! :)

I wouldn't have found the solution to that problem by myself.

Once again, thank you for your help !

It is very appreciated !