In this post, will describe how to use an interrupt event of timer2 using nano board. If you want a process that works in the background and separated from the function loop (), you can use timer2. Timer2 can be set as a timer with overflow mode. When timer2 overflow, certain vector address to be executed. In arduino, vector address to timer2 with overflow mode is TIMER2_OVF_vect.
Initialization of timer2
First you must initialize timer2 as timer overflow mode. To initialize timer2 use the following code:
The code to initialize timer2 can be explained as follows:
- At line 10 aims to disable timer2, so that does not work.
- At line 12 aims to set timer2 to become overflow during 10ms.
- At line 13 aims to clear flag interrupt of timer2. Each 10ms this flag will be set and will execute address of interrupt: TIMER2_OVF_vect
- At line 14 aims to enable timer2 interrupt as overflow mode.
- At line 15 aims to set wave generator normal of timer2
- AT line 16 aims to set prescaler of timer2 to 1024
How to calculate time of overflow interrupt
The equation is:
t = (1/F) * 1024 * (255 – R) * 1000 mS
F is frequency of microcontroler in Hz
R is value of TCNT2 register
For example timer overflow will generate every 10mS (t) dan F is 16000000MHz.
10 = (1/16000000) * 1024 * (255-R) * 1000
(255 – R) = (10 * 16000000)/(1024 * 1000)
(255 – R) = 156.25
R = 255 – 156.25 = ~98 (decimal)
Routine of timer2 overflow interrupt
If the register is set to 98, the routine of timer2 overflow interrupt will be executed every 10ms. Address of vector interrupt is TIMER2_OVF_vect.
In this routine thing to do is to set TCNT2 = 98, so the routine is executed again every 10ms. Additionally TIFR2 set to 00, TIFR2 = 00.
Next, you can add the code in this routine, such as a counter or other variables. Make the code as short as possible, try the code created only manipulate variables.
Codes above can be explained as follows:
- Line 21 and 22, set timer2 counter to 10ms and reset timer2 interrupt flag.
- Line 24 to 28, change the logic of variable flag_led as toggle every 500ms, using variable flag_500ms as counter to get again time of 500ms.
- Line 24, check the flag_500ms whether zero. If zero is reached, flag_led will be invert (line 26). Next on line 27 refresh flag_500ms become value of 50 as time counter of 500ms.
Setup() and Loop() functions
The code of setup() and loop() functions be explained as follows:
- On setup() function, line 35 configure D2 to D9 as digital output. Line 36 setup the variable of flag_500ms = 50 for 500ms counter based on 10ms. Line 37 init the timer2 as timer overflow interrupt for time of 10ms.
- On loop() function, line 42 and 43 set D2 to D9 with logic 0/1 based on flag_led variable.
Last updated byat .