In my another tutorial Make Delay with Timer 0 (CTC Mode, Pooling), I have made a delay function using timer 0 in normal mode. This time I will modify the timer mode to use CTC mode. In normal mode, timer count will count up from loaded value to overflow value. In CTC mode, timer count will count up from zero to compare match value. Compare match value is stored on compare match register (OCRx). To calculate compare match value for delay 10ms, we can use this formula OCR0A = (0.01s * 16000000Hz)/1024 = 156 = 0x9C.
After we get OCR0A value, we can use that in delay function:
// Delay 10ms with timer 0 CTC mode, pooling
void T0Delay()
{
// Load initial count value
TCNT0 = 0;
// Load compare match value
OCR0A = 0x9C;
// Init timer mode and prescaler
TCCR0A = (1 << WGM01);
TCCR0B = (1 << CS02) | ( 1 << CS00);
// Wait until timer 0 compare match
while ((TIFR0 & (1 << OCF0A)) == 0);
// Stop timer 0
TCCR0B = 0;
// Clear compare math flag
TIFR0 = (1 << OCF0A);
}








