On atmega2560 (STK600 board), I am using Timer0 which is 8-bit timer. I want to generate an overflow every 4ms…how do I set the timer for 4ms? (the clock speed is 8MHz, I am aware of setting up a timer by diving (clock speed)/(prescaler) and when the counter resets, it generates an overflow interrupt. But not sure about setting for 4ms!
Secondly, once the timer overflows and generates an OVERFlOW interrupt, calculate 1 second..How to do that?
Thanks in advance!
4ms won’t be possible with the OVERFLOW interrupt:
F_CPU = 8,000,000hz
F_OVERFLOW = 1/0.004s = 250hz
CYCLES_PER_OVERFLOW = F_CPU / F_OVERFLOW = 32,000, i.e.: An overflow should occur each 32,000 CPU clock cycles
CYCLES_PER_TIMER_TICK = 32,000 / 256 = 125 = prescaler value
125 is not available as prescaler, but you can use 128 if that’s close enough for your purpose (4.096ms).
If not, you can consider to use a timer compare interrupt instead of the overflow int. – Or change F_CPU…
Once you have your interrupt each 4ms, you can increment a global variable on each interrupt and each time the variable’s value reaches 250, another second has passed and the variable can be re-set to 0 to count towards the next second.