In this tutorial, I will show you how to make a delay function with timer 0 on Arduino Uno. The delay function will generate a delay of 10ms. The settings that I used for this timer is normal mode. In this mode, timer will count from a loaded value up to timer overflow value. Loaded value for timer 0 (TCNT0) can be calculated with this formula TCNT0 = (1 + 0xFF) - (T * CLK)/N. T is the period of this timer will be overflow (0.01s), N is the prescaler, and CLK is the crystal frequency (16 MHz). The prescaler that I use is 1024. Therefore the TCNT0 value is (1 + 0xFF) - (0.01s * 16000000Hz)/1024 = 100 = 0x64.
This is the function for generating 10ms delay using timer 0:
// Delay 10ms with timer 0 normal mode, pooling
void T0Delay()
{
// Load initial count value
TCNT0 = 0x64;
// Init timer mode and prescaler
TCCR0A = 0;
TCCR0B = (1 << CS02) | (1 << CS00);
// Wait until timer 0 overflow
while ((TIFR0 & (1 << TOV0)) == 0);
// Stop timer 0
TCCR0B = 0;
// Clear time 0 overflow flag
TIFR0 = (1 << TOV0);
}
In this function there is a while loop for waiting until timer 0 is overflow. Using while loop for waiting something happen is usually called pooling method. When use pooling method, CPU is not do anything and can't do other task, just wait until something happen.