AVR Chapter 3
AVR Chapter 3
AVR Chapter 3
…
• V: Two’s complement overflow SREG: I T H S V N Z C
R15
indicator
• S: For signed tests
CPU R16
R17
PC
…
• H: Half Carry Flag
• T: Transfer bit used by BLD Instruction decoder R30
R31
(Bit load) and BST (Bit store) instructions Instruction Register
registers
• I: Global Interrupt Enable/Disable Flag
• In the sequence of instructions to be executed, it is
often necessary to transfer program control to a
different location. There are many instructions in AVR
to achieve this. This chapter covers the control
transfer instructions available in AVR Assembly
language.
• we discuss instructions used for looping, as well as
instructions for conditional and unconditional
branches (jumps)
BRANCH INSTRUCTIONS AND
LOOPING
• Repeating a sequence of instructions or an operation a certain
number of times is called a loop.
• The loop is one of most widely used programming techniques.
• In the AVR, there are several ways to repeat an operation many times.
• A sample Program without Loop.
LDI R16,0 ;R16 = 0
LDI R17,3 ;R17 = 3
ADD R16,R17 ;add value 3 to R16 (R16 0x03)
ADD R16,R17 ;add value 3 to R16 (R16 0x06)
ADD R16,Rl7 ;add value 3 to R16 (R16 0x09)
ADD R16,R17 ;add value 3 to R16 (R16 0x0C)
ADD R16,R17 ;add value 3 to R16 (R16 0x0F)
ADD R16,R17 ;add value 3 to R16 (R16 0x12)
Using BRNE instruction for looping
• The BRNE (branch if not equal) instruction uses the zero flag in the status register.
• It means, if it is not zero, it branches (Jumps) back to the target address referred
to by the label.
• The BRNE instruction is used as follows:
BACK: ................. ; start of the loop
......... ; body of the loop
......... ; body of the loop
DEC Rn ;decrement Rn, Z = 1 if Rn= 0
BRNE BACK ;branch to BACK if Z = 0
• In the last two instructions, the Rn (e.g., R16 or R17) is decremented; if it is not
zero, it branches (jumps) back to the target address referred to by the label.
Write a program to (a) clear R20, then (b) add 3 to R20 ten times, and
( c) send the sum to PORTB. Use the zero flag and BRNE.
Load Counter . INCLUDE “M32DEF. INC”
CLEAR R20
LDI R16, 10 ;R16 = 10 (decimal) for counter
Load R21 with 3 LDI R20, 0x00 ;R20 = 0x00
Time delay=
(250x6+3)x1μs=1503 μs
Large delay using a nested loop
R2 EQU 0x7 Time delay =
EQU 0x8 { [ (5 x 250) + 5 ] x 200 + 3
R3 - 200 – 1 } x 1 μs
D MOVLW D’200’ 1
EL MOVWF R2 1 Fall through in BNZ
AY
AGAIN MOVLW D’250’ 1
MOVWF R3 1
HERE NOP 1
NOP 1
DECF R3, F 1
BNZ HERE 2
DECF R2, F 1
BNZ AGAIN 2
RETURN 1
Toggle PORTB every 1 s.
(The crystal frequency is 10 MHz)
R2 EQU 0x2 DELAY
MOVLW D’20’ 1
R3 EQU 0x3
R4 EQU 0x4 MOVWF R4 1
BACK MOVLW D’100’ 1
MOVLW 0x55 MOVWF R3 1
MOVWF PORTB AGAIN MOVLW D’250’ 1
BACK CALL DELAY MOVWF R2 1
COMF PORTB HERE NOP 1
GOTO BACK NOP 1
DECF R2, F 1
BNZ HERE 2
DECF
Time delay = 20 x 100 x 250 x 5 x 400 ns R3, F 1
=1s AGAIN 2
BNZ
DECF R4, F 1
BNZ BACK 2