0% found this document useful (0 votes)
106 views

Advanced Coding Timers

The document discusses timers in Arduino coding. It defines timers as hardware counters that can measure time intervals and generate interrupts. The Arduino Uno and Mega boards contain multiple timers that can be configured using registers to select modes like overflow or output compare. Timers allow generating precise delays by counting clock cycles and can produce waveforms by comparing the counter to preset values. Practical applications include blinking LEDs, reading sensor inputs, and controlling servos with precise timing.

Uploaded by

Sab Bah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
106 views

Advanced Coding Timers

The document discusses timers in Arduino coding. It defines timers as hardware counters that can measure time intervals and generate interrupts. The Arduino Uno and Mega boards contain multiple timers that can be configured using registers to select modes like overflow or output compare. Timers allow generating precise delays by counting clock cycles and can produce waveforms by comparing the counter to preset values. Practical applications include blinking LEDs, reading sensor inputs, and controlling servos with precise timing.

Uploaded by

Sab Bah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

1

Advanced Arduino Coding


Timers

BY ENG. HOSSAM ARAFA


2
Outline
• What is a Timer?
• Timer Concepts
• Classification of the Timers
• ATmega Processor Interrupt Types
• Timer based Interrupts
• Timer Overflow
• Timer Registers
• Clock select and timer frequency
• Timer modes
• PWM and Timers
• Examples of Timer Interrupts
• How to adjust Arduino PWM Frequencies
• Practical Applications
• References
3
What is a timer?
• A timer, A.K.A. counter is a piece of hardware built in the Arduino controller. It is like a clock, and can be
used to measure time events.

• The timer can be programmed by some special registers. You can configure the prescaler for the timer, or
the mode of operation and many other things.

• The Arduino board is based on the Atmel AVR ATmega168 or the ATmega328. These chips are pin
compatible and only differ in the size of internal memory. Both have 3 timers, called Timer0, Timer1 and
Timer2. Timer0 and Timer2 are 8bit timer, where Timer1 is a 16bit timer.

• The most important difference between 8bit and 16bit timer is the timer resolution. 8bits means 256 values
(two to the power of 8) where 16bit means 65536 values (two to the power of 16) which is much higher
resolution.

• The Arduino Mega series is based on the Atmel AVR ATmega1280 or the ATmega2560. They are almost
identical to previous chips but only differs in memory size. These chips have 6 timers. First 3 timers (Timer 0,
Timer1 and Timer2) are identical to the ATmega168/328. Timer3, Timer4 and Timer5 are all 16bit timers,
similar to Timer1.

• All timers depends on the system clock of your Arduino system. Normally the system clock is 16MHz, but
the Arduino Pro 3/3V is 8Mhz, so be careful when writing your own timer functions.

• The timer hardware can be configured with some special timer registers. In the Arduino firmware, all timers
were configured to a 1kHz frequency and interrupts are generally enabled.
4
Timer Concepts
Since childhood, we have been coming across the following formula 1
Now suppose, we need to flash an LED every 1 ms. This implies that its frequency is 1/1ms = 1000 Hz. Now
let’s assume that we have an external crystal XTAL of 16 MHz. Hence, the CPU clock frequency is 16 MHz.
Now, as I said that the timer counts from 0 to TOP. For an 8-bit timer, it counts from 0 to 255 whereas for a
16-bit timer it counts from 0 to 65535. After that, they overflow. This value changes at every clock pulse.
Let’s say the timer’s value is zero now. To go from 0 to 1, it takes one clock pulse. To go from 1 to 2, it takes
another clock pulse. To go from 2 to 3, it takes one more clock pulse. And so on. For F_CPU = 16 MHz, time
period T = 1/16M = 62.5 ns. Thus for every transition (0 to 1, 1 to 2, etc.), it takes only 62.5 ns!
Now, as stated above, we need a delay of 1 ms. This maybe a very short delay, but for the microcontroller
which has a resolution of 62.5 ns, its quite a long delay! To get an idea of how long it takes, let’s calculate the
timer count from the following formula 2
Substitute Required Delay = 1 ms and Clock Time Period = 62.5 ns, and you get Timer Count = 16000. Can you
imagine that? The clock has already ticked 16000times to give a delay of only 1 ms! Now, to achieve this, we
definitely cannot use an 8-bit timer (as it has an upper limit of 255, after which it overflows). Hence, we use a
16-bit timer (which is capable of counting up to 65535) to achieve this delay.
Prescaler how do we actually reduce the frequency? This technique of frequency division is called prescaling.
We do not reduce the actual F_CPU. The actual F_CPU remains the same (at 16 MHz in this case). So basically,
we derive a frequency from it to run the timer. Thus, while doing so, we divide the frequency and use it.
There is a provision to do so in AVR by setting some bits.
Formula 1 Formula 2
5

Classification of the Timers


• Timer0: 8bit timer
In the Arduino world timer0 is been used for the software Sketch timer functions, like delay(),
millis() and micros(). If you change timer0 registers, this may influence the Arduino timer
function. So you should know what you are doing.
• Timer1: 16bit timer
In the Arduino world the Servo library uses timer1 on Arduino Uno (timer5 on Arduino Mega).
• Timer2: 8bit timer like timer0
In the Arduino world the tone() function uses timer2.
• Timer3, Timer4, Timer5: 16bit Timers
Timer 3,4,5 are only available on Arduino Mega boards.
6

ATmega Processor Interrupt Types


• External Interrupts
• Pin Change Interrupts
• Internal Interrupts
 Timer based Interrupts
 Hardware Interrupts
_____________________________________________________
• Timer based Interrupts
 Timer Overflow
 Clear Timer on Compare Match
 Timer1 Input Capture
7
Timer based Interrupts
A timer can generate different types of interrupts. The register and bit definitions can be
found in the processor data sheet ( Atmega328 or Atmega2560 ) and in the I/O definition
header file (iomx8.h for Arduino, iomxx0_1.h for Arduino Mega in the
hardware/tools/avr/include/avr folder). The suffix x stands for the timer number (0..5),
the suffix y stands for the output number (A,B,C), for example TIMSK1 (timer1 interrupt
mask register) or OCR2A (timer2 output compare register A).

Output Compare Interrupt Technique Overflow Interrupt Technique


8

Timer Overflow
Timer overflow means the timer has reached is limit value. When a timer overflow
interrupt occurs, the timer overflow bit TOVx will be set in the interrupt flag register
TIFRx. When the timer overflow interrupt enable bit TOIEx in the interrupt mask register
TIMSKx is set, the timer overflow interrupt service routine ISR(TIMERx_OVF_vect) will be
called.

Timer Overflow
Timer Registers 9
You can change the Timer behavior through the timer register. The most important timer registers are:
TCCRx - Timer/Counter Control Register. The prescaler can be configured here.
10
Cont. Timer Registers

• TCNTx - Timer/Counter Register. The actual timer value is stored here.


Cont. Timer Registers 11
• OCRx - Output Compare Register

The Output Compare Registers contain a 16-bit value that is continuously compared with
the counter value (TCNT1). A match can be used to generate an Output Compare
interrupt, or to generate a waveform output on the OC1x pin.
The Output Compare Registers are 16-bit in size. To ensure that both the high and low
bytes are written simultaneously when the CPU writes to these registers, the access is
performed using an 8-bit temporary High Byte Register (TEMP). This temporary register is
shared by all the other 16-bit registers.
12
Cont. Timer Registers
• ICRx - Input Capture Register (only for 16bit timer)

The Input Capture is updated with the counter (TCNT1) value each time an event occurs
on the ICP1 pin (or optionally on the Analog Comparator output for Timer/Counter1).
The Input Capture can be used for defining the counter TOP value.
The Input Capture Register is 16-bit in size. To ensure that both the high and low bytes
are read simultaneously when the CPU accesses these registers, the access is performed
using an 8-bit temporary High Byte Register (TEMP). This temporary register is shared by
all the other 16-bit registers.
13
Cont. Timer Registers
• TIMSKx - Timer/Counter Interrupt Mask Register. To enable/disable timer interrupts.

Bit 7, 6 – Reserved
Bit 5 – ICIE1: Timer/Counter1, Input Capture Interrupt Enable
Bit 4, 3 – Reserved
Bit 2 – OCIE1B: Timer/Counter1, Output Compare B Match Interrupt Enable
Bit 1 – OCIE1A: Timer/Counter1, Output Compare A Match Interrupt Enable
Bit 0 – TOIE1: Timer/Counter1, Overflow Interrupt Enable
14
Cont. Timer Registers
• TIFRx - Timer/Counter Interrupt Flag Register. Indicates a pending timer interrupt.

Bit 7, 6 – Reserved
Bit 5 – ICF1: Timer/Counter1, Input Capture Flag
Bit 4, 3 – Reserved
Bit 2 – OCF1B: Timer/Counter1, Output Compare B Match Flag
Bit 1 – OCF1A: Timer/Counter1, Output Compare A Match Flag
Bit 0 – TOV1: Timer/Counter1, Overflow Flag
Clock select and Timer Frequency 15
• Clock select and timer frequency
Different clock sources can be selected for each timer independently. To calculate the timer frequency (for example 2Hz
using timer1) you will need:
• CPU frequency 16Mhz for Arduino
• maximum timer counter value (256 for 8bit, 65536 for 16bit timer)
• Divide CPU frequency through the chosen prescaler (16000000 / 256 = 62500)
• Divide result through the desired frequency (62500 / 2Hz = 31250)
• Verify the result against the maximum timer counter value (31250 < 65536 success) if fail, choose bigger prescaler.

TCCRXB- 3 bits Control the prescaler Value


16
Timer Modes
• Timers can be configured in different modes. Timers can be configured in different modes.
17
Cont. Timer Modes
Normal Mode
In normal mode, TCNT1 counts up and triggers the Timer/Counter 1 Overflow interrupt when
it rolls over
The timer must be preloaded every time in the interrupt service routine.

Timer Overflow
Timer overflow means the timer has reached is limit value.
When a timer overflow interrupt occurs, the timer overflow
bit TOVx will be set in the interrupt flag register TIFRx. When
the timer overflow interrupt enable bit TOIEx in the interrupt
mask register TIMSKx is set, the timer overflow interrupt
service routine ISR(TIMERx_OVF_vect) will be called.

Normal Mode Technique


Cont. Timer Modes 18
CTC Mode (Clear timer on compare match)
- Output Compare Mode
The Output Compare mode is used to perform repeated timing. The value in TCNT1 (which is
counting up if not stopped by the prescaler select bits) is permanently compared to the value
in OCR1A. When these values are equal to each other, the Output Compare Interrupt Flag
(OCF in TIFR) is set and an ISR can be called. By setting the CTC1 bit in TCCR1B, the timer can
be automatically cleared upon compare match.

When a output compare match interrupt occurs, the


OCFxy flag will be set in the interrupt flag register
TIFRx . When the output compare interrupt enable bit
OCIExy in the interrupt mask register TIMSKx is set, the
output compare match interrupt service
ISR(TIMERx_COMPy_vect) routine will be called.

Output Compare Technique


Cont. Timer Modes 19
Input Capture Mode
The Input Capture Mode can be used to measure the time between two edges on the ICP pin
(Input Capture Pin). Some external circuits make pulses which can be used in just that way. Or
you can measure the rpm of a motor with it. You can either set it up to measure time
between rising or falling edges on the pin. So if you change this setting within the ISR you can
measure the length of a pulse. Combine these two methods and you have completely
analyzed a pulse. How it works?, Here's a flow chart of its basic functionality:

When a timer input capture interrupt


occurs, the input capture flag bit ICFx will
be set in the interrupt flag register TIFRx.
When the input capture interrupt enable bit
ICIEx in the interrupt mask register TIMSKx
is set, the timer input capture interrupt
service routine ISR(TIMERx_CAPT_vect) will
be called.

Input Capture Technique


20
Cont. Timer Modes
PWM Modes
Note: This part is taken from http://maxembedded.com/2011/08/avr-timers-pwm-mode-part-i/
• Fast PWM
• Phase Correct PWM
• Frequency and Phase Correct PWM

PWM Technique
Cont. Timer Modes 21
PWM Generation
The simplest way to generate a PWM signal is by comparing
the a predetermined waveform with a fixed voltage level as
shown in the Figure.
In the diagram shown above, we have a predetermined
waveform, sawtooth waveform. We compare this waveform
with a fixed DC level. It has three compare output modes of
operation:
Inverted Mode – In this mode, if the waveform value is
greater than the compare level, then the output is set high,
or else the output is low. This is represented in figure A
above.
Non-Inverted Mode – In this mode, the output is high
whenever the compare level is greater than the waveform
level and low otherwise. This is represented in figure B
above.
Toggle Mode – In this mode, the output toggles whenever
there is a compare match. If the output is high, it becomes
low, and vice-versa.
PWM Technique
Cont. Timer Modes 5
22
Timer Concepts - Revisited
In this section, we will revise some important and necessary
concepts related to timers. Consider the following timer diagram.
We are very well aware that the AVR provides us with an option
of 8 and 16 bit timers. 8bit timers count from 0 to 255, then back
to zero and so on. 16bit timers count from 0 to 65535, then back
to zero. Thus for a 8bit timer, MAX = 255 and for a 16bit timer,
MAX = 65535.
The timer always counts from 0 to TOP, then overflows back to
zero. In figure A shown above, TOP = MAX. Now, I guess you all
are familiar with timers in CTC Mode, in which you can clear the
timer whenever a compare match occurs. Due to this, the value
of TOP can be reduced as shown in figure B. The yellow line
shows how the timer would have gone in normal mode. Now, the
CTC Mode can be extended to introduce variable TOP as shown in
figure C (however there isn’t any practical utility of this).
TOP never exceeds MAX. TOP <= MAX.
Now that you are aware of the terminologies of TOP, BOTTOM
and MAX, we can proceed to the different modes of operation.
Timer Technique
23
Cont. Timer Modes
Fast PWM Mode
Consider the following diagram.
• In simple terms, this is Fast PWM! We have a
sawtooth waveform, and we compare it with a fixed
voltage level (say A), and thus we get a PWM output
as shown (in A). Now suppose we increase the
compare voltage level (to, say B). In this case, as we
can see, the pulse width has reduced, and hence
the duty cycle. But, as you can see, both the pulses
(A and B) end at the same time irrespective of their
starting time.
• In this mode, since sawtooth waveform is used, the
timer counter TCNTn (n = 0,1,2) counts from
BOTTOM to TOP and then it is simply allowed to
overflow (or cleared at a compare match) to
BOTTOM.
Fast PWM Technique
24
Cont. Timer Modes
Phase Correct PWM Mode
Now have a look at the following diagram.
• Here instead of a sawtooth waveform, we have
used a triangular waveform. Even here, you can see
how PWM is generated. We can see that upon
increasing the compare voltage level, the duty cycle
reduces. But unlike Fast PWM, the phase of the
PWM is maintained. Thus it is called Phase
Correct PWM.
• By visual inspection, we can clearly see that the
frequency of Fast PWM is twice that of Phase
Correct PWM.

Phase Correct PWM Technique


25
Cont. Timer Modes
Frequency and Phase Correct PWM Mode
Now have a look at the following diagram.
• Technically, Phase Correct PWM and Frequency and
Phase Correct PWM are same if the TOP remains
same. If we have a variable TOP, the frequency of
the output wave will keep changing as shown
below. The following illustration has a flaw (which
one of my readers pointed out) that it basically
represents a Fast PWM with variable frequency.
Due to lack of availability of time, it is not possible
for me to create another illustration. So, kindly bear
with me. However, you can at least get the concept
of variable TOP from the diagram.
• Thus, for this, we need Frequency and Phase
Correct PWM. Since in most cases the value of TOP
remains same, it doesn’t matter which one we are
choosing – Phase Correct or Frequency and Phase
Correct PWM. Freq and Phase Correct PWM Mode
26
Cont. Timer Modes
Choosing Timer
• In AVR, PWM Mode is available in all timers. TIMER0 and TIMER2 provide 8bit accuracy
whereas TIMER1 provides 16bit accuracy. In 8bit accuracy, you have 256 individual
steps, whereas in 16bit accuracy, you have 65536 steps.
• Now suppose you want to control the speed of a DC motor. In this case, having 65536
steps is totally useless! Thus we can use an 8bit timer for this. Even 8bit is too much,
but there is no other choice. Obviously there isn’t much difference in speed between
123/256th and 124/256th of full speed in case of a motor! But if you use servo motors,
you have to use 16bit timer. More on that later.
• If you need quite high resolution in your application, go for 16bit timer.

Choosing Mode of Operation


• If you want to control the speed of DC motors or brightness of LEDs, go for any one of
them. But if you are using it for telecommunication purposes, or for signal sampling,
fast PWM would be better. For general applications, phase correct PWM would do.
27
Cont. Timer Modes
Choosing Compare Output Modes
• Out of the three modes, inverted, non-inverted and toggle mode, non-inverted mode is
the most reasonable. This is because upon increasing the compare voltage, the duty
cycle increases. However, you can choose any of them. Regarding toggle mode, I
wonder if there is any practical application of it.
PWM and Timers 28
There is fixed relation between the timers and the PWM capable outputs. When you look in the data
sheet or the Pinout of the processor these PWM capable pins have names like OCRxA, OCRxB or OCRxC
(where x means the timer number 0..5). The PWM functionality is often shared with other pin
functionality.
The Arduino has 3Timers and 6 PWM output pins. The relation between timers and PWM outputs is:
Pins 5 and 6: controlled by timer0 The Default Frequency = 976.56 HZ
Pins 9 and 10: controlled by timer1 The Default Frequency = 490.20 HZ
Pins 11 and 3: controlled by timer2 The Default Frequency = 490.20 HZ
On the Arduino Mega we have 6 timers and 15 PWM outputs:
Pins 4 and 13: controlled by timer0 The Default Frequency = 976.56 HZ
Pins 11 and 12: controlled by timer1 The Default Frequency = 490.20 HZ
Pins 9 and10: controlled by timer2 The Default Frequency = 490.20 HZ
Pin 2, 3 and 5: controlled by timer 3 The Default Frequency = 490.20 HZ
Pin 6, 7 and 8: controlled by timer 4 The Default Frequency = 490.20 HZ
Pin 46, 45 and 44:: controlled by timer 5 The Default Frequency = 490.20 HZ
29
Examples of Timer Interrupts
Blinking LED with timer overflow #define ledPin 13
interrupt void setup() {
pinMode(ledPin, OUTPUT); // initialize timer1
we use the timer overflow interrupt. noInterrupts(); //disable all interrupts
In this case timer1 is running in TCCR1A = 0;
normal mode.
TCCR1B = 0; // 31250
The timer must be preloaded every
time in the interrupt service routine. TCNT1 = 34286; // preload timer 65536-(16MHz/256/2Hz)
TCCR1B |= (1 << CS12); // 256 prescaler
TIMSK1 |= (1 << TOIE1); // enable timer overflow interrupt
interrupts(); // enable all interrupts
}

ISR(TIMER1_OVF_vect)
{ // interrupt service routine that wraps a user defined function supplied by attachInterrupt
TCNT1 = 34286; // preload timer
digitalWrite(ledPin, digitalRead(ledPin) ^ 1);
}
void loop() { // your program here... }
30
Examples of Timer Interrupts
#define ledPin 13
Blinking LED with compare match void setup()
interrupt (CTC) {
pinMode(ledPin, OUTPUT);
uses the timer1 in CTC mode and // initialize timer1
the compare match interrupt to noInterrupts(); // disable all interrupts
toggle a LED. The timer is TCCR1A = 0;
configured for a frequency of 2Hz. TCCR1B = 0;
TCNT1 = 0;
The LED is toggled in the interrupt
OCR1A = 31250; // compare match register 16MHz/256/2Hz
service routine. TCCR1B |= (1 << WGM12); // CTC mode
TCCR1B |= (1 << CS12); // 256 prescaler
TIMSK1 |= (1 << OCIE1A); // enable timer compare interrupt
interrupts(); // enable all interrupts
}

ISR(TIMER1_COMPA_vect) // timer compare interrupt service routine


{
digitalWrite(ledPin, digitalRead(ledPin) ^ 1); // toggle LED pin
So if, you want to use flag instead }
of Interrupt void loop()
{
if (TIFR & (1 << OCF1A)) {} // your program here...
}
TIFR |= (1 << OCF1A);
Examples of Timer Interrupts 31
Measure pulse Width with Input Capture interrupt
The example uses the timer1 in Input Capture mode and the Input Capture interrupt to Measure pulse
width of external signal via pin 8
The time-stamps can then be used to calculate
frequency, duty-cycle, and other features of the signal
applied. Alternatively the time-stamps can be used for
creating a log of the events.
Notes :-
- The elements of the block diagram that are not directly
a part of the Input Capture unit are gray shaded.
- The noise canceler improves noise immunity by using a
simple digital filtering scheme. The noise canceler input
is monitored over four samples, and all four must be
equal for changing the output that in turn is used by the
edge detector. The noise canceler is enabled by setting The Input Capture Unit
the Input Capture Noise Canceler (ICNC1) bit in
Timer/Counter Control
Register B (TCCR1B). When enabled the noise canceler
introduces additional four system clock cycles of delay
from a change applied to the input, to the update of the
ICR1 Register. The noise canceler uses the system clock
and is therefore not affected by the prescaler.
How to adjust Arduino PWM frequencies 32
For further knowledge on Arduino PWM frequencies refer to the ATMega Complete Datasheet and this
Arduino.cc page "Secrets of Arduino PWM“
http://playground.arduino.cc/Main/TimerPWMCheatsheet
Issues from adjusting PWM Frequencies and workarounds :
http://forum.arduino.cc/index.php?topic=16612.msg121040#msg121040

Pins 5 and 6 TCCR0B = (TCCR0B & 0b11111000) | (0xyy);


Pins 9 and 10 TCCR1B = (TCCR1B & 0b11111000) | (0xyy);
Pins 11 and 3 TCCR2B = (TCCR2B & 0b11111000) | (0xyy);
33
Practical Applications

Watch the Video


34
References
I would like to thank all the sources which this information is collected from them, and I wish them
every success.
• Atmega328p Datasheet
• Arduino Cookbook, 2nd Edition: Michael Margolis
• http://playground.arduino.cc/Main/TimerPWMCheatsheet
• http://forum.arduino.cc/index.php?topic=16612.msg121040#msg121040
• https://www.arduino.cc/en/Tutorial/SecretsOfArduinoPWM
• http://maxembedded.com/2011/06/introduction-to-avr-timers/
• http://maxembedded.com/2011/08/avr-timers-pwm-mode-part-i/
• http://maxembedded.com/2012/01/avr-timers-pwm-mode-part-ii/
• http://letsmakerobots.com/node/28278
• http://www.embedds.com/programming-16-bit-timer-on-atmega328/
• http://gammon.com.au/timers
Contact Information
I hope if you use the parts of the slides, mentioned the source in order not waste this effort.

[email protected]

You might also like