In this tutorial, I will make tutorial for making millis() function that will return number of millisecond since AVR microcontrollers began executing program. This function is like millis() function on Arduino. I will use ATmega16 and CodeVisionAVR for this tutorial. First, you have to make a variable that will hold the value of millisecond. I declared this variable as volatile because the value of this variable will be changed inside ISR.
// Store value of millisecond since uC started volatile unsigned long millis_value;
Next, Setup timer 0 (or another timer if you wish) to generate interrupt every 1 ms. I am using timer 0 on CTC mode to count up from 0 to the value of OCR0 register. The prescaler that I use is 64 with 16 MHz CPU clock. To calculate the OCR0 register for 1ms compare match, we can use this formula OCRx = ((T x Fcpu) / N) - 1. Where T is the desired compare match value in second (1ms = 0.001s), Fcpu in Hz is 16,000,000 and N is prescaler (64). The OCR0 value will be 0xF9. To generate code for this settings we will use CodeWizardAVR. This is the settings for timer 0: