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

CHAP2VER2

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

CHAP2VER2

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

Chapitre 2.

Microcontroller’s Advanced
Fonctionalities
•the planned activities

•The phone may ring

•Someone may knock on the door


•What should we
do?
•By default only the main routines
runs
•Interrupt routines run only when
there are interrupts

We can choose to ignore interrupt

If we prefer not to have interrupt


we can remove the interrupt routine
•If interrupt is disabled
•How do we handle cases when

•Someone •The phone


knocks on rings
our door

•We can check on the door regulary


since we won’t be able to hear any
knocking
•After checking we go back to our
normal routine,and periodically we
check on the phone as we will not
be able hearing any ringing
•This method is called
An interrupt in relation to
microcontrollers is a
mechanism that temporarily
suspends the main program,
passing control to an
interim code.
•The interrupt system onboard a
microcontroller allows it to respond to
these internally and externally generated
events. By definition we do not know
when these events will occur.
•A microcontroller normally executes
instructions in an orderly fetch-execute
sequence as dictated by a user-written
program.
•However, a microcontroller must also be
ready to handle unscheduled, events that
might occur inside or outside the
microcontroller.
•When an interrupt event occurs, the
microcontroller will normally complete the
instruction it is currently executing
•Saves the address of the next instruction (PC)
on the stack,
• then jumps to a fixed location in memory called the
And
interrupt vector table
•The microcontroller gets the address of
the ISR from the interrupt vector table
and jumps to it and starts to execute the
ISR unit it reaches last instruction RETI
Once the ISR is complete, the MCU returns
back to the interrupted program by loading
the return address from the stack to the
Program Counter.
the microcontroller will resume processing
where it left off before the interrupt event
occurred

.•Interrupts can be enabled or disabled


dynamically and when multiple interrupts
come simultaneously priorities can be
assigned.
The command by which we tell the MCU to suspend the MLP is
given in the form of voltage logic.This command signal is
known as Interrupting Signal or Interrupt Request Signal (IRQ)
An interrupt service routine (ISR) is a block of code that’s
executed in response to an interrupt.
Interrupt service routine (ISR)

The interrupt handler is an external function called an


Interrupts Service Routine (ISR). Interrupts service routines
do have specific constrains and do not behave exactly like
some other functions.
All register that will be used locally in the ISR must be saved
to the stack! This includes the SREG special function
register! Look at the following instructions in an assembler
program:
dec r16
brne LOOP1
If an interrupt will occur during the decrement instruction,
this instruction will be executed. Th following instruction
(branch if not equal) relies on the Zero flag from the SREG
register. If the flags are changed by operations inside the ISR
the program will not work properly.
;-------------------------------------------------------------------------------
; ISR with two internal variables
;--------------------------------------------------------------------------
-----
ISR_I1: push r16 ;save r16 to stack (needed as
temporary reg.)
in r16,SREG ;read status register
push r16 ;save SREG to stack
push r17 ;save r17 to stack (needed in ISR)

;ISR code

pop r17 ;recover r17


pop r16 ;recover SREG
out SREG,r16 ;
pop r16 ;recover r16
reti ;return from interrupt (takes return
address
;from stack and saves it to the program
ISRs don't get parameters, and they don't return anything.
Generally the ISR will use volatile global variables to
communicate with the main program.
An ISR should be very short (best less than a millisecond),
because it blocks the main program and also other ISRs.
Interrupt vector table
Atmega328P Interrupt vector is a definite address in the program
memory where a JMP instruction should be written to jump to the
ISR corresponding to the interrupt.
Each interrupt vector occupies two instruction words in the table,
because a jump (not relative) needs two instructions.
As seen,these interrupts and the
separate Reset Vector each have a
separate program vector located at
the lowest addresses in the Flash
program memory space.
The AVR provides several different interrupt sources.
These interrupts and the separate Reset Vector each have a separate
program vector in the program memory space.
All interrupts are assigned individual enable bits which must be written
logic one together with the Global Interrupt Enable bit in the Status
Register in order to enable the interrupt.
Types of Interrupts
 The ATmega328P provides support for 26 different interrupt
sources.
The table determines the priority levels of the different interrupts.
The higher the address the higher is the priority level. RESET has
the highest priority. Next is the external interrupt INT0 (Arduino
Uno Pin 2)
The interrupt priority noted in the above table is important when
more than one interrupt is generated at the same time.
When this happens, the interrupt of higher priority is executed
while the one of lower priority is suppressed.
“Reset” is the interrupt of highest priority and it has no interrupt
vector. This means that on the reset/reboot, no user-defined routine
can be run.
 interrupts are classified into two categories.

1. Hardware interrupts: generated by the microcontroller’s


input/output pins.
An external hardware/component triggers a change in voltage signal
for Atmega’s input/output pin.

 As the name suggests, external interrupts are triggered by


hardwares(External Devices).

there are two types of hardware interrupts: external and pin change
interrupts.
2. Software interrupts: generated by user-defined program
instructions.
They’re always associated with the microcontroller’s built-in
peripherals and communication port. These interrupts
are not triggered by an external hardware component but by
changes to the built-in peripherals or software configuration.

The built-in peripherals must be configured to generate interrupts


by writing program instructions.
Otherwise, the interrupt is generated automatically on completion of
a software instruction that’s associated with a communication
port/peripheral.
 Timer interrupt, Serial interrupts, ADC(Analog to Digital
Converters) interrupt etc are examples of Software interrupts
in Atmega32.
ATmega328P Interrupt Enable
All interrupts are assigned
 individual enable bits which must be written logic one together
 with the Global Interrupt Enable bit in the Status Register (SREG)
in order to enable the interrupt.

Global Interrupts (Interrupt flag in SREG)


 When an interrupt occurs, the Global Interrupt Enable I-bit is
cleared and all interrupts are disabled.
 The user software can write logic one to the I-bit to enable nested
interrupts.
 All enabled interrupts can then interrupt the current interrupt
routine. The I-bit is automatically set when a Return from
Interrupt instruction – RETI – is executed.
 When the AVR exits from an interrupt, it will always return to the
main program and execute one more instruction before any
pending interrupt is served.
The vector is normally a jump to the interrupt routine, and this jump
takes three clock cycles.

The interrupt execution response for all the enabled AVR interrupts is
four clock cycles minimum.
During this four clock cycle period, the Program Counter is pushed
onto the Stack.
After four clock cycles, the program vector address for the actual
interrupt handling routine is executed.

If an interrupt occurs during the execution of a multi-cycle


instruction, this instruction is completed before the interrupt is served.
A return from an interrupt handling routine takes four clock cycles.
During these four clock cycles, the Program Counter (two bytes) is
popped back from the Stack, the Stack Pointer is incremented by
two, and the I-bit in SREG is set.

If the program never enables an interrupt source, the Interrupt


Vectors are not used, and regular program codes can be placed at
these locations. This is also the case if the Reset Vector is in the
Application section while the Interrupt Vectors are in the Boot
section or vice versa.
How does interrupts work?
The service initiating a hardware interrupt sends an interrupt
request (IRQ) to the controller.
The controller marks the request with a specific interrupt flag (bit)
of that service in a special function register (SPR).
If interrupts are momentarily forbidden (locked), the flag memories
the interrupt request and it will be executed after the interrupt is
unlocked.
If the interrupt is activated (globally and specifically), the
controller ends the instruction momentarily executed by the main
program.
The return address (address of the following instruction in the
main program) is saved automatically to the stack.
All other interrupts are locked (global interrupt flag in the
SREG register).
The specific interrupt flag from the service initiating the interrupt is
cleared.
The controller looks at the the corresponding address in the vector
table and executes the instruction contained on that address (rjmp or
jmp).
If per example Timer0 generates an overflow interrupt request, the
controller will look at the Flash address 0x0020 and find an jump to
the interrupt handler (ISR) with the label TIM0_OVF (an arbitrary
name).

After the execution of the ISR the return address is loaded to the
program counter (this is done by the return from interrupt (reti)
instruction in the ISR).
The global interrupt flag in the SREG register is cleared, so that other
interrupts may be treated.
Minimum one instruction from the main program is executed.
Typical and general program setup in assembler for ATmega328P
(including the address; taken from the data sheet):
0x0000 jmp RESET ; Reset Handler
0x0002 jmp EXT_INT0 ; IRQ0 Handler
0x0004 jmp EXT_INT1 ; IRQ1 Handler
0x0006 jmp PCINT0 ; PCINT0 Handler
0x0008 jmp PCINT1 ; PCINT1 Handler
0x000A jmp PCINT2 ; PCINT2 Handler
0x000C jmp WDT ; Watchdog Timer Handler
0x000E jmp TIM2_COMPA ; Timer2 Compare A Handler
0x0010 jmp TIM2_COMPB ; Timer2 Compare B Handler
0x0012 jmp TIM2_OVF ; Timer2 Overflow Handler
0x0014 jmp TIM1_CAPT ; Timer1 Capture Handler
0x0016 jmp TIM1_COMPA ; Timer1 Compare A Handler
0x0018 jmp TIM1_COMPB ; Timer1 Compare B Handler
0x001A jmp TIM1_OVF ; Timer1 Overflow Handler
0x001C jmp TIM0_COMPA ; Timer0 Compare A Handler
0x001E jmp TIM0_COMPB ; Timer0 Compare B Handler
0x0020 jmp TIM0_OVF ; Timer0 Overflow Handler
0x0022 jmp SPI_STC ; SPI Transfer Complete Handler
0x0024 jmp USART_RXC ; USART, RX Complete Handler
0x0026 jmp USART_UDRE ; USART, UDR Empty
Handler
0x0028 jmp USART_TXC ; USART, TX Complete
Handler
0x002A jmp ADC ; ADC Conversion Complete
Handler
0x002C jmp EE_RDY ; EEPROM Ready Handler
0x002E jmp ANA_COMP ; Analog Comparator Handler
0x0030 jmp TWI ; 2-wire Serial Interface Handler
0x0032 jmp SPM_RDY ; Store Program Memory Ready
Handler
0x0033 RESET: ldi r16,high(RAMEND) ; Main program start
0x0034 out SPH,r16 ; Set Stack Pointer to top of RAM
0x0035 ldi r16,low(RAMEND)
0x0036 out SPL,r16
0x0037 sei ; Enable interrupts
0x0038 ... ; next instruction of Main
... ... ... ...
Reset and Interrupt Vectors Placement
MCUCR – MCU Control Register
The MCU Control Register controls the placement of the Interrupt
Vector table.

Bit 1 – IVSEL: Interrupt Vector Select


When the IVSEL bit is cleared (zero), the Interrupt Vectors are placed
at the start of the Flash memory.
When this bit is set (one), the Interrupt Vectors are moved to the
beginning of the Boot Loader section of the Flash.
Bit 0 – IVCE: Interrupt Vector Change Enable
The IVCE bit must be written to logic one to enable change of
the IVSEL bit.
IVCE is cleared by hardware four cycles after it is written or
when IVSEL is written
ATmega328P External Interrupts
The External Interrupts are triggered by the INT0 and INT1
PIN change interrupt is an other form of hardware interrupt
They are not restricted to specific pins
All the pins can be used for pin change interrupt

The interrupts will trigger even if the INT0 and INT1 or


PCINT23…0 pins are configured as outputs.
ATmega328P External Interrupts

External Interrupt INT0 External Interrupt INT1


Associated with PD2 (pin 2) on Associated with PD3 (pin 3)
the ATmega328P on the ATmega328P.
can be triggered by a low logic level,
any logic change, and a falling or
rising edge.

Can be used to trigger an Can be used as a second


interrupt service routine external interrupt to
(ISR) that responds to trigger another ISR for
events such as button handling additional
presses, sensor readings, or external events or
other external signals. signals.
ATmega328P External Interrupt Enable

Global Interrupt Enable bit in the Status Register (SREG) in order to


enable the interrupt.
EIMSK – External Interrupt Mask Register
We can enable/disable external interrupts by setting bits INT1 and
INT0 in the External Interrupt Mask register EIMASK.

•Bit 7:2 – Reserved


These bits are unused bits and will always read as zero .
Bit 1 – INT1: External Interrupt Request 1
Enable :
When the INT1 bit is set (one) and the I-bit in the Status Register
(SREG) is set (one), the external pin interrupt is enabled.
Bit 0 – INT0: External Interrupt Request 0
Enable : When the INT0 bit is set (one) and the I-bit in the Status
Register (SREG) is set (one), the external pin interrupt is enabled.
EIFR – External Interrupt Flag Register
The External Interrupt Flag Register contains the INTF1 and INTF0
flag.

•Bit 7:2 – Reserved


These bits are unused bits and will always read as zero.
•Bit 1 – INTF1: External Interrupt Flag 1
When an edge or logic change on the INT1 pin triggers an interrupt
request, INTF1 becomes set (one).
•If the I-bit in SREG and the INT1 bit in EIMSK are set (one), the
MCU will jump to the corresponding Interrupt Vector.
•The flag is cleared when the interrupt routine is executed.
Alternatively, the flag can be cleared by writing a logical one to it.
•This flag is always cleared when INT1 is configured as a level
interrupt.
•Bit 0 – INTF0: External Interrupt Flag 0
When an edge or logic change on the INT0 pin triggers an interrupt
request, INTF0 becomes set (one).
•If the I-bit in SREG and the INT0 bit in EIMSK are set (one), the
MCU will jump to the corresponding Interrupt Vector.
•The flag is cleared when the interrupt routine is executed.
Alternatively, the flag can be cleared by writing a logical one to it.
This flag is always cleared when INT0 is configured as a level
interrupt.
EICRA – External Interrupt Control Register A

To define a level trigger or edge trigger on external INT0 and INT1


pins External Interrupt Control Register A is used.
ISC01, ISC00 (Interrupt Sense Control bits)

These bits define the level or edge that triggers the INT0 pin.
ISC11, ISC10 (Interrupt Sense Control bits)

These bits define the level or edge that triggers the INT1 pin.
The main program will keep le blue LED turn on
When push button A is pressed the red LED turns on for second
And when push button B is pressed the green LED turns on for
second
There are two ways to achieve that: Polling and interrupt
The main program will keep the blue LED turn on
When push button A is pressed the red LED turns on for second
And when push button B is pressed the green LED turns on for
second
Programing the Atmega 328 for interrupt

 Set up the stack


 Enable External Interrupt Mask (EIMask)
 Set INT0 bit to a logic 1 in the external Interrupt control register
A (EICRA)
 Set global interrupt Enable(Ibit)in the status register
LED BLUE:
PIN Change Interrupts

In addition to our two (2) external interrupts, twenty-three (23) pins


can be programmed to trigger an interrupt if there pin changes state.
Pin Change Interrupts allow you to detect changes in the state of a
pin and trigger an interrupt service routine (ISR) in response.
This allows you to respond quickly to changes in input signals, such
as button presses, sensor readings, or other events, without having to
continuously poll the pin in your code
The Pin Change Interrupts in ATMega328 work by monitoring the
state of multiple pins in a group, referred to as a Pin Change Interrupt
Vector.
When a change in state, such as a rising or falling edge, is detected on
one or more of the pins in the group, the corresponding interrupt
flag(s) is set, and the ISR associated with the interrupt is executed.
These 23 pins are in turn divided into three (3) interrupt groups

Thus there are 3 banks for pin change interrupt for three ports; B,
C and D.
See the atmega328 interrupt vector table table below.
To use Pin Change Interrupts in ATMega328, you need to configure
the necessary registers and register bits.
This typically involves setting the interrupt mask register (PCMSKx)
to specify which pins in the group you want to monitor, and enabling
the Pin Change Interrupts in the Pin Change Interrupt Control Register
(PCICR)

Optionally there is also pin change interrupt flag register which are set
if interrupt are enabled. You also need to implement the ISR function
in your code, which will be executed when the interrupt is triggered. It
is a bit different from Programming Atmega328P External Interrupt.
The difference being mainly due to masking of bits required and the
pin change interrupt having lower priority than the external hardware
interrupt.

Thus there are mainly 3 types of registers- a control register, a flag


register and mask register
PCICR – Pin Change Interrupt Control Register

The Pin Change Interrupt Control Register contains enables or


disables the PCI1, PCI2, PCI3.

Bit 7:3 – Reserved


These bits are unused bits and will always read as zero.
Bit 2 – PCIE2: Pin Change Interrupt Enable 2
 When the PCIE2 bit is set (one)
 and the I-bit in the Status Register (SREG) is set (one),
 pin change interrupt 2 is enabled.
 Any change on any enabled PCINT[23:16] pin will cause an
interrupt.
 The corresponding interrupt of Pin Change Interrupt Request is
executed from the PCI2 Interrupt Vector.
 PCINT[23:16] pins are enabled individually by the PCMSK2
Register.
Bit 1 – PCIE1: Pin Change Interrupt Enable 1
 When the PCIE0 bit is set (one)
 and the I-bit in the Status Register (SREG) is set (one),
 pin change interrupt 0 is enabled.
 Any change on any enabled PCINT[7:0] pin will cause an
interrupt.
 The corresponding interrupt of Pin Change Interrupt Request
is executed from the PCI0 Interrupt Vector.
 PCINT[7:0] pins are enabled individually by the PCMSK0
Register.
PCIFR – Pin Change Interrupt Flag Register

The Pin Change Interrupt Flag Register contains the PCIF1, PCIF2,
PCIF3 flags.

Bit 7:3 – Reserved


These bits are unused bits and will always read as zero.

The flag register to monitor interrupt flag is usually not required


as interrupt happens automatically.
Bit 2 – PCIF2: Pin Change Interrupt Flag 2
 When a logic change on any PCINT[23:16] pin triggers an
interrupt request, PCIF2 becomes set (one).
 If the I-bit in SREG and the PCIE2 bit in PCICR are set (one),
 the MCU will jump to the corresponding Interrupt Vector.
 The flag is cleared when the interrupt routine is executed.
Alternatively, the flag can be cleared by writing a logical one to it.

Bit 1 – PCIF1: Pin Change Interrupt Flag 1


 When a logic change on any PCINT[14:8] pin triggers an
interrupt request, PCIF1 becomes set (one).
 If the I-bit in SREG and the PCIE1 bit in PCICR are set (one),
the MCU will jump to the corresponding Interrupt Vector.
 The flag is cleared when the interrupt routine is executed.
Alternatively, the flag can be cleared by writing a logical one to
it.
PCMSK2 – Pin Change Mask Register 2

Bit 7:0 – PCINT[23:16]: Pin Change Enable Mask 23…16


Each PCINT[23:16]-bit selects whether pin change interrupt is
enabled on the corresponding I/O pin.
If PCINT[23:16] is set
and the PCIE2 bit in PCICR is set,
pin change interrupt is enabled on the corresponding I/O pin.
If PCINT[23:16] is cleared, pin change interrupt on the
corresponding I/O pin is disabled.
PCMSK1 – Pin Change Mask Register 1

Bit 6:0 – PCINT[14:8]: Pin Change Enable Mask 14…8


Each PCINT[14:8]-bit selects whether pin change interrupt is enabled
on the corresponding I/O pin.
If PCINT[14:8] is set and the PCIE1 bit in PCICR is set, pin change
interrupt is enabled on the corresponding I/O pin.
If PCINT[14:8] is cleared, pin change interrupt on the corresponding
I/O pin is disabled.
PCMSK0 – Pin Change Mask Register 0

Bit 6:0 – PCINT[7:0]: Pin Change Enable Mask 7…0


Each PCINT[7:0] bit selects whether pin change interrupt is
enabled on the corresponding I/O pin.
If PCINT[7:0] is set and the PCIE0 bit in PCICR is set, pin change
interrupt is enabled on the corresponding I/O pin.
If PCINT[7:0] is cleared, pin change interrupt on the corresponding
I/O pin is disabled.
Thus there are mainly 3 types of registers- a control register, a flag
register and mask register.
So the steps to enable pin change interrupt on a pin are:

1. Selectthe pin for pin change interrup, say PD7


2. Enable pin-change interrupt on PD7.
To do this, first find the bank where PD7 is located which is port D
and the port D pin change interrupt belongs to PCINT2 bank. This
means that the PCIE2 bit in the PCICR register has to be set. IIn
program code we do this in the following manner
3. Mask the PD7 pin
Since PD7 belongs the PCINT2 we need to mask the PCINT23 bit in
the PCMSK2 register. This is done in the following way in program
code.
4. Enable to global interrupt.
Timer in AVR ATmega32
Introduction
Timers are one of the most important features in modern
microcontrollers.
They allow us to measure how long something takes to execute, create
non-blocking code, precisely control pin timing, and even run
operating systems.
Generally, we use a timer/counter to
1. Turn on or 2. Generate a precision 3. Measure the
turn off an output signal (period, characteristics
external duty cycle, frequency). (period, duty
device at a For example, generate cycle, frequency)
programmed a complex digital of an incoming
time. waveform with varying digital signal
pulse width to control Count external
the speed of a DC events
motor
•Internal Timer: As an internal timer the unit, ticks on the oscillator
frequency. The oscillator frequency can be directly feed to the timer
or it can be pre-scaled. In this mode it used generate precise delays.
Or as precise time counting machine.
•External Counter: In this mode the unit is used to count events on
a specific external pin on a MCU.
•Pulse width Modulation(PWM) Generator: PWM is used in
speed control of motors and various other applications.
What is a Counter

The counter part of an ATmega328P Timer/Counter


peripheral subsystem is an example of an asynchronous
(ripple) counter, which is a collection of flip-flops with the
clock input of stage n connected to the output of stage n -1
Timing Terminology
 Frequency
 The number of times a particular event repeats within a 1-s
period.
 The unit of frequency is Hertz, or cycles per second.
 For example, a sinusoidal signal with a 60-Hz frequency
means that a full cycle of a sinusoid signal repeats itself 60
times each second, or every 16.67 ms.
 For the digital waveform shown, the frequency is 2 Hz.
 Period
 The flip side of a frequency is a period.
 If an event occurs with a rate of 2 Hz, the period of that event is
500 ms.
 To find a period, given a frequency, or vice versa, we simply
need to remember their inverse relationship, F = 1/T where F and
T represent a frequency and the corresponding period,
respectively.
Duty Cycle
In many applications, periodic pulses are used as control signals.
A good example is the use of a periodic pulse to control a servo
motor. To control the direction and sometimes the speed of a motor,
a periodic pulse signal with a changing duty cycle over time is used.
Duty cycle is defined as the percentage of one period a signal is ON.
The periodic pulse signal shown in the Figure is ON for 50% of the
signal period and off for the rest of the period. Therefore, we call
the signal in a periodic pulse signal with a 50% duty cycle. This
special case is also called a square wave.
Definitions of commonly used terms in Timer
 BOTTOM The counter reaches the BOTTOM when it
becomes 0x00.
 MAX The counter reaches its MAXimum when it becomes
0xFF (decimal 255).
 TOP The counter reaches the TOP when it becomes equal to
the highest value in the count sequence.
 The TOP value can be assigned to be the fixed value 0xFF
(MAX) or the value stored in the OCR0A Register. The
assignment is dependent on the mode of operation.
Clock Source

 The Timer/Counter can be clocked internally, via the Prescaler, or


by an external clock source on the T0 pin.
 The Clock Select logic block controls which clock source and
edge the Timer/Counter uses to increment (or decrement) its value.
 The Timer/Counter is inactive when no clock source is selected
In AVR ATmega32, there are three timers:
•Timer0: 8-bit TC0 (Timer/Counter 0) Module/Register. It is also
Known as TCNT0 (Timer/Counter 0).
•Timer1: 16-bit TC1 (Timer/Counter 1) Module/Register. It is also
Known as TCNT1 (Timer/Counter 1).
•Timer2: 8-bit TC2 (Timer/Counter 2) Module/Register. It is also
Known as TCNT2 (Timer/Counter 2).

Timer0 and Timer1 can also be used as a counter but we can not use
Tmier2 as a counter
Basic registers and flags of the Timers

A. TCNTn: Timer / Counter Register


Every timer has a timer/counter register. It is zero upon reset.
We can access value or write a value to this register. It counts up with
each clock pulse.

B. TOVn: Timer Overflow Flag


Each timer has a Timer Overflow flag. When the timer
overflows, this flag will get set.

C. TCCRn: Timer Counter Control Register


This register is used for setting the modes of timer/counter.

D. OCRn: Output Compare Register


The value in this register is compared with the content of the
TCNTn register. When they are equal, the OCFn flag will get set.
Counter Unit
The main part of the Timer/Counter is the programmable bi-directional
counter unit.

Signal Description:
Increment or decrement TCNTn
count
by 1
Select between increment or
direction
decrement
clkTn can be
generated
from an
external or
internal clock
source

clear Clear TCNTn


clkTn Timer / Counter Clock
Depending on the
Signalize that TCNTn has
top mode of operation
reached a maximum value
used, the counter is
Signalize that TCNTn has cleared, incremented,
bottom
reached the minimum value or decremented at each
timer clock (clkTn).
Output Compare Unit

 comparator
continuously
compares TCNTn
and OCRn.
 If equal, the
output compare
flag is set
(OCFn) and an
interrupt can be
issued.

The waveform generator uses this signal to generate an output


to a pin.
Determination of Count Value to be loaded into Timer/Counter n

Let's suppose that we want to create a time delay of 50us. Then the
formula to calculate the count value to be loaded into TCNTn register is
as follows.
where, Td = 50us, Fosc = 8MHz, and N is pre-
scalar which can be 1, 8, 64, 256 or 1024
We cannot use pre-scalar of 1 because it will
give negative value for C. So we use next pre-
scalar 8. This then will give value C as,
Basic Mode of Timer Operations

There are basically three types of timer mode of operation which are:
1. Normal Mode
2. CTC Mode
3. PWM
a. Fast PWM
b. Phase Correct PWM
8 bit timers
The ATmega168 has 2, 8-bit timers: Counter0 and Counter2. Each of
these timers are controlled by the following registers.
Counter0 Counter2 Description
TCCR0A TCCR2A Timer/Counter Control Register A
TCCR0B TCCR2B Timer/Counter Control Register B
TCNT0 TCNT2 Timer/Counter Register
OCR0A OCR2A Output Compare Register A
OCR0B OCR2B Output Compare Register B
Timer/Counter Interrupt Mask
TIMSK0 TIMSK2
Register

We’ll focus on Counter0 and the most commonly used registers.


Timer0: 8-bit

The registers which are important in configuring and reading flags


for Timer/Counter 0 are as follows.
1. TCCR0 – Timer/Counter 0 Control Register

This is an 8-bit register used to determine


 the mode of operation of this timer
 The frequency or clock frequency by determining the value of
prescalar

Bit 7- FOC0: Force compare match


Write only a bit, which can be used while generating a wave.
Writing 1 to this bit causes the wave generator to act as if a
compare match has occurred.
Bit 6, 3 - WGM00, WGM01: Waveform Generation Mode
The following table shows what bit combination of WGM01 and
WGM00 configures the micrcontroller timer/counter in which mode.
Bit 5:4 - COM01:00: Compare Output Mode
These bits control the waveform generator.
Bit 2:0 - CS02:CS00: Clock Source Select
These bits are used to select a clock source.
The following tables is used to determine the value of these bits.
2. TIFR0 – Timer/Counter 0 Interrupt Flag
Register

Bit 0 - TOV0: Timer0 Overflow flag


0 = Timer0 did not overflow
1 = Timer0 has overflown (going from 0xFF to 0x00)
Bit 1 - OCF0: Timer0 Output Compare flag
0 = Compare match did not occur
1 = Compare match occurred

Bit 2 - TOV1: Timer1 Overflow flag


Bit 3 - OCF1B: Timer1 Output Compare B match flag
Bit 4 - OCF1A: Timer1 Output Compare A match flag
Bit 5 - ICF1: Input Capture flag
Bit 6 - TOV2: Timer2 Overflow flag
Bit 7 - OCF2: Timer2 Output Compare match flag
3. OCR0: (output compare register)
-8 bit register
this register is always compared against TCNT0
When the two values are equal,the output compare flag (OCF0) will
be set

4. TCNT0 :The timer counter register.

 the 8-bit counter itself


 holds the present value of count
 counts from 0 to 255
 When value exceeds 255,the timer overflowflag is set indicating
the end of the count
5. TIMSK – Timer/Counter Interrupt Mask Register

controls which interrupts are enabled.

Bit 0 - TOIE0: Timer/Counter0 Overflow Interrupt Enable

When the TOIE0 = 1 and the I-bit in the Status Register = 1


the Timer/Counter0 Overflow interrupt is enabled
The corresponding interrupt (at vector $012) is executed if an
overflow in Timer/Counter0 occurs
Bit 7 - OCIE2: Timer/Counter2 Output Compare Match Interrupt Enable
When the OCIE2 bit is set (one) and the I-bit in the Status Register is set (one),
the Timer/Counter2 Compare Match interrupt is enabled.
The corresponding interrupt (at vector $006) is executed if a compare
match in Timer/Counter2 occurs, i.e. when the OCF2 bit is set in the Timer/Counter
Interrupt Flag Register - TIFR.

Bit 6 - TOIE2: Timer/Counter2 Overflow Interrupt Enable


When the TOIE2 bit is set (one) and the I-bit in the Status Register is set (one),
the Timer/Counter2 Overflow interrupt is enabled. The corresponding interrupt
(at vector $008) is executed if an overflow in Timer/Counter2 occurs, i.e. when the TOV2
bit is set in the Timer/Counter Interrupt Flag Register - TIFR.
Bit 5 - TICIE1: Timer/Counter1 Input Capture
Interrupt Enable

When the TICIE1 bit is set (one) and the I-bit


in the Status Register is set (one), the
Timer/Counter1 Input Capture Event Interrupt
is enabled. The corresponding interrupt (at
vector $00A) is executed if a capture triggering
event occurs on PD6 (ICP), i.e. when the ICF1
bit is set in the Timer/Counter Interrupt Flag
Register - TIFR.

Bit 4 - OCIE1A: Timer/Counter1 Output


CompareA Match Interrupt Enable

When the OCIE1A bit is set (one) and the I-


bit in the Status Register is set (one), the
Timer/Counter1 CompareA Match interrupt is
enabled. The corresponding interrupt (at
vector $00C) is executed if a CompareA match
in Timer/Counter1 occurs, i.e. when the OCF1A
bit is set in the Timer/Counter Interrupt Flag
Register - TIFR.
Bit 3 - OCIE1B: Timer/Counter1 Output
CompareB Match Interrupt Enable

When the OCIE1B bit is set (one) and the I-


bit in the Status Register is set (one), the
Timer/Counter1 CompareB Match interrupt is
enabled. The corresponding interrupt (at
vector $00E) is executed if a CompareB match
in Timer/Counter1 occurs, i.e. when the OCF1B
bit is set in the Timer/Counter Interrupt Flag
Register - TIFR.

Bit 2 - TOIE1: Timer/Counter1 Overflow


Interrupt Enable

When the TOIE1 bit is set (one) and the I-bit


in the Status Register is set (one), the
Timer/Counter1 Overflow interrupt is enabled.
The corresponding interrupt (at vector $010) is
executed if an overflow in Timer/Counter1
occurs, i.e. when the TOV1 bit is set in the
Timer/Counter Interrupt Flag Register - TIFR.
 Detailed block diagram of timer0
Normal Mode
The simplest model of operation is the Normal mode
 In this mode of operation, the Timer is usually used in creating
certain time delay.
 The required time delay determines count value that is loaded into
the Timer TCNTn register.
 Once TCNTn is loaded the timer is started.
 The count starts from the loaded count value to the top value which is
256 decimal or 0xFF hex for 8-bit timer0.
 Once the top value is reached, flags are set in the Timer/Counter flag
register and the timer is again loaded with the count value and the
process is repeated.
 .
 We can also setup to generate timer/counter interrupt by
configuring certain registers related to the timer/counter

The counter simply overruns when it passes its maximum 8-bit value
(TOP = 0xFF) and then restarts from the bottom (0x00).

In normal operation, the Timer/Counter Overflow Flag (TOVn) will


be set in the same timer clock cycle as the TCNTn becomes zero.

The TOVn Flag, in this case, behaves like a ninth bit, except that it is
only set, not cleared.

However, combined with the timer overflow interrupt that


Automatically clears the TOVn Flag,
Steps to Program Delay using Timer0

1. Load the TCNT0 register with the initial value (let’s take 0x25).
2. For normal mode and the pre-scaler option of the clock, set the value
in the TCCR0 register. As soon as the clock Prescaler value gets
selected, the timer/counter starts to count, and each clock tick causes
the value of the timer/counter to increment by 1.
3.Timer keeps counting up, so keep monitoring for timer overflow i.e.
TOV0 (Timer0 Overflow) flag to see if it is raised.
4. Stop the timer by putting 0 in the TCCR0 i.e. the clock source will
get disconnected and the timer/counter will get stopped.
5. Clear the TOV0 flag. Note that we have to write 1 to the TOV0 bit to
clear the flag.
6. Return to the main function.
. CTC Mode

Clear Timer on Compare (CTC) mode is a mode of operation for the


timers in microcontrollers.
It is used to generate a specific frequency of square wave signals by
comparing the timer's counter value to a predetermined value, also
known as the compare value.

There are two advantages of CTC mode of the timer.


First, CTC mode provides users for greater and flexible control of
frequency of the output square wave signal generated at the OC0A or
OC0B pins.
The second advantage of CTC mode is that this mode simplifies the
counting of external events.
Clear Timer on Compare Match (CTC) Mode

counter resolution manipulated by output compare register (OCR0)


-counter cleared to zero when its value equals OCR0
-TOP defined by OCR0
-interrupt can be generated at compare point
-output pin (OC0) can be utilized
-output pin can toggle, set, or clear on match
-duty cycle constant, frequency is variable
Important Registers for CTC mode
The important registers for configuring the ATmega328p
microcontroller in CTC mode are as follows.
TCCR0A – Timer/Counter 0 Control Register A

The function of Compare Output Modes bits COM0A1, COM0A0 in


Non-PWM mode is defined as follows.
Similarly, the function of Compare Output Modes bits COM0B1,
COM0B0 in Non-PWM mode is defined as follows.

Timers and CTC pins


Each of Timer is equipped with Clear Timer on Compare Match(CTC)
feature.
Each timer has two compare units and hence each timer can generate
CTC signal on two pins
The Timer 0 generates CTC signal on pin PD6(OC0A) and
PD5(OC0B),
the Timer 1 generates CTC signal on pin PB1(OC1A) and
PB2(OC1B)
and the Timer 2 generates CTC signal on pin PB3(OC2A) and
PD3(OC2B). This is shown in the picture below.
The ATmega168 has a single 16 bit timer, which is referred to as
Counter1. It works like the 8 bit timer, except the counter has more
bits in it. This intervals to be set with longer duration and greater
precision.
Timer 1 Basics
The Timer 1 is 16 bit, that means it can count from 0 to 2^16 =
65536.
Hence the Timer/Counter 1 is a 16 bit registered formed out of
TCNT1H and TCNT1L as shown below.

Timer 3 also has 2 control registers which allow us to configure it and


use it in any mode you wish.

You might also like