0% found this document useful (0 votes)
242 views20 pages

Avr Notes

This document provides an overview of AVR microcontrollers, including their architecture, memory organization, interrupts, and built-in features such as analog-to-digital converters (ADCs), pulse-width modulation (PWM), and timers. It also discusses assembly instruction sets, C programming, interrupt programming, and programming peripherals like keyboards, LCDs, and ADCs. Questions and answers are provided about interrupt structures, registers associated with ports, ADC features, addressing modes, and memory organization.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
242 views20 pages

Avr Notes

This document provides an overview of AVR microcontrollers, including their architecture, memory organization, interrupts, and built-in features such as analog-to-digital converters (ADCs), pulse-width modulation (PWM), and timers. It also discusses assembly instruction sets, C programming, interrupt programming, and programming peripherals like keyboards, LCDs, and ADCs. Questions and answers are provided about interrupt structures, registers associated with ports, ADC features, addressing modes, and memory organization.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

AVR micro-controllers

Overview and features (8335), Architecture, memory organization interrupts, inbuilt


controller features (ADC, PWM and Timer)
Assembly instruction set and introduction to C programming, interrupt programming,
keyboard and LCD programming, ADC, DAC programming.

Questions

1. Describe interrupt structure of AVR microcontroller. (4)


Ans: There are no of interrupts resourses varies as per variants of AVR. The AVR 8-bits microcontroller
provide both internal and external interrupt sources. The internal interrupts are associated with the
microcontroller's peripherals. That is the Timer/Counter, Analog Comparator, UART, USART, WDT, SPI,
ADC, EEPROM, RESET, etc. The external interrupts are triggered via external pins.e.g
Atmega128 has 35 Interrupts sorces,
Atmega32 has 26 Interrupt resources,
Atmega8535 has 21 interrupt resourses,
AT90S8515 has 13 interrupt resourses and so on…
In order for the microcontroller to respond to an interrupt event the interrupt feature of the microcontroller must
be enabled along with the specific interrupt. This is done by setting the Global Interrupt Enabled bit and the
Interrupt Enable bit of the specific interrupt. For the AVR 8-bits microcontroller this bit is located in the
Status I/O Register (SREG). The Global Interrupt Enabled is bit 7, the I bit, in the SREG.

Bit 7 – I: Global Interrupt Enable


The Global Interrupt Enable bit must be set for the interrupts to be enabled. The individual interrupt enable
control is then performed in separate control registers. If the Global Interrupt Enable Register is cleared, none of
the interrupts are enabled independent of the individual interrupt enable settings. The I-bit is cleared by
hardware after an interrupt has occurred, and is set by the RETI instruction to enable subsequent interrupts. The
External Interrupts are triggered by the INT0, INT1, and INT2 pins. This feature provides a way of generating a
software interrupt. The External Interrupts can be triggered by a falling or rising edge or a low level This is set
up as indicated in the specification for the MCU Control Register – MCUCR and MCU Control and Status
Register – MCUCSR.
The MCU Control Register contains control bits for interrupt sense control and general MCU functions.
MCU Control and Status Register – MCUCSR

An interrupt vector is the memory address of an interrupt handler. The interrupt vector for each interrupt
provided by the AVR microcontrollers can be found in its respective datasheet. The General Interrupt Control
Register (GICR) controls the placement of the Interrupt Vector table.

Bit 0 - IVCE: Interrupt Vector Change Enable


Bit 1 -IVSEL: Interrupt Vector Select
INT0 - External Interrupt Request 0
INT1 - External Interrupt Request 1
INT2 - External Interrupt Request 2.
( For answer of such question only mention the register you know don’t write details of each field as it is not
specifically mentioned. Also provided the one must write the genral about Interrupts in brief as it shows better
understanding.)

2. Describe registers associated with ports of AVR microcontroller. (4)


Ans: Ports in the AVR are gates from the central processing unit to internal and external hard- and software
components. The CPU communicates with these components, reads from them or writes to them, e.g. to the
timers or the parallel ports. The most used port is the flag register, where results of previous operations are
written to and branch conditions are read from.
There are 64 different ports, which are not physically available in all different AVR types. Depending on
the storage space and other internal hardware the different ports are either available and accessable or not.
Which of these ports can be used is listed in the data sheets for the processor type.
Ports have a fixed address, over which the CPU communicates. The address is independent from the
type of AVR. So e.g. the port adress of port B is always 0x18 (0x stands for hexadecimal notation). You don't
have to remember these port adresses, they have convenient aliases. These names are defined in the include files
(header files) for the different AVR types, that are provided from the producer.
All information in the microcontroller, from the program memory, the timer information, to the state on
any of input or output pins, is stored in registers. Registers are like shelves in the bookshelf of processor
memory. In an 8-bit processor, like the AVR ATMega 16 we are using, the shelf can hold 8 books, where each
book is a one bit binary number, a 0 or 1. Each shelf has an address in memory, so that the controller knows
where to find it.
The 32 IO pins of the ATMega16 are divided into 4 ports, A, B, C, and D. Each port has 3 associated
registers. For example, for port D, these registers are referred to in C-language by PORTD, PIND, and DDRD.
For port B, these would be PORTB, PINB, and DDRB, etc. In C-language, PORTD is really a macro, which
refers to a number that is the address of the register in the AVR, but it is much easier to remember PORTD than
some arbitray hexadecimal number.
The DDRx Register
 The DDRD register sets the direction of Port D. Each bit of the DDRD register sets the corresponding
Port D pin to be either an input or an output. A 1 makes the corresponding pin an output, and a 0 makes
the corresponding pin an input.
 To set the second pin to be an input, one may use the cbi(reg,bit) function which clears a bit (makes it
low or binary 0) in a register:
 Note that in C, the bit indexing begins with 0. The bits in a register go from 0 to 7. This may be a source
of confusion, because when we talk about the "first pin" or "pin 1" of a port, we are referring to the 0 bit
or P0 in C. The AVRmini boards label the first pin as pin 1.
 To set the value of all the bits in the DDRx register (or any register) using the outb(reg,byte) command.
It writes a byte (8 bits) to a register.
The PORTx Register
 The PORTx register functions differently depending on whether a pin is set to input or output. The
simpler case is if a pin is set to output. Then, the PORTC register, for example, controls the value at the
physical IO pins on Port C. For example, we can set all the port C pins to output and then make 4 of
them high (binary 1) and 4 of them low (binary 0):
 When a pin is set to be an input, PORTx register DOES NOT contain the logic values applied to the
pins. We use the PINx register for that. If a pin is an input, a 1 in the PORTx register sets a pull-up
resistor. This is helpful for a variety of circuits.
The PINx Register
 When a pin is set to input, the PINx register contains the value applied to the pin. The pins have an
electrical threshold of around 2.5 volts. If a voltage above this level is applied to an input pin, the
corresponding bit of the PINx register will be a 1. Below this voltage, the bit will be a zero. To read the
value of an input port, you can use the inb(reg) function. It returns an 8-bit number that is the value of
the 8 bits in the specified register. 
 There is also a function available for checking the state of an individual bit, without reading the entire
PINx register. The function bit_is_set(reg,bit) returns a 1 if the given bit in the given register is set, and
a 0 if the bit is cleared.

3. Write any four important features of ADC in AVR microcontroller.(4)


Ans: Many AVR parts have a built-in Analog to Digital Converter (ADC). The ADC has a resolution of 10 bits,
and, depending on which part is used, there are 6 to 8 channels available. Sampling rates up to 15.4 ksps, using
full 10-bit resolution, are selectable.
Features of ADC in AVR microcontroller(Atmega16/32)

4. Describe any four addressing modes of AVR microcontroller with suitable example.(4)
Ans: The addressing modes used of AVR Microcontroller as follows: (For more examples w.r.t to each mode please refer
the Mazidi’s book for AVR very detailed explaination is there. And for digram explaining the modes one may refer the
AVR instruction set maual)
 Register Direct, Single Register Rd

 Register Direct, Two Registers Rd and Rr

 I/O Direct
 Data Direct

 Data Indirect with Displacement

 Data Indirect

 Data Indirect with Pre-decrement

 Data Indirect with Post-increment

 Direct Program Addressing

 Indirect Program Addressing

 Relative Program Addressing


5. Describe memory organiztion of AVR microcontroller.(4)
Ans: The AVR Enhanced RISC microcontroller supports powerful and efficient the Program memory (Flash)
and Data memory (SRAM, Register file, I/O Memory, and Extended I/O Memory).
Program memory:
The AVR's program is stored in nonvolatile (persistent on power-down) programmable Flash memory.
It is divided into 2 sections. The first section is the Application Flash section. It is where the AVR's program is
stored. The second section is called the Boot Flash section and can be set to execute immediately when the
device is powered up. The Flash has a special property of being able to write over itself, which may seem like a
stupid thing to do.
But the Boot Flash section can come in handy if it is programmed with a small program that takes data from
the serial port and writes it into the Application Flash section. Such a program is called a bootloader, and it
allows the device to be programmed from a regular serial port, rather than using a complicated or expensive
programmer circuit. For commercial devices, it makes so-called “firmware upgrades” very easy. We will use a
bootloader. This program is already loaded on the chip.
Data memory:
The AVR's data memory is volatile RAM. It is organized in 8-bit registers. All information in the
microcontroller, from the program memory, the timer information, to the state on any of input or output pins, is
stored in registers. Registers are like shelves in the bookshelf of processor memory. In an 8-bit processor, like
the one we are using, the shelf can hold 8 books, where each book is a one bit binary number, a 0 or 1. Each
shelf has an address so that the controller knows where to find it. Some registers, such as those in RAM, are for
storing general data. Others have specific functions like controlling the A/D converters or timers, or setting and
getting values on the I/O pins. Registers in RAM can be read or written. Other registers may be read-only or
write-only. In fact, some specialized registers may have certain bits that are only to be read, and certain bits that
are only to be written.
Registers:
 32 8-bit GPRs (General Purpose Registers)
 R0 - R31
 16-bit X-, Y-, and Z-register
 Used as address pointers
 PC (Program Counter)
 16-bit SP (Stack Pointer)
 8-bit SREG (Status Register)
 7 8-bit I/O registers (ports)

AVR Memory Architecture Overview


6. Draw and explain architecture of AVR microcontroller.
Ans: (Explain the details accordingly to the blocks shown in figure as per marks provided)

AVR microcontroller Architecture:


This applies to all types of AVR microcontrollers because they all use same AVR core technology. So lets
go through some of them:
 Ability to work at 1MIPS/MHz (MIPS – Millions Instructions Per Second); 
 On chip Flash memory (now tiny series have up to 8kB, mega up to 256kB) with write cycle not less
than 1000 times;
 On chip RAM memory (tiny series up to 512B, mega up to 8kB); 
 On chip EEPROM memory (tiny series up to 512B, mega up to 4kB) with write cycle not less than
100000 times;
 Working frequencies up to 20MHz;
 Protection fuses from unintentional reading and modification of program and data memories; 
 Ability to program in system – directly on board using ISP cable; 
 Four types of clock generators: Internal generator, RC generator of clock cycles, Internal generator with
external crystal resonator, and External synchronisation; 
 Two or three power down modes; 
 Some microcontroller can work at very low voltages like 1.8V; 
Other internal processor properties:
 Static architecture where minimal frequency equal to zero; 
 ALU is connected directly to general purpose registers; 
 Most of commands are performed in one clock cycle; 
 Multilevel system of interrupts;
 Many sources of interrupts – two of them are external; 
 Three level hardware stack.
I/O system properties:
 Software configurable and selection of I/O ports; 
 Ports can be programmed as inputs and outputs independently to each other; 
 Input buffers uses Smith triggers on all pins;
 Support of Internal Pull-Up resistors (about 35 to 120kOhm); 
Peripheral devices vary from device to device. Refer to datasheets to find out what peripherals are included in
concrete model. In general we can mention:
 8 bit timer counter with pre-scaler; 
 16 bit timer counter with pre-scaler ; 
 Watch dog timer;
 PWM generator;
 Analog comparator;
 ADC;
 Hardware modulator;
 SPI interface;
 TWI (I2C) interface;
 UART.

7. Write a .C. program to flash 55H and AAH alternately. Eight LED.s are connected to PORTD of AVR microcontroller.(4)
Ans:
#include <avr/io.h>
#include <util/delay.h>
int main()
{
DDRD = 0xFF; // Configure port D as output
while(1)
{
PORTC = 0x55; // Turn ON LEDs alternately
_delay_ms(250); // Wait 250ms
PORTC = 0xAA; // Turn OFF LEDs
_delay_ms(250); // Wail 250ms
}
return 0;
}

8. Explain with neat diagram ADC module and associated registers ofAVR. (8)
Ans: (For more useful data and related information please go through http://www.avrbeginners.net/)
The Analog to Digital Converter (ADC) is used to convert an analog voltage (a voltage that vary
continuously within a known range) to a 10-bit digital value. For instance, it can be used to log the output of a
sensor (temperature, pressure, etc) at regular intervals, or to take some action in function of the measured
variable value. There are several types of ADCs. The one used by AVR is of the "succesive approximation
ADC" kind. The following is a simplified scheme of the ADC.
At the input of the ADC itself is an analog multiplexer, which is used to select between eight analog
inputs. That means that you can convert up to eight signals (not at the same time of course). At the end of the
conversion, the correponding value is transferred to the registers ADCH and ADCL. As the AVR's registers are
8-bit wide, the 10-bit value can only be held in two registers.
The analog voltage at the input of the ADC must be greater than 0V, and smaller than the ADC's
reference voltage AREF. The reference voltage is an external voltage you must supply at the Aref pin of the
chip. The value the voltage at the input is converted to can be calculated with the following formula:
ADC conversion value = round( (vin/vref)*1023)
Since it is a 10-bit ADC, you have 1024(1024=2^10) possible output values (from 0 to 1023). So, if vin is equal
to 0V, the result of the conversion will be 0, if vin is equal to vref, it will be 1023, and if vin is equal to vref/2 it
will be 512. As you can see, since you are converting a continuous variable (with infinite possible values) to a
variable with a finite number of possible values (elegantly called a "discrete variable"), the ADC conversion
produces an error, known as "quantization error".

Modes of Operation:
The ADC has two fundamental operation modes: Single Conversion and Free Running. In Single
Conversion mode, you have to initiate each conversion. When it is done, the result is placed in the ADC Data
register pair and no new conversion is started. In Free Runing mode, you start the conversion only once, and
then, the ADC automatically will start the following conversion as soon as the previous one is finished.
The analog to digital conversion is not instantaneous, it takes some time. This time depends on the clock signal
used by the ADC. The conversion time is proportional to the frequency of the ADC clock signal, which must be
between 50kHz and 200kHz.
If you can live with less than 10-bit resolution, you can reduce the conversion time by increasing the
ADC clock frequency. The ADC module contains a prescaler, which divides the system clock to an acceptable
ADC clock frequency. You configure the division factor of the prescaler using the ADPS bits (see below for the
details).
To know the time that a conversion takes, just need to divide the number of ADC clock cycles needed
for conversion by the frequency of the ADC clock. Normaly, a conversion takes 13 ADC clock cycles. The first
conversion after the ADC is switched on (by setting the ADEN bit) takes 25 ADC clock cycles. This first
conversion is called an "Extended Conversion". For instance, if you are using a 200kHz ADC clock signal, a
normal conversion will take 65 microsenconds (13/200e3=65e-6), and an extended conversion will take 125
microseconds (25/200e3=125e-6).

Registers related ADC:


There are four registers related to the operation of the ADC : ADC Multiplexer Select Register
(ADMUX), ADC Control and Status Register (ADCSR), ADC Data Register Low (ADCL) and ADC Data
Register High (ADCH). Let's discuss them in detail.

ADMUX
Bit Bit Bit Bit Bit Bit 2 Bit 1 Bit 0
7 6 5 4 3
--- --- --- --- --- MUX2 MUX1 MUX0
This register is used to select which of the 8 channel (between ADC0 to ADC7) will be the input to the ADC.
Since there are 8 possible inputs, only the 3 least significant bits of this register are used. The following table
describe the setting of ADMUX.
MUX2 MUX1 MUX0 Selected
Input
0 0 0 ADC0
0 0 1 ADC1
0 1 0 ADC2
0 1 1 ADC3
1 0 0 ADC4
1 0 1 ADC5
1 1 0 ADC6
1 1 1 ADC7
If these bits are changed during a conversion, the change will have no effect until this conversion is
complete. This is a problem when multiple channels are scanned:

The ISR always changes the ADMUX value to the next channel (or some other value that can be
reconstructed by the next ISR) the value in the ADC data register pair is always the conversion result from the
last ADMUX change. When the ISR changes ADMUX from 2 to 3, the value in the data registers is from
channel 2.

ADCSR

Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0


ADEN ADSC ADFR ADIF ADIE ADPS2 ADPS1 ADPS0
ADEN (ADC Enable) bit : Setting this bit enables the ADC. By clearing this bit to zero, the ADC is
turned off. Turning the ADC off while a conversion is in progress will terminate this conversion.
ADSC (ADC Start Conversion) bit : In Free Running Mode, you must set this bit to start the first conversion.
The following conversions will be started automatically. In Single Conversion Mode, you must set it to start
each conversion. This bit will be cleared by hardware when a normal conversion is completed. Remember that
the first conversion after the ADC is enabled is an extended conversion. An extended conversion will not clear
this bit after completion.
ADFR (ADC Free Running Select) bit : To use the Free Running Mode, you must set this bit.
ADIF (ADC Interrupt Flag) bit : This bit is set when an ADC conversion is completed.
If the ADIE bit is set and global interrupts are enabled, the ADC Conversion Complete interrupt is
executed. ADIF is cleared by hardware when executing the corresponding interrupt handling vector.
Alternatively, ADIF is cleared by writing a logical 1 (!) to the flag. This has a nasty side effect : if you modify
some other bit of ADCSR using the SBI or the CBI instruction, ADIF will be cleared if it has become set before
the operation.
ADIE (ADC Interrupt Enable) bit : When the ADIE bit is set and global interrupts are enabled, the ADC
interrupt is activated and the ADC interrupt routine is called when a conversion is completed. When cleared, the
interrupt is disabled.
ADPS (ADC Prescaler Select ) bits : These bits determine the division factor between the AVR clock frequency
and the ADC clock frequency. The following table describe the setting of these bits :

ADPS2 ADPS1 ADPS0 Division


Factor
0 0 0 2
0 0 1 2
0 1 0 4
0 1 1 8
1 0 0 16
1 0 1 32
1 1 0 64
1 1 1 128
ADCL and ADCH

These registers hold the result of the last ADC conversion. ADCH holds the two most significant bits, and
ADCL holds the remaining bits.
When ADCL is read, the ADC Data Register is not updated until ADCH is read. Consequently,it is essential
that both registers are read and that ADCL is read before ADCH.
The ATmega series of AVRs have a more complex ADC. They are similar to the ADC explained here, but have
some additional features like (see the datasheet for the details) :
 7 Differential Input Channels
 2 Differential Input Channels with Optional Gain of 10x and 200x(1)
 Optional Left adjustment for ADC Result Readout
 Selectable 2.56V ADC Reference Voltage
 ADC Start Conversion by Auto Triggering on Interrupt Sources
9. Write a note on Timers of AVR Microcontrollers.
Ans: The AVR has different Timer types. Some AVRs have special timers which support many more modes.
The timers basically only count clock cycles. The timer clock can be equal to the system clock (from the crystal
or whatever clocking option is used) or it can be slowed down by the prescaler first. When using the prescaler
you can achieve greater timer values, while precision goes down.
The prescaler can be set to 8, 64, 256 or 1024 compared to the system clock. An AVR at 8 MHz and a
timer prescaler can count (when using a 16-bit timer) (0xFFFF + 1) * 1024 clock cycles = 67108864 clock
cycles which is 8.388608 seconds. As the prescaler increments the timer every 1024 clock cycles, the resolution
is 1024 clock cycles as well: 1024 clock cycles = 0.000128 seconds compared to 0.125µs resolution and a range
of 0.008192 seconds without prescaler. It's also possible to use an external pin for the timer clock or stop the
timer via the prescaler.
The timers are realized as up-counters. Here's a diagram of the basic timer hardware. Don't panic, I'll
explain the registers below
The 8-bit Timer:

The 8-bit timer is pretty simple: The timer clock (from System Clock, prescaled System Clock or
External Pin T0) counts up the Timer/Counter Register (TCNT0). When it rolls over (0xFF -> 0x00) the
Overflow Flag is set and the Timer/Counter 1 Overflow Interrupt Flag is set. If the corresponding bit in TIMSK
(Timer Interrupt Mask Register) is set (in this case the bit is named "TOIE0") and global Interrupts are enabled,
the micro will jump to the corresponding interrupt vector (in the 2313 this is vector number 7).
The 16-bit Timer
is a little more complex, as it has more modes of operation:
Register Overview:
Write:
When writing the high byte (e.g. TCNT1H), the data is placed in the TEMP register. When the low byte is
written, the data is transferred to the actual registers simultaneously. So the high byte must be written first to
perform a true 16-bit write.
Read:
When reading the low byte, the high byte is read from TCNT1 simultaneously and can be read afterwards. So
when reading, access the low byte first for a true 16-bit read.
TCNT
Most important is the Timer/Counter Register (TCNT1) itself. This is what all timer modes base on. It counts
System Clock ticks, prescaled system clock or from the external pin.
TCCR

The Timer/Counter Control register is used to set the timer mode, prescaler and other options.
TCCR1A:
Bit 7 Bit 0
COM1A1 COM1A0 --- --- --- --- PWM11 PWM10

Here's what the individual bits do:


COM1A1/COM1A0: Compare Output Mode bits 1/0; These bits control if and how the Compare Output pin is
connected to Timer1.
COM1A1 COM1A0 Compare Output Mode
0 0 Disconnect Pin OC1 from
Timer/Counter 1
0 1 Toggle OC1 on compare match
1 0 Clear OC1 on compare match
1 1 Set OC1 on compare match
With these bit you can connect the OC1 Pin to the Timer and generate pulses based on the timer. It's further
described below.
PWM11/PWM10: Pulse Width Modulator select bits; These bits select if Timer1 is a PWM and it's resolution
from 8 to 10 bits:
PWM11 PWM10 PWM Mode
0 0 PWM operation disabled
0 1 Timer/Counter 1 is an 8-bit PWM
1 0 Timer/Counter 1 is a 9-bit PWM
1 1 Timer/Counter 1 is a 10-bit PWM
The PWM mode of Timer1 is dsecribed below.
TCCR1B:
Bit 7 Bit 0
ICNC1 ICES1 --- --- CTC1 CS12 CS11 CS10
ICNC1: Input Capture Noise Canceler; If set, the Noise Canceler on the ICP pin is activated. It will trigger the
input capture after 4 equal samples. The edge to be triggered on is selected by the ICES1 bit.
ICES1: Input Capture Edge Select;
When cleared, the contents of TCNT1 are transferred to ICR (Input Capture Register) on the falling edge of the
ICP pin.
If set, the contents of TCNT1 are transferred on the rising edge of the ICP pin.
CTC1: Clear Timer/Counter 1 on Compare Match; If set, the TCNT1 register is cleared on compare match. Use
this bit to create repeated Interrupts after a certain time, e.g. to handle button debouncing or other frequently
occuring events. Timer 1 is also used in normal mode, remember to clear this bit when leaving compare match
mode if it was set. Otherwise the timer will never overflow and the timing is corrupted.
CS12..10: Clock Select bits; These three bits control the prescaler of timer/counter 1 and the connection to an
external clock on Pin T1.
CS12 CS11 CS10 Mode Description
0 0 0 Stop Timer/Counter 1
0 0 1 No Prescaler (Timer Clock = System
Clock)
0 1 0 divide clock by 8
0 1 1 divide clock by 64
1 0 0 divide clock by 256
1 0 1 divide clock by 1024
1 1 0 increment timer 1 on T1 Pin falling
edge
1 1 1 increment timer 1 on T1 Pin rising
edge

OCR1
The Output Compare register can be used to generate an Interrupt after the number of clock ticks written to it. It
is permanently compared to TCNT1. When both match, the compare match interrupt is triggered. If the time
between interrupts is supposed to be equal every time, the CTC bit has to be set (TCCR1B). It is a 16-bit
register (see note at the beginning of the register section).
ICR1
The Input Capture register can be used to measure the time between pulses on the external ICP pin (Input
Capture Pin). How this pin is connected to ICR is set with the ICNC and ICES bits in TCCR1A. When the edge
selected is detected on the ICP, the contents of TCNT1 are transferred to the ICR and an interrupt is triggered.
TIMSK and TIFR
The Timer Interrupt Mask Register (TIMSK) and Timer Interrupt Flag (TIFR) Register are used to control
which interrupts are "valid" by setting their bits in TIMSK and to determine which interrupts are currently
pending (TIFR).
Bit 7 Bit 0
TOIE1 OCIE1A --- --- TICIE1 --- TOIE0 ---
TOIE1: Timer Overflow Interrupt Enable (Timer 1); If this bit is set and if global interrupts are enabled, the
micro will jump to the Timer Overflow 1 interrupt vector upon Timer 1 Overflow.
OCIE1A: Output Compare Interrupt Enable 1 A; If set and if global Interrupts are enabled, the micro will jump
to the Output Compare A Interrupt vetor upon compare match.
TICIE1: Timer 1 Input Capture Interrupt Enable; If set and if global Interrupts are enabled, the micro will jump
to the Input Capture Interrupt vector upon an Input Capture event.
TOIE0: Timer Overflow Interrupt Enable (Timer 0); Same as TOIE1, but for the 8-bit Timer 0.
TIFR is not really necessary for controlling and using the timers. It holds the Timer Interrupt Flags
corresponding to their enable bits in TIMSK. If an Interrupt is not enabled your code can check TIFR to
deternime whether an interrupt has occured and clear the interrupt flags. Clearing the interrupt flags is usually
done by writing a logical 1 to them (see datasheet).

Timer Modes
Normal Mode:
In normal mode, TCNT1 counts up and triggers the Timer/Counter 1 Overflow interrupt when it rolls over from
0xFFFF to 0x0000. Quite often, beginners assume that they can just load the desired number of clock ticks into
TCNT1 and wait for the interrupt (that's what I did...). This would be true if the timer counted downwards, but
as it counts upwards, you have to load 0x0000 - (timer value) into TCNT1. Assuming a system clock of 8 MHz
and a desired timer of 1 second, you need 8 Million System clock cycles. As this is too big for the 16-bit range
of the timer, set the prescaler to 1024 (256 is possible as well).
8,000,000/1024 = 7812.5 ~ 7813
0x0000 - 7813 = 57723 <- Value for TCNT1 which will result in an overflow after 1 second (1.000064 seconds
as we rounded up before)
So we now know the value we have to write to the TCNT1 register. So? What else? This is not enough to
trigger the interrupt after one second. We also have to enable the corresponding interrupt and the global
interrupt enable bit. Here's a flow chart of what happens:

The only steps you have to do are:


- set prescaler to 1024 (set bits CS12 and CS10 in TCCR1B)
- write 57723 to TCNT1
- enable TOIE1 in TIMSK
- enable global interrupt bit in SREG
- wait. Or do anything else. All the counting and checking flags is done in hardware.
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.
The flow chart should show an arrow from CTC1 set? "Yes" to set OCF instead of a line, but somehow the
Flow Charting Program didn't think that was a good idea. Bad luck.
Let's discuss a small example:We want the Timer to fire an int every 10ms. At 8 MHz that's 80,000 clock
cycles, so we need a prescaler (out of 16-bit range).
In this case, 8 is enough. Don't use more, as that would just pull down accuracy. With a prescaler of 8, we need
to count up to 10,000.As the value of TCNT1 is permanently compared to OCR1 and TCNT1 is up-counting,
the value we need to write to OCR is acutally 10,000 and not 0x0000-10,000, as it would be when using the
timer in normal mode.
Also, we need to set CTC1: If we didn't, the timer would keep on counting after reaching 10,000, roll over and
then fire the next int when reaching 10,000, which would then occur after 0xFFFF*8 clock cycles. That's after
0.065536 seconds. Not after 10ms. If CTC1 is set, TCNT1 is cleared after compare match, so it will count from
0 to 10,000 again with out rolling over first.
What is to be done when those 10ms Interrupts occur? That depends on the application. If code is to be
executed, the corresponding interrupt enable bit has to be set, in this case it is OCIE1A in TIMSK. Also check
that global interrupts are enabled.
If the OC1 (Output Compare 1) pin is to be used, specify the mode in TCCR1A. You can set, clear or toggle the
pin. If you decide that you want to toggle it, think about your timing twice: If you want a normal pulse which
occurs every 10ms, the timer cycle must be 5ms: 5ms -> toggle on -> 5ms -> toggle off. With the 10ms example
above and OC1 set up to be toggled, the pulse would have a cycle time of 20ms.
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 analysed a pulse. How it works?
Here's a flow chart of its basic functionality:

You see that it's actually pretty simple. I left out the low level stuff such as Interrupt validation (enabled/global
enable), as you should understand that by now. The contents of TCNT1 are transferred to ICR1 when the
selected edge occurs on the Input Capture Pin and an ISR can be called in order to clear TCNT1 or set it to a
specific value. The ISR can also change the egde which is used to generate the next interrupt.
You can measure the length of a pulse if you change the edge select bit from within the ISR. This can be done
the following way:
Set the ICES (Input Capture Edge Select) bit to 1 (detect rising edge)
When the ISR occurs, set TCNT1 to zero and set ICES to 1 to detect negative egde
When the next ISR is called, the pin changed from high to low. The ICR1 now contains the number of
(prescaled) cycles the pin was high. If the ISR again sets the edge to be detected to rising (ICES=1), the low
pulse time is measured. Now we have the high time AND the low time: We can calculate the total cycle time
and the duty cycle.
It's also possible to connect the Analog Comparator to the input capture trigger line. That means that you can
use the Analog Comparator output to measure analog signal frequencys or other data sources which need an
analog comparator for timing analysis.

PWM Mode

The Pulse Width Modulator (PWM) Mode of the 16-bit timer is the most complex one of the timer modes
available. That's why it's down here.
The PWM can be set up to have a resolution of either 8, 9 or 10 bits. The resolution has a direct effect on the
PWM frequency (The time between two PWM cycles) and is selected via the PWM11 and PWM10 bits in
TCCR1A. Here's a table showing how the resolution select bits act. Right now the TOP value might disturb you
but you'll see what it's there for. The PWM frequency show the PWM frequency in relation to the timer clock
(which can be prescaled) and NOT the system clock.
PWM11 PWM10 Resolution TOP- PWM
value Frequency
0 0 PWM function disabled
0 1 8 bits $00FF fclock/510
1 0 9 bits $01FF fclock/1022
1 1 10 bits $03FF fclock/2046

To understand the next possible PWM settings, I should explain how the PWM mode works. The PWM is an
enhanced Output Compare Mode. In this mode, the timer can also count down, as opposed to the other modes
which only use an up-counting timer. In PWM mode, the timer counts up until it reaches the TOP value (which
is also the resolution of the timer and has effect on the frequency).
When the TCNT1 contents are equal to the OCR1 value, the corresponding output pin is set or cleared,
depending on the selected PWM mode: You can select a normal and an inverted PWM. This is selected with the
COM1A1 and COM1A0 bits (TCCR1A register). The possible settings are:

COM1A1 COM1A0 Effect:


0 0 PWM disabled
0 1 PWM disabled
1 0 Non-inverting PWM
1 1 inverting PWM

Non-inverted PWM means that the Output Compare Pin is CLEARED when the timer is up-counting and
reaches the OCR1 value. When the timer reaches the TOP value, it switches to down-counting and the Output
Compare Pin is SET when the timer value matches the OCR1 value.
Inverted PWM is, of course, the opposite: The Output Compare Pin is set upon an up-counting match and
cleared when the down-couting timer matches the OCR1 value. Here are two diagrams showing what this looks
like:
The reason why you can select between inverting and non-inverting pwm is that some external hardware might
need an active-low pwm signal. Having the option to invert the PWM signal in hardware saves code space and
processing time.
The PWM is also glitch-free. A glitch can occur when the OCR1 value is changed: Imagine the PWM counting
down to 0. After the pin was set, the OCR1 value is changed to some other value. The next pulse has an
undefined length because only the second half of the pulse had the specified new length. That's why the PWM
automatically writes the new value of OCR1 upon reaching the TOP value and therefore prevents glitches.

Typical applications for the PWM are motor speed controlling, driving LEDs at variable brightness and so on.

You might also like