You are on page 1of 202

EEE-342 Microprocessor

System and Interfacing 4(3,1)

IrfanUllah
Irfan_ullah@comsats.edu.pk
Lecturer
Room 402
Cubator 1ne
Introduction
 Course Title : EEE-342 Microprocessor Systems and Interfacing
 Prerequisite : EEE-241 Digital Logic Design
Basic Programming (C++, Java)
Small knowledge of Computer Architecture
 Department : Electrical Engineering
 Designation : Lecturer, Department of Electrical Engineering
 Contact Information : Irfan_Ullah@comsats.edu.pk
 Room Number : 402 (Cubator 1ne)
 Office Hours: :
Introduction
 Distribution of Marks:
 Theory (75%) Practical/ Laboratory Exercises (25%)
 Project 75% out of (25)% lab marks
 Recommended Books:
 AVR Microcontroller and Embedded Systems: Using Assembly and C”, by Muhammad
Ali Mazidi
 Atmel AVR Microcontroller Primer: Programming and Interfacing” By Steven F. Barrett,
Daniel J. Pack. Morgan and Claypool, 2007.
 Reference Books:
 ATMega16 Datasheet
 Embedded Systems Design with the Atmel AVR Microcontroller
Course Minimum Requirement
 80% attendance
 50% marks Theory
 80% attendance Lab
 50% marks in Lab
 Project
 4 Assignments
 4 Quiz
Rules (Most Important)
 No retake for the quiz.
 Quiz maybe announced as well as
unannounced.
 Once the Quiz is announced never be delayed
by the student.
 Assignment must be submited on time.
 No retake for sessional as well as Final Exam.
 Cheating is strongly discouraged and strict
Action will be taken against it.
Rules (Most Important)
 No excuse will be treated once quiz,
assignment or sessional is announced most
popular excuses other course burden, Project
work, Final year Project Supervisor meeting.
 Class participation is encouraged and I will
give bonus marks for it.
 Attendance will be taken at the end of
Lecture.
What is Computer?
 Perform Calculation
 On numbers
 Everything can be converted to numbers
 Follow Instruction(a Program)
 Automatic(Self-Contained)
Lecture Objectives
 Microprocessor
 AVR Microcontroller Architecture
 AVR Register
 AVR Instruction Set
 AVR Ports and I/O Operations
 Addressing Modes
 AVR Pipelining
Microprocessor
 A microprocessor incorporates the functions of a computer's central
processing unit (CPU) on a single integrated circuit (IC), or at most a few
integrated circuits.
 It is a multipurpose, programmable device that accepts digital data as input,
processes it according to instructions stored in its memory, and provides
results as output.
 It is an example of sequential digital logic, as it has internal memory.
Microprocessors operate on numbers and symbols represented in
the binary numerical system.
 Examples Intel x86(286,386,486),Pentium series, Motorola Power PC,
Advance RISC Machine (ARM) Processor .
 Microprocessor might only include an arithmetic logic unit (ALU) and a
control logic section.
Microprocessor
 The ALU performs Arithmetic operations addition, subtraction, and logical
operations AND or OR.
 Each operation of the ALU sets one or more flags in a status register, which
indicate the results of the last operation (zero value, negative number,
overflow. or others).
 Control Unit retrieves instruction operation codes from memory, and initiates
whatever sequence of operations of the ALU required to carry out the
instruction.
 A single operation code might affect many individual data paths, registers,
and other elements of the processor.
Microprocessor
 A multi-core processor is simply a single chip containing more than one
processing cores.
 This effectively multiplies the processor's potential performance by the
number of cores.
 Some components, such as bus interface and cache, may be shared
between cores.
 The cores are physically very close to each other, they can communicate
with each other much faster than separate processors in a multiprocessor
system, which improves overall system performance.
Microprocessor
Why Atmel’s AVR
Microcontroller?
1. RISC architecture with mostly fixed-length instruction, load-store
memory access, and 32 general-purpose registers.
2. A two-stage instruction pipeline that speeds up execution.
3. Majority of instructions take one clock cycle
4. Up to 20-MHz clock operation
5. Wide variety of on-chip peripherals, including digital I/O, ADC,
EEPROM, Timer, UART, RTC timer, pulse width modulator (PWM),
etc
6. Internal program and data memory
7. In-system programmable
8. Available in 8-pin to 64-pin package size to suit wide variety of
applications
9. Wide operating voltage from 2.7 V to 6.0 V.
10. Designed from the ground up for efficiency with C code
13
AVR Packaging Variations

14
AVR-ATMega16
 Atmel AVR 8-Bit Processors come in a
variety of configurations and packages
 They all share a common core – registers,
instructions, basic I/O capabilities
 Our focus is the ATMega16

15
1. AVR Microcontroller Architecture

AVR Microcontroller Architecture

 ATmega16 Features
 The high-performance, low-power Atmel 8-bit AVR RISC-based
microcontroller combines 16KB of programmable flash memory,
1KB SRAM, 512B EEPROM, an 8-channel 10-bit A/D converter

 40 – Pin Dual Inline Package (DIP)


 16 Kbytes of In-System Self-
programmable Flash program memory
 512 Bytes EEPROM
 1 Kbyte Internal SRAM
 Two 8-bit Timer
 One 16-bit Timer
 8-channel, 10-bit ADC etc.
ATMega16 Specs
 131 Instructions
 32 8-bit GP registers
 Clock speed1 MHz upto16 MHz
 16K programmable flash (instructions)
 512Bytes EEPROM
 1K internal SRAM
 Timers, serial and parallel I/O, ADC

17
Complete
Architecture

1. The CPU components are


shaded blue.
2. The memory components are
shaded green.
3. The clock components are
shaded in yellow.
4. The I/O components are
shaded in purple.
RISC VS CISC
 RISC = Reduced Instruction Set Computer.
 CISC = Complex Instruction Set Computer.
 RISC has less instructions but apparently
faster execution and less complex microcode.
 CISC has more instructions increasing the
complexity of the microcode possibly slowing
the speed.
Example
• Multiplying two numbers.
• CISC Approach
– MULT 2:3, 5:2

• RISC Approach
– LOAD A, 2:3
LOAD B, 5:2
PROD A, B
STORE 2:3, A
Summary
CISC RISC
Emphasis on hardware Emphasis on software

Includes multi-clock Single-clock,


complex instructions reduced instruction only

Memory-to-memory: Register to register:


Mostly "LOAD" and "STORE" "LOAD" and "STORE"
incorporated in instructions are independent instructions
Large code sizes
Small code sizes,
Low cycles per second,
high cycles per second

Transistors used for storing Spends more transistors


complex instructions on memory registers
Performance Equation
• The difference between CISC and RISC becomes
evident through the basic computer performance
equation:

• RISC systems shorten execution time by reducing the


clock cycles per instruction (i.e. simple instructions
take less time to interpret)
• CISC systems shorten execution time by reducing the
number of instructions per program.
AVR CPU
 PC: address of next
instruction
 IR: prefetched
instruction
 ID: current
instruction
 GPR: R0-R31
 ALU: Note internal
data path

23
Von Neumann Vs Harvard
architecture
 Harvard architecture has separate data and
instruction busses, allowing transfers to be
performed simultaneously on both busses.
 A Von Neumann architecture has only one
bus which is used for both data transfers and
instruction fetches
1. AVR Microcontroller Architecture

AVR Microcontroller Architecture


AVR Memory
 Flash: Machine
instructions go here
 SRAM: For runtime data
 Note bus independence
for data and instructions
 EEPROM: Secondary
storage
 EEPROM and Flash
memories have a limited
lifetime of erase/write
cycles

26
AVR Memories
 SRAM
 Volatile storage for working variables not held in
registers
 Flash
 Holds instructions and constant data
 Special instruction allows a byte of program memory
to be loaded into a register
 EEPROM
 Secondary storage accessed via I/O registers

27
SRAM
 The ATMega16 has 1K (1024 bytes) of byte
addressable static RAM
 This is used for variable storage and stack space
during execution
 SRAM addresses start at $0060 and go through
$045F

28
Address Space
 The AVR data address space is addressed
linearly
 Addresses $00 - $1F correspond to the 32
general purpose registers
 Addresses $20 - $5F correspond to the 64 I/O
registers
 Addresses $60 - $45F are SRAM locations

29
AVR Data Memory
The Register File
 The Register File
 32 8-bit registers

31
EEPROM
 Electrically Erasable Programmable Read
Only Memory
 Programs can read or write individual bytes
 This memory is preserved when power is
removed
 Access is somewhat slow; it serves as a form of
secondary storage

32
Program Counter(PC)

 commonly called the instruction pointer (IP)


or sometimes called the instruction address
register.
 PC holds either the memory address of the
instruction being executed, or the address of
the next instruction to be executed.
 The PC is incremented automatically after
fetching a program instruction.
Status Register (SREG)
 C: Carry Flag
 Z: Zero Flag
 N: Negative Flag
 V: Two’s complement overflow indicator
 S: N ⊕ V, For signed tests
 H: Half Carry Flag
 T: Transfer bit
 I: Global Interrupt Enable/Disable Flag
Instruction Set:
The complete collection of instructions that are understood
by a CPU (William Stallings)
Usually represented in assembly codes
Elements of an Instruction
 Operation code (Op code)
 Do this
 Source Operand reference(Rs)
 To this
 Result Operand reference(Rd)
 Put the answer here
 Next Instruction Reference
 When you have done that, do this...
Instruction Types
Math Instruction
 Add
 Subtract
 Increment
 Decrement
 Set/Clear Registers
Logical Instruction
 Logical AND
 Logical OR
 Exclusive OR
 One’s Complement
 Two’s Complement
Branch Instructions
Control Transfer Instruction
• RJMP/RCALL – Relative Jmp (+/-k)
• IJMP/ICALL – Indirect Jmp (Z Reg)
• RET/RETI – Return from call/interrupt
• CP* - Compare
• SB* - Skip if Bit in Register or I/O is set/clr
• BR* - Branch if condition is met
Data Transfer Instructions
• MOV – Move between registers
• LD/LDI – Load / Load Immediate
• ST/STI – Store / Store Immediate
• IN/OUT – In and Out Ports
• PUSH/POP – On and off stack
Bit and Bit Test
Instructions(Chapter 5)
• SBI/CBI – Set / Clear Bit in register
• LSL/LSR – Logical Shift Left / Right
(c<-MSB..LSB<-0)
• ROL/ROR – Rotate Left / Right
(<-C<-MSB..LSB<-)
• ASR – Arithmetic Shift Right
• SWAP – Swap Nibbles
• BST/BLD – Bit Store / Load
• BSET/BCLR – Set / Clear Status Bits by number
• SE*/CL* - Set / Clear Status Bits by name
Other Instructions
 NOP – Do nothing for 1 cycle
 SLEEP – Sleep until reset or interrupted
 WDR – Watch Dog Reset
AVR Instruction Set
Addition Instruction

Add Rd, Rs
Rd = Rd+Rs
Data Movement Instructions
LDS Instruction (Loading Data)
LDS Rd, Address
Data Movement Instructions
STS Instruction (Storing Data)
STS Address, Rs

IN Instruction (Loading Data)


IN Rd, (SFR Name / Address) Loads data from the I/O Space
(Ports, Timers, Configuration registers etc.) into register Rd in the
register file.
OUT Instruction (Storing Data)

 Out (SFR Name / Address), Rs. Stores data from register Rr in the
register file to I/O Space (Ports, Timers, Configuration registers
Example:
etc.).

 clr r16 ; Clear r16


 ser r17 ; Set r17
 out $18,r16 ; Write zeros to Port B
 nop ; Wait (do nothing)
 out $18,r17 ; Write ones to Port B
Data Movement Instructions

MOV Instruction (Between Registers)


MOV Rd, Rs
Other Branch Instruction
BREQ (Branch If Z = 1)
IF-ELSE Implementation in AVR Assembly
 Flow Chart
 CPI R17,Cond
 BREQ IFBLOCK
 ELSECODE
 JMP END
 IFBLOCK:
 IFBLOCKCODE
 END:
Unconditional Branch
Instruction
 JMP(Jump)
 RJMP(Relative Jump)
 IJMP(Indirect Jump)
JMP Instruction

Example:
mov r1,r0 ; Copy r0 to r1
jmp farplc ; Unconditional jump
...
farplc: nop ; Jump destination (do nothing)

PC ← k Cycles: 3
RJMP Instruction

PC - 2K +1 and PC + 2K

Cycles: 2
IJMP Instruction
Loops
Example
Nested Loops
Loops (Class Act)
 Write code in assembly for tables from 10 to
1 for 10 digits (1X1…1X10, 8X1…8X10 etc)
using nested loops. You can use maximum of
4 registers. The result is send to Port B.
Solution
INCLUDE "M32DEF.INC“
LDI R16,0xFF
OUT DDRB, R16
LDI R16,10 ;Table Digit
MULT: LDI R18,0
LDI R17,10 ; Counter for 10 time mult
COUNT: ADD R18,R16 ; Result
OUT PORTB,R18 ;Output
DEC R17
BRNE COUNT
DEC R16
BRNE MULT
Delay Calculation
 Operating Frequency 1MHz
 Time for 1 cycle = 1/1Mhz= 1us
 Branch can take 2 CC when jumps back and
takes 1 when falling through the loop.
Stack
 LIFO(Last In First Out) based stack
 Initialize stack
 Stores the CPU Info

Words: 1 (2 bytes)
Cycles: 2
Stack (Page 120)
CALL Instruction

Words: 2 (4 bytes)
Cycles: 4, devices with 16 bit PC PC ← k
5, devices with 22 bit PC
CALL Instruction
 When CALL is executed
1. Saves the address of the next instruction (below call)
in the stack.
2. Transfer control to the subroutine
3. This is how CPU knows where to return when
resume.
 PC size is of 16 bit(AtMega32,AtMega128)
1. Broken into two bytes.
2. Higher byte is pushed into the stack.
3. Lower byte is pushed into the stack.
RET Instruction
 When RET is executed
1. Top location of the stack is copied to PC.
2. Stack Pointer is Incremented.
3. This is how CPU executes the instruction below the
CALL.
 For explanation see the next example
Example 3-10 (Page 123)
Example 3-10 (Page 123)
Parallel I/O Ports
 Most general-purpose I/O devices
 Each I/O Port has 3 associated registers
1. DDRx (where “x” is A, B, C…)
 Data Direction Register Port x
 Determines which bits of the port are input and which are output
DDRB = 0x02; /* sets the second lowest of port B to output” */

2. PORTx
 Port Driver Register
PORTB = 0x02; /* sets the second bit of port B and clears the others */

3. PINx
 Port Pins Registers
 Returns the status of all 8 port B pins.
unsigned int x;
x = PINB; /* Places the status of port B into variable x */
72
Port Setup
 For output  For input
 Set corresponding bit  Clear corresponding bit
in DDRn in DDRn
 Set/clear bit in PORTn  Set/clear
to output that value corresponding bit in
PORTn to
activate/deactivate
internal pullup resistor
 Read bit in PINn

73
Input/Output Ports
 All ports initially set to input
 Must declare all output pins using DDRx
(Data Direction Registry Port x)
 Input port pins are floating. Can supply a pull-up resistor
by writing logic 1 to the corresponding bit of the port
driver register
PORTA = 0x03; /enable internal pull-ups on lowest 2 bits*/
 Port pins in output mode are typically capable of sinking
20 mA, but source much less.

74
Good Programming Practices:
Rules every programmer should know and follow.
 Comment your code such that it is clear what
you code does
 You should be able to figure out your code years
after it’s written
 A good programmer should be able to figure out
what your code does from your comments.
 Scheme comments start with ;
;this is a comment
;this is another comment
Example:
Addressing Modes:
Addressing modes are the ways how architectures specify
the address of an object it want to access.
AVR Addressing Modes
• Register Direct, with 1 and 2 registers
• I/O Direct
• Data Direct
• Data Indirect
– with pre-decrement
– with post-increment
Register Direct: 1 Register

Examples:
INC R16
CLR R22
Register Direct: 2 Registers

Examples:
ADD R16,R17
CP R22,R5
MOV R0, R1
I/O Direct

Examples:
IN R16,PIND
OUT PORTC,R16
Data Direct

Examples:
STS 0x1000,R16
Data Indirect

Examples:
LD R16, Y
ST Z, R16
Data Indirect with
Displacement

Examples:
LDD R16, Y+0x10
STD Z+0x20, R16
Data Indirect: Pre-Decrement

Examples:
LD R16, -Z
ST -Z, R16
Data Indirect: Post-Increment

Examples:
LD R16, Z+
ST Z+, R16
Pipelining
Branch Penalty
 In some circumstances CPU must flush out
the perfetched INS in queue.
 Example when Branch INS is executed.
 The CPU start to fetch code from new location
 Previous fetched code is discarded.
 Execution unit will wait for the Fetch Unit (needs extra
cycle)
I/O Bit Manipulation:
Sometime we need one or two bits instead of
the entire 8 bits.
SBI Instructions
 Set bit in the i/o register.
CBI Instructions
 Clear bit in the i/o register
Example
Example
Example
Monitor the Status of a Single
Bit
Example
Bit test instruction for reading
the status of i/o pin
Example
ADD VS ADC
SUB
Example
SUB VS SUBI
SBIW
SBC
MULTIPLICATION
DIVISION (No Division Function)
Signed and Unsigned Number
 If D7 = 0 the number is positive.
 If D7 = 1 the number is negative. (-1 to -128)

 Negative number is represented by 2’s


Complement.
How to show negative
number?
Range of sign numbers
Overflow Issue
Overflow Issue
Overflow Issue(Sign bit)
HomeTask
 Logic and Compare Instruction
 And
 Or
 Ex-or
 Com
 Neg
 Cp
Data Serialization:
Serializing data is a way of sending byte of data one
bit at a time through single pin.
ROR Instruction
ROL Instruction
Transfer of Data serially
1. Using Serial Port
 Follow RS232 serial communication protocol
 Limited Control over the sequence
2. User defined Protocol
 User can control Sequence of Data.
 The Spaces between Data.
Example
 Write a program to transfer the value 41H
serially via pin PB1. Put one high at the start
and end of the data. Send LSB first.
 41H = 0100 0001B

Packet will be
 1 0100 0001 1
Example
 Write a program that find number of 1s in a
given Byte.
LSL Instructions
LSR Instruction
ASR Instruction
Example
Assume that R20 has the number -6. Show that
the LSR command cannot be used to divide the
content of R20?
Example 5-32
Swap Instruction
BCD
 Binary coded decimal numbers.
Two types of BCD
 Unpacked BCD
 Upper 4 bit are always zeros.
 Lower 4 bits represent decimal number.
 Example: 0000 1001b = 9 , 0000 0101b =5
 Packed BCD
 A single byte represent two BCD number
 Example 1001 0101b = 9 5
 Packed BCD is twice time efficient.
ASCII Numbers
 American standard code for Information
Interchange.
 Seven bit number assigned to every
character, number and symbols.
Example 5-34
Example 5-35
ASCII to Packed BCD Conversion
Chapter 7
AVR Programming in C
 It is easier and user friendly.
 It is easier to debug and modify.
 More readability.
 C code is portable to other Platform.
Data types
Example 7-1
Example 7-2
Example 7-3
Example 7-4
Example 7-5
Time delays
 Three methods to generate time delays.
1. Using For loop
2. Predefined C function
3. Using AVR Timers
 Factor effecting the accuracy of the delay
 The duration of the Clock Period for the Instruction
Cycle.
 The compiler used to compile the C program
Example 7-7(delay using loop)
Example 7-7(delay using predefined
function)
Example 7-10 (I/O program in C)
Example 7-11 (I/O program in C)
Bit Addressable
 I/o port of AtMega series AVR are bit
addressable as we seen in assembly
language.
 But some Compiler do not support it.
 The following code is used in CodeVision
AVR but WinAVR do not support it.

 Solution : using AND OR Bit-wise Logical


Operation
Bitwise Logic Operator
Example 7-13 (Logic Operators)
Example 7-14 (Logic Operators)
Example 7-16 (Logic Operators)
Example 7-18 (Logic Operators)
Compound operator
 To reduce coding we use these operators.
Bitwise shift operation
 Two operators
 Improve code clarity.
Example 7-23 (same 7-18)
Example 7-25
Example 7-26
Example 7-27
Class Activity
Chapter 8 AVR Hardware
Connection
Reset Pin
 Active low.
 Stable clk src
 Stable Voltage
AVR Fuse Bits and Lock Bits
 Fuse bits are used to select or eliminate the
need for external component
 If a fuse bit is incorrectly programmed, it may coz the
system to fail i.e. SPIEN = 0. disable SPI programming
mode.

 Lock Bits are used to restrict access to flash


memory.
 Code Protection.
 After locking you are not able to read or verify.
 Not recommended at development stage.
FUSE Bits
FUSE Bits
Clock Sources
FUSE Bits (CKSEL0…3)
 These are used to select the Clk Src.
 Default choice is Internal RC(0001).
 No need for an external Crystal or Capacitors.
 An internal RC oscillator can cause 3% inaccuracy
 Therefore not recommended.
External RC Oscillator
 F = 1/ 3RC
 You can replace R by potentiometer for variable clock.
 Minimum value for C = 22 pF. You may enable program
internal 36pF capacitor b/w XTAL1 and Gnd and remove
external capacitor.
External Crystal Oscillator
 CKSEL0…3 = 0000. we can use external
clock source.
Fuse Bits(FB) for reset Delay
 CPU needs stable clock source and voltage
level to work properly.
 Short delay after reset allow the power to
become stable.
 The delay time is set by SUT1,SUT0 and
CKSEL0 table 8.11.
Brown out detector
 The power source provided to Vcc Pin fluctuates
causing the CPU to malfunction.
 Brown out detection is used to overcome this
problem.
 BOD circuit can compare Vcc with BOD level
and reset the chip if Vcc Fall below it.
 BOD Level = 2.7 when BOD Level (FB) =1
 BOD Level = 4 when BOD Level (FB) =0
 BOD circuit is enable by BODEN (FB)
Recommended settings
 If you are using external setting with
frequency >1 MHz.
 CKSEL3,CKSEL2,CKSEL1,SUT1,SUT0 = 1.
 CKOPT = 0.
Loading Program in AVR
 Three Methods to load a program
1. Parallel Programming
 Device burner is used to load the program into uC.
2. In circuit Serial Programming(ISP)
 It allows the developer to program and debug their uC
while it is in the system e.g. SPI(3 pins),JTAG.
 JTAG provide more freedom in addition to programing
you can trace your program line by line and watch the
changes in the memory location, ports or registers
while your program is running .
Loading Program in AVR
3. Boot Loader
 A boot loader is a peace of code burn into the uC.
 Its purpose is to communicate with the user
board to load the program.
 It can communicate via serial port, CAN port, USB
port or even Ethernet connection. It can also used
to debug a system like JTAG.
 This method is helpful for the developer who do
not have device programmer or JTAG connection.
AVR Timer
Counter Register
 Many application need to count an event.
 We connect the external event srs to the clk
pin of the counter register.
 When an event occur, the content of the
counter is incremented automatically.
Counter as Time delay
 If the oscillator frequency is known calculate
the time period and multiply it with the
content of the counter.
 Clear the counter
 Wait until the counter reached a certain
number for example
 uC having oscillator frequency 1MHz
 The content of the counter register incremened once
per u.second.
 Required delay is 100 us then wait until counter
reaches 100.
Question
 What is the difference between normal
register and counter register?
Properties of Timers
1. Timer works independently of CPU.
2. It can be used to measure time accurately.
3. Upon certain conditions take some action automatically or inform
CPU.
• One of the basic condition is the situation when timer
OVERFLOWS i.e. its counted up to its maximum value (255 for 8
BIT timers) and rolled back to 0. In this situation timer can issue
an interrupt and you must write an Interrupt Service Routine
(ISR) to handle the event.
AVR Timer/Counter 0
 Resolution is 8 Bit
 Three related registers
1. TCNT0 (Timer Counter)
2. TCCR0 (Timer Counter Control Register)
3. OCR0 (Output Compare Register)
 Two flags
1. TOV0 (Timer Overflow Flag)
2. OCF0 (Output Compare Flag)
AVR Timer/Counter 0
 The timer register are located in the I/O
Register memory
 How we can access them in assembly?
 You can access it with the help of IN and
OUT Instruction
TCCR0
Prescaler
TIFR (Timer Counter Interrupt
Flag Register)
TOV0
 The flag is set when counter overflow.
 It remain set until the software clear
it(manually).
 In order to clear we need to write 1 to it.
Normal Mode
1. Load the TCNT0 with the initial value.
2. Configure TCCR0 register.
3. Keep monitoring TOV0 flag to see if it is
raised.
4. Stop the timer by TCCR0 = 0.
5. Clear TOV0.
6. Go back to step 1.
Example
Largest time delay
XTAL=8Mhz
 00 FF
 Total iteration 255 then 1 more for role back.
 256 * 0.125 us = 32 us
 Smallest frequency 1/(2* 32us) = 15.624 KHz
 What if we need more time delay ?
1. Multiple call to delay
2. Prescaling the clock
3. Using 16 bit timer
CTC Mode
Clear timer on Compare match
1. Load value in OCR0

2. Clear TCNT0

3. Configure TCCR0 register for CTC mode.

4. Keep monitoring OCF0 flag to see if it is


raised.
5. Stop the timer by TCCR0 = 0.

6. Clear OCF0
Example
 OCR0 = 9
 Xtal = 8MHz
 50% duty cycle PB3
 Timer CTC Mode
 Total delay =?
 T CCs= 9+1= 10
 Time = 10* 0.125us = 1.25us
Example 9-21
Important Note
 When CTC mode is used
 If we load value of OCR0=89 < TCNT0=95
 The Counter miss Compare Match.
 Count up to max Value 0xFF and rolls over
 Problem?
AVR Timer/Counter 2
 Resolution is 8 Bit
 Three related registers
1. TCNT2 (Timer Counter)
2. TCCR2 (Timer Counter Control Register)
3. OCR2 (Output Compare Register)
 Two flags
1. TOV2 (Timer Overflow Flag)
2. OCF2 (Output Compare Flag)
Difference Timer0 and Timer2
 Timer 2 can be used as real time counter
 Connect crystal 32.768KHz at TOSC1 and TOSC2

 When CS02—CS01 have values 110 or 111,


select between different scale of clock rather
then counting external event.
TCCR2
Example 9.25 Timer2
AVR Timer/Counter 1
 16 Bit resolution.
 Five 16-bit related registers
1. TCNT1(H,L) (Timer Counter)
2. TCCR1(A,B) (Timer Counter Control Register)
3. OCR1B(H,L) (Output Compare Register)
4. OCR1A(H,L) (Output Compare Register)
5. ICR1(H,L) (Input Capture Register)
 Two flags
1. TOV1 (Timer Overflow Flag)
2. OCF1A (Output Compare Flag)
3. OCF1B (Output Compare Flag)
Block Diagram Timer1
Timer1 Control Register
Example
 Xtal =8 MHz
 Tclk = 1/8MHz =0.125us
 Prescaler = 256 Tclk =0.125*256 = 32us
 Req Cyc =1s/32us = 0x7A12
 Value to be loaded in TCNT?
 FFFF +1 – 0x7A12 = 0x85EE
Calculating TCCR value
 Normal Mode, Prescaler = 256
 TCCR1A = 00000000 = 0x00
 TCCR1B = 00000100 = 0x04
Example 8-42 C Code

You might also like