Sunteți pe pagina 1din 96

Timer/Counter

Modified from Dr. Lam Phung’s Slides


Timers in AVR
• Many computer applications require accurate
timing.
• Examples include
– recording the time when an event occurs,
– calculating the time difference between events,
– performing tasks at specific or periodic times,
– creating accurate time delays,
– generating waveforms of certain shape, period, or
duty cycle
Timer terminology
• Input Capture:
– An input signal is connected to a pin, called input capture,
of the timer.
– When a preset event (rising edge, falling edge, change)
occurs on this pin, the current timer value is stored in a
register.
• Output Compare:
– A timer typically has a pin, called output compare.
– When the timer reaches a preset value, the output
compare pin can be automatically changed to logic 0 or
logic 1.
Overview of Timers in ATmega8535
• ATmega8535 has three timers: Timer 0, Timer 1
and Timer 2.
• Each timer is associated with a counter and a
clock signal.
• The counter is incremented by 1 in every clock
cycle of the timer.
• The clock signal of a timer can come from
– the internal system clock or
– an external clock source.
Overview of Timers in ATmega8535
• When the internal system clock is used, a
prescaler can be applied to make the timer
count at a slower rate.
• Example:
– Consider a system clock of 1Mhz (i.e. 1μs per
cycle).
– Suppose that a timer prescaler of 64 is used.
– Then, timer will increment every 64μs.
Overview of Timers in ATmega8535
8-bit Timer/Counter0 with PWM
• Features
– Single Compare Unit Counter
– Clear Timer on Compare Match (Auto Reload)
– Glitch-free, Phase Correct Pulse Width Modulator (PWM)
– Frequency Generator
– External Event Counter
– 10-bit Clock Prescaler (1, 8, 64, 256, 1024)
– Overflow and Compare Match Interrupt Sources (TOV0 and
OCF0)
Timer/Counter
Control Register

External Clock
Pin

Current timer/
counter value

Output Compare
Register
Output
Compare Pin
Timer Registers
Registers
Timer/Counter Control Register – TCCR0

• Bit 7 – FOC0: Force Output Compare


– The FOC0 bit is only active when the WGM00 bit
specifies a non-PWM mode.
– However, for ensuring compatibility with future
devices, this bit must be set to zero when TCCR0 is
written when operating in PWM mode.
Timer/Counter Control Register – TCCR0

• Bit 6, 3 – WGM01:0: Waveform Generation Mode


– Modes of operation supported by the Timer/Counter unit are:
Normal mode, Clear Timer on Compare Match (CTC) mode,
and two types of Pulse Width Modulation (PWM) modes
Operation Mode- Normal Mode (0)
WGM01:0 = 0

• In the normal mode, the timer


will continually count from 0x00
(BOTTOM) to 0xFF (TOP).
• When the TCNT0 returns to 0
on each cycle of the counter,
the Timer/Counter Overflow
Flag (TOV0) will be set.

• The normal mode is useful for generating a periodic ‘‘clock


tick’’ that may be used to calculate elapsed real time or
provide delays within a system fclk _ I /O
ftov = N: Prescaler
N�
256
Operation Mode- Phase Correct PWM
Mode (1) → WGM01:0 = 1
• In the Phase Correct PWM
mode, the TCNT0 register
counts from 0x00 to 0xFF and
back down to 0x00 continually.
• Every time the TCNT0 value
matches the value set in the
OCR0 register, the OCF0 flag is
set and a change in the PWM
signal occurs.
fclk _ I /O
fOCnPCPWM =
N�
510
N: Prescaler
Operation Mode- Clear Timer on Compare Match
(2) → WGM01:0 = 2

• In the CTC modem, the TCNT0


timer is reset to 0 every time
the TCNT0 counter reaches the
value set in OCR0.
• The Output Compare Flag 0
(OCF0) is set when this event
occurs.
• The OCF0 flag is enabled by
• The CTC mode is used to asserting the Timer/Counter 0
generate a precision digital Output Compare Math
waveform such as a Interrupt Enable (OCIE0) flag in
periodic signal or a single the TIMSK and when the I-bit in
pulse. the Status Register is set to 1.
Operation Mode- Fast PWM (3)
• The fast PWMmode is used to
generate a precision
PWMsignal of a desired
frequency and duty cycle.
• It is called the fast PWM
because its maximum
frequency is twice that of the
Phase Correct PWM mode.
• When the TCNT0 register value
• It continues to count up reaches the value set in the
to the TOP value, at which OCR0 register, it will cause a
time the Timer/Counter 0 change in the PWM output as
Overflow Flag (TOV0) is prescribed by the system
set. designer.
Timer/Counter Control Register – TCCR0

• Bit 2:0 – CS02:0: Clock Select


– The three Clock Select bits select the clock source to be
used by the Timer/Counter.
Timer/Counter Control Register – TCCR0

• Bit 5:4 – COM01:0: Compare Match Output Mode


– These bits control the Output Compare pin (OC0) behavior.
– If one or both of the COM01:0 bits are set, the OC0 output
overrides the normal port functionality of the I/O pin it is
connected to.
– However, note that the Data Direction Register (DDR) bit
corresponding to the OC0 pin must be set in order to
enable the output driver.
Data Direction Register (DDR) bit
corresponding to the OC0 pin

pin must be set in order


to enable the output
driver
Timer/Counter Control Register – TCCR0

• The function of the COM01:0 bits depends on


the WGM01:0 bit setting.
• Normal (0), CTC (2)
Timer/Counter Control Register – TCCR0

• Fast PWM Mode (3)

A special case occurs when OCR0 equals TOP and COM01 is set. In this
case, the Compare Match is ignored, but the set or clear is done at TOP
Timer/Counter Control Register – TCCR0

• Phase Correct PWM Mode (1)


Timer/Counter Register – TCNT0

• The Timer/Counter Register gives direct access, both


for read and write operations, to the Timer/Counter
unit 8-bit counter.
• Writing to the TCNT0 Register blocks (removes) the
Compare Match on the following timer clock.
• Modifying the counter (TCNT0) while the counter is
running, introduces a risk of missing a Compare
Match between TCNT0 and the OCR0 Register.
Output Compare Register – OCR0

• The Output Compare Register contains an 8-


bit value that is continuously compared with
the counter value (TCNT0).
• A match can be used to generate an output
compare interrupt, or to generate a waveform
output on the OC0 pin.
Timer/Counter Interrupt Mask
Register – TIMSK

• Bit 1 – OCIE0: Timer/Counter0 Output Compare


Match Interrupt Enable
– When the OCIE0 bit is written to one, and the I-bit in the
Status Register is set (one), the Timer/Counter0
Compare Match interrupt is enabled.
– The corresponding interrupt is executed if a Compare
Match in Timer/Counter0 occurs (i.e., when the OCF0 bit
is set in the Timer/Counter Interrupt Flag Register –
TIFR).
Timer/Counter Interrupt Mask
Register – TIMSK

• Bit 0 – TOIE0: Timer/Counter0 Overflow


Interrupt Enable
– When the TOIE0 bit is written to one, and the I-bit in
the Status Register is set (one), the Timer/Counter0
Overflow interrupt is enabled.
– The corresponding interrupt is executed if an
overflow in Timer/Counter0 occurs (i.e., when the
TOV0 bit is set in the Timer/Counter Interrupt Flag
Register – TIFR).
Timer/Counter Interrupt Flag
Register – TIFR

• Bit 1 – OCF0: Output Compare Flag 0


– The OCF0 bit is set (one) when a Compare Match
occurs between the Timer/Counter0 and the data
in OCR0 – Output Compare Register0.
Timer/Counter Interrupt Flag
Register – TIFR

• Bit 0 – TOV0: Timer/Counter0 Overflow Flag


– The bit TOV0 is set (one) when an overflow occurs
in Timer/Counter0. TOV0 is cleared by hardware
when executing the corresponding interrupt
handling vector
Example using Timer/Counter
• Want to create a program that will blink LED at
0.5 Hz on PortC (3,2,1,0).
• Assume FCPU = 16 MHz.
• Solution:
– Use Timer0 as delay that will generate interrupt at
every overflow
– Timer0 counts from 0 to 255 (256 times)
– Need an interrupt every second
Example using Timer/Counter
• Need a clock to feed the timer/counter0 at
1/256 = 3.90625 ms → 256 Hz
• With FCPU=16MHz → Need a prescaler
– 16M/256 = 62500
– But we only have a max of 1024 prescaler…..
– What to do?
Example using Timer/Counter
• So we begin with max prescaler
– 16M/1024 = 15625 Hz
• Timer/Counter will overflow
– 15625/256 = 61.03515625 Hz → 16.384 ms
• To get 1 second
– 1 sec = N * 16.384 ms → N = 61.03515625
– N → 61
– Create a variable to hold N and increment N at
every time the timer/counter overflows
Example using Timer/Counter

• Setting Up Timer/Counter0 : TCCR0


– Prescaler @ 1024, Waveform Generator Off,
Output Compare off.
– Prescaler @ 1024 CS02:0 = 5 (101)
// Prescaler = FCPU/1024
TCCR0|=(1<<CS02)|(1<<CS00);
Example using Timer/Counter

• Setting Up Timer/Counter0 : TCCR0


– Enable Overflow Interrupt
//Enable Overflow Interrupt Enable
TIMSK|=(1<<TOIE0);

– Not like setting up external interrupt


– But still need to enable global interrupt in SREG
Example using Timer/Counter
• ISR for Timer0 Overflow @ 61.03515625 Hz
ISR(TIMER0_OVF_vect)
{
//This is the interrupt service routine for TIMER0 OVERFLOW Interrupt.
//CPU automatically call this when TIMER0 overflows.

//Increment our variable

N++;
if(N==61)
{
PORTC=~PORTC; //Invert the Value of PORTC
N=0;
}
}
// File: timer0.c
// Date modified: 17 Sept 2012
// By: Yudi Gondokaryono

#include <avr/io.h> // avr header file for IO ports


#include <avr/interrupt.h> // avr header file for interrupts

volatile uint8_t N;

int main(void)
{
// Prescaler = FCPU/1024
TCCR0|=(1<<CS02)|(1<<CS00);
//Enable Overflow Interrupt Enable
TIMSK|=(1<<TOIE0);
//Initialize Counter
TCNT0=0;
//Initialize our variable
N=0;
//Port C[3,2,1,0] as output
DDRC|=0x0F;
PORTC=0x0F; // Turn off LEDs
//Enable Global Interrupts
sei();
//Infinite loop
while(1);
}

ISR(TIMER0_OVF_vect)
{
//This is the interrupt service routine for TIMER0 OVERFLOW Interrupt.
//CPU automatically call this when TIMER0 overflows.

//Increment our variable


N++;
if(N==61)
{
PORTC=~PORTC; //Invert the Value of PORTC
N=0;
}
}
Timer 1: An overview
• 16-bit counter.
• 10-bit prescaler: 8, 64, 256, and 1024
• can trigger a timer overflow interrupt when counter reaches
MAX.
• can trigger an input capture interrupt when an event occurs
on the input capture pin.
– timer value is stored automatically in a register.
– input capture pin for Timer 1 is ICP1 .
• can trigger an output compare match interrupt when timer
reaches a preset value.
– There are two independent output compare channels A and B.
Timer 1: Block diagram
Timer/Counter1
Registers
• Timer/Counter 1
– TCNT1
– 16-bit register that stores the current
value of the timer.
• Timer/Counter 1 Control Registers
– TCCR1A and TCCR1B
– To configure the operations of Timer 1.
• Input Capture Register
– ICR1
– to store timer value when an event occurs
on input capture pin.
• Interrupt registers
– TIMSK to enable timer interrupts
– TIFR to monitor status of timer interrupts.
• Output Compare Registers
– OCR1A, OCR1B
– To store the preset values for output
compare.
Timer/Counter 1 Control Register A (TCCR1A)
Timer/Counter 1 Control Register B (TCCR1B)
Clock select

• Timer 1 can use the internal or external clock.


• If using the internal clock, we can set Timer 1 to run 8,
64, 256, or 1024 times slower than the internal clock.
Waveform Generator
Timer/Counter Interrupt Mask Register
(TIMSK)
Timer/Counter Interrupt Flag Register (TIFR)
Timer applications
• In this section, we consider three applications
of Timer 1.
– Creating an accurate delay using timer overflow
interrupt.
– Measuring elapsed time between two events.
– Measuring the period of a square signal using
input capture interrupt.
Creating an accurate delay
• Write a C program to toggle PORTB every 2
seconds.
• It should use Timer 1 overflow interrupt to
create delays of 2s each.
Creating an accurate delay
• Analysis
– Internal system clock: 1MHz.
– With no prescaler, Timer 1 increments every 1 μs.
– Timer 1 is 16-bit counter, so it will overflow every 216 μs.
– For a 2s delay, we need Timer 1 to overflow for 2s/216 μs = 31
times.
• Coding
– Write code to enable & intercept Timer 1 overflow interrupt.
– Use interrupt handler to count the number of overflows.
– When number overflows is 31, toggle port B.
Creating an accurate delay: timer_delay.c
Measuring elapsed time
• To measure time using Timer 1, we must keep
track of both
– the number of times that Timer 1 has overflowed: n
– the current counter value: TCNT1
• If we reset n and TCNT1 at the beginning of the
interval, then the time elapse is (assuming no
prescaler, 1MHz clock)
t = n x 65536 + TCNT1 (μs)
Measuring elapsed time

t = n x 65536 + TCNT1 (μs)


Measuring elapsed time
• Use Timer 1 to measure the execution time of
some custom C code.
• Approach:
– Clear Timer 1 when the code starts.
– Record Timer 1 when the code finishes.
– Also, use Timer 1 Overflow Interrupt to keep track
of how many times it has overflowed.
Measuring elapsed time: measure_time.c
Measuring period of a square signal
• Use Timer 1 input capture interrupt to measure the
period of a square wave
• Analysis:
– The period of a square wave = the time difference
between two consecutive rising edges.
– Connect the square wave to input capture pin of Timer 1.
– Configure input capture module to trigger on a rising
edge.
Input Capture Unit Block Diagram

• When a capture is triggered, the 16-bit value of the


counter (TCNT1) is written to the Input Capture Register
(ICR1).
Measuring period of a square signal
• Assumption: the input signal has a high
frequency, hence timer overflow can be ignored.
• Implementation:
– Select timer operations: normal, no prescaler, internal
clock 1MHz, noise canceller enabled, input capture
for rising edges.
• TCCR1A = 0b00000000;
• TCCR1B = 0b11000001;
– Enable input capture interrupt:
• TIMSK = 0b00100000;
measure_period.c
Output Compare
• Output compare allows custom processing to be
done when timer reaches a preset target value.
• Examples of custom processing:
– clearing timer,
– changing values of dedicated pins,
– triggering an interrupt.
• Output compare can be used to
– generate signals of various shapes,
– perform actions (e.g. ADC) at specific time instants.
Output Compare: Common elements
• Output compare registers: To store the target timer
values.
• Output compare pins: These dedicated pins can be
automatically changed (set, reset, toggled) when there
is an output compare match.
• Configuration registers: To configure the operations of
timer.
• Output compare interrupt: Code for extra processing
when there is an output compare match can be put in
ISR.
Output Compare Unit in Timer 1
• Timer 1 has two output compare channels: A and
B.
• Timer 1 is continuously compared to OCR1A,
OCR1B, or a fixed limit.
• When a match occurs, a flag OCF1x is set where x
= A’ or ‘B’.
• When a match occurs, Timer 1 can
– trigger an output compare interrupt.
– change output compare pins OC1x.
Output Compare Unit ─ Block diagram
Double Buffering
• The double buffering synchronizes the update of the OCR1x
Compare Register to either TOP or BOTTOM of the counting
sequence.
• The synchronization prevents the occurrence of odd-length, non-
symmetrical PWM pulses, thereby making the output glitch-free.
• When the double buffering is enabled, the CPU has access to the
OCR1x Buffer Register.
• The content of the OCR1x (Buffer or Compare) Register is only
changed by a write operation (the Timer/Counter does not
update this register automatically as does the TCNT1– and ICR1
Register).
Output Compare Unit ─ Main aspects

• What changes can be made to output


compare pins OC1x?
• What are the available operation modes of
timer 1?
• Steps to produce a custom waveform?
• How to use output compare interrupt?
Changing output compare pins OC1x
• When there’s a timer event (compare match, or timer = 0),
pins OC1x can be automatically updated:
– toggle,
– set to 1,
– clear to 0, or
– no change.
• The type of update is controlled by two bits in TCCR1A register:
– COM1x1 and COM1x0 where x = ‘A’ or ‘B’.

• The exact change depends also the operation mode of Timer 1.


Operations modes of Timer 1
• Timer 1 has 15 operation modes that are divided
into 5 groups:
– Normal
– Clear Timer on Compare Match
– Fast PWM
Three PWM groups
– Phase correct PWM
– Phase and Frequency Correct PWM
• The operation mode is selected by 4 bits:
WGM = {WGM13, WGM12, WGM11, WGM10}
Selecting operation mode of Timer 1
Normal mode
• Timer repeatedly counts from 0 to TOP, where TOP =
0xFFFF.
• Overflow flag TOV1 is set after timer reaches TOP.
• No change is allowed on output compare pins OC1x
CTC modes
• Timer is reset to 0 when it reaches the value in
OCR1A or ICR1
CTC modes
• On compare match, change of pins OC1x is
allowed.
Note CTC Mode
• Changing the TOP to a value close to BOTTOM when the
counter is running with a low or no prescaler value must be
done with care since the CTC mode does not have the
double buffering feature.
• If the new value written to OCR1A or ICR1 is lower than the
current value of TCNT1, the counter will miss the Compare
Match.
• The counter will then have to count to its maximum value
(0xFFFF) and wrap around starting at 0x0000 before the
Compare Match can occur.
• In many cases this feature is not desirable.
Fast PWM modes
• Timer goes from 0 to TOP, where TOP is equal to
– 0xFF (for 8-bit mode, WGM = 0101),
– 0x1FF (for 9-bit mode, WGM = 0110),
– 0x3FF (for 10-bit mode, WGM = 0111),
– value in ICR1 (for WGM = 1110),
– value in OCR1A (for WGM = 1111).
• Compare match occurs when timer = OCR1x register.
Fast PWM modes
• On compare match, change of pins OC1x is
allowed.
Fast PWM modes
Note to PWM Mode
• Changing the TOP value the program must
ensure that the new TOP value is higher or
equal to the value of all of the compare
registers.
• If the TOP value is lower than any of the
compare registers, a Compare Match will
never occur between the TCNT1 and the
OCR1x.
Note to PWM Mode
• Using the ICR1 Register for defining TOP works
well when using fixed TOP values.
– By using ICR1, the OCR1A Register is free to be
used for generating a PWM output on OC1A.
• However, if the base PWM frequency is
actively changed (by changing the TOP value),
using the OCR1A as TOP is clearly a better
choice due to its double buffer feature.
Phase Correct PWM modes
• Timer counts up and down between 0 and TOP, where TOP is equal
to
– 0xFF (for 8-bit mode, WGM = 1000)
– 0x1FF (for 9-bit mode, WGM = 0010)
– 0x3FF (for 10-bit mode, WGM = 0011)
– value in ICR1 (for WGM = 1010)
– value in OCR1A (for WGM = 1011)
• Compare match occurs when timer = OCR1x register
Phase Correct PWM modes
• On compare match, change of pins OC1x is
allowed.
Phase Correct PWM modes
Phase and Frequency Correct PWM modes

• Timer counts up and down between 0 and


TOP, where TOP is equal to
– value in ICR1 (for WGM = 1000) or
– value in OCR1A (for WGM = 1001)
• Compare match occurs when timer = OCR1x
register.
• On compare match, changing pins OC1x is
done similarly in Phase Correct PWM modes.
Actively changing PWM Freq.
• Using Phase Correct PWM mode (WGM = 1011)
– Use OCR1A as TOP (double buffered)
– OCR1A is updated @ TOP
– The PWM period starts and ends at TOP.
– Consequence:
• This implies that the length of the falling slope is determined by
the previous TOP value, while the length of the rising slope is
determined by the new TOP value.
• When these two values differ the two slopes of the period will
differ in length.
• The difference in length gives the unsymmetrical result on the
output.
Phase Correct PWM mode
(WGM = 1011)
Actively changing PWM Freq.
• Using Phase and Freq Correct PWM mode
(WGM = 1001)
– Use OCR1A as TOP (double buffered)
– OCR1A is updated @ BOTTOM
– The PWM period starts and ends at TOP.
– Consequence:
• Gives symmetrical result on the output.
Phase and Freq Correct PWM mode
(WGM = 1001)
Producing a custom waveform
Steps to produce a custom waveform on an
output compare pin OC1x
1. Select the operation mode of Timer 1:
CTC, fast PWM, or phase correct PWM, …
2. Select how output compare pin will be set registers
TCCR1A and
updated on compare match event. TCCR1B
3. Configure timer 1: clock source,
prescaler, …
4. Put correct values in the output compare
registers. set register
OCR1A or ICR1
Example 1: Producing a custom waveform

• Use Timer 1 to create a signal with period =


1000μs, high time = 200μs
Determining registers

• ICR1 = 1000 → period of output signal


• OCR1A = 200 → pulse width of output signal
• WGM3:0 = 1110 → Fast PWM mode where TOP = ICR1.
• CS12:0 = 001 → Internal clock, no prescaler
• COM1A1:0 = 10 → set OC1A when timer = 0
clear OC1A when compare match
Program make_pwm.c
Testing
• Use oscilloscope to measure signal on pin
OC1A
Output Compare Interrupt
• What if we need to
– perform custom operations at predefined time
instants, or
– produce signals on an arbitrary output pin?
• A possible approach is to
– trigger an output compare interrupt at correct
time instants.
– write an ISR that performs the custom operations.
Output Compare Interrupt

• Output compare interrupt is enabled by OCIE1A


and OCIE1B flag for channel A and B, respectively.
• C names for these interrupts:
TIMER1_COMPA_vect and TIMER1_COMPB_vect.
Output Compare Interrupt
• Use Timer 1’s output compare interrupt to
toggle pin B(1) every 1000μs.
Program oc_int.c
Example application of PWM
• PWM signals are commonly used in embedded applications:
motor control, sound alarm and radio transmission.
• A PWM signal is a periodic, rectangular pulse. The period
and the duty cycle can vary.
• Here, we’ll generate a PWM signal to control a servo motor.
Controlling a servo motor
• We use a servo motor S3003.
• It has three wires
– Black: Ground
– Red: DC supply between (4.8V, 6V)
– White: PWM signal
• To keep the motor at a given angle, we
must send a PWM signal of a specific
duty cycle.
• The frequency of the PWM signal is
50Hz.
• This motor have a rotation range of 180°.
• Range of duty cycle: 1% to 12%.
Controlling a servo motor
• Write C program that lets the user press switches SW0
and SW1 to rotate the motor left and right, respectively.

• The switches can be connected to pins of port A.


• Depending on which switch is pressed, we increment or
decrement the duty cycle.
• We then produce a PWM signal on pin OC1A with
– a period of 20000μs,
– a specific duty cycle between 1% and 12%.
motor_control.c

S-ar putea să vă placă și