0% found this document useful (0 votes)
39 views148 pages

PT 2

Uploaded by

gprem89
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)
39 views148 pages

PT 2

Uploaded by

gprem89
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/ 148

ECED3204: Microprocessor

Part II--Assembly and C Language


Programming
Jason J. Gu
Department of Electrical and Computer Engineering
Dalhousie University

Electrical and Computer Engineering


Dalhousie University 1
Outline

i. Part II.1 AVR Assembly Language


Programming
ii. Part II.2 Hardware and Software
Development Tools for the AVR
iii. Part II.3 Advanced Assembly Programming
and Subroutine Calls
iv. Part II.4 C Language Programming

Electrical and Computer Engineering


Dalhousie University 2
Part II.1 AVR Assembly Language
Programming

Electrical and Computer Engineering


Dalhousie University 3
Outline

i. AVR Assembly Language Program Structure


ii. Memory
iii. Assembler Directives
iv. Writing Program to Perform Arithmetic
v. Write Program Loops
vi. Data Manipulation
vii. Time Delay

Electrical and Computer Engineering


Dalhousie University 4
AVR Assembly Language Program Structure
 Types of statements: assembly instructions,
assembler directives, or comments
 Statement forms: up to four fields
1. [label:] directive [arguments] [comment]
2. [label:] instruction [operands] [comment]
3. Comment
4. Empty line

Note: items placed in braces ([]) are optional.


AVR assembler is not case sensitive

Electrical and Computer Engineering


Dalhousie University 5
AVR Assembly Language Program
Structure (cont’d.)
 Label field
 Optional
 Purpose: identify a location in program memory or
identify a location in data memory
 Must begin with a letter, or _; followed by zero or
more letters, digits, and special characters (and _);
terminated by colon (:)
 Examples:
 Valid label: loop: True: _flight: ques:
 Invalid label: ,oo: 5 space:

Electrical and Computer Engineering


Dalhousie University 6
AVR Assembly Language Program
Structure (cont’d.)

 Operation field: an AVR mnemonic or an


assembler directive
 Examples: inc, add, st, ld, ldd, std, sub,adc, .def, .org
 Operand field: follows operation field; separated
by at least one space
 Operand may be a constant, a register, or a memory
location
 Example:
 Adc r10,r11 .org 0100
 St X,r0 .db 11,12,13,14,15

Electrical and Computer Engineering


Dalhousie University 7
AVR Assembly Language Program
Structure (cont’d.)
 Comment field: used to explain the function or
operation of one or more instructions
 Comment forms
; [Text]
//this is a comment line
/* this is also a comment and may span
multiple lines */
 Adc r10,r11 ; adding r10 and r11 with carry
 //following instruction does subtraction without carry
 Sub r10,r11

Electrical and Computer Engineering


Dalhousie University 8
Expressions

 To form the operand field of instruction


 To form assembler directive
 May consist of
 Operands add r5,r6
 Operators + - * / << >> >=
 Functions low(expression)
 Internally 32 bits

Electrical and Computer Engineering


Dalhousie University 9
Expressions (cont’d.)

 Operands that may be used


 User defined labels given location counter value
at place they appear
 User defined variables (set directive)
 User defined constants (equ directive)
 Integer constants
 Current value of PC

Electrical and Computer Engineering


Dalhousie University 10
Expressions (cont’d.)
 Functions, example: ldi, r28 low(ibuf)
Function Return value/description
Low (expression) low byte (least significant byte) of the given expression
High(expression) second byte of the given expression
Byte2(expression) same as high
Byte3(expression) third byte of the given expression
Byte4(expression) fourth byte (most significant byte) of the given expression
Lwrd (expression) lower word (bit 0 to 15) of the given expression
Hwrd(expression) higher word (bit 16 to 31) of the given expression
Page(expression) bit 16 to 21 of the given expression
Exp2(expression) 2**expression
Log2(expression) integer part of log2(expression)

Electrical and Computer Engineering


Dalhousie University 11
Functions (cont’d.)

Function Return value/description


Int(expression) truncates a floating-point expression to an integer
Frac(expression) extracts the fractional part of a floating-point expression
q7(expression) converts a fractional floating-point expression to a form
suitable for the fmul/fmuls/fmulsu instructions
(sign + 7-bit fraction)

q15(expression) converts a fractional floating-point expression to the form


returned by the fmul/fmuls/fmulsu instructions
(sign+15-bit fraction)

abs(expression) absolute value of the expression


DEFINED(symbol) returns true if symbol is previously defined using
.equ/.set/.def directives
STRLEN(string) length of a string constant, in bytes

Electrical and Computer Engineering


Dalhousie University 12
Expressions (cont’d.)
 Operators ~0X0F
Symbol Operation Symbol Operation
! Logical not <= Less or equal
~ Bitwise not > Greater than
 Unary minus >= Greater or equal
* Multiplication == Equal
/ Division != Not equal
+ Addition & Bitwise AND
 Subtraction ^ Bitwise XOR
<< Shift left | Bitwise OR
>> Shift right || Logical OR
< Less than && Logical AND

Electrical and Computer Engineering


Dalhousie University 13
Expressions (cont’d.)
 Formats of constants
 Accepted bases: binary, octal, decimal and
hexadecimal
 Binary constants
 Lowercase b or uppercase B suffix:
1010b, 1010B
 Lowercase b or uppercase B prefix to
single-quoted value: b'101011', B'1110111'

Electrical and Computer Engineering


Dalhousie University 14
Formats of constants (cont’d.)

 Octal constants
 Lowercase q or uppercase Q suffix:
 1234q, 1347Q
 Lowercase q or uppercase Q prefix to
single-quoted value: q'11224', Q'7654321'
 Decimal constants
 No suffix or prefix
 Lowercase d or uppercase D prefix to
single-quoted value:
 d'2345', D'9843210'

Electrical and Computer Engineering


Dalhousie University 15
Formats of constants (cont’d.)

 Hexadecimal constants
 Lowercase h or uppercase H as suffix to value
preceded by a 0:
 0ABCDEh, 0A8B30H
 0x as a prefix:
 0x1234, 0xFFFC
 Lowercase h or uppercase H prefix to
single-quoted value:
 h'3344', H'FFFC'

Electrical and Computer Engineering


Dalhousie University 16
Memory Class

 Class types:
 code memory, data memory, and EEPROM
memory
 Segment within the memory space:
 data segment, program segment, or EEPROM
segment: dseg, cseg, eseg
 Location counter assigned to each segment
during assembly process so assembler
knows next place to use

Electrical and Computer Engineering


Dalhousie University 17
Assembler Directives

Table 3.2 AVR assembler directives

Electrical and Computer Engineering


Dalhousie University 18
Assembler Directives (cont’d.)

Table 3.2 AVR assembler directives (cont’d.)

Electrical and Computer Engineering


Dalhousie University 19
Assembler Directives: Example
 .dseg ;start a new data seg
 buf: .byte 20 ;reserve 20 bytes
 …
 .cseg ;start a new code seg
 ldi XL,low(buf) ;load X register low
 ldi XH,high(buf) ;load the X register high
 .....
 //use a symbol to refer to a register. Redefine r5 as myregister

 .def myregister =r5;

Electrical and Computer Engineering


Dalhousie University 20
Assembler Directives: Example
 .device ATXMega128A1

 .cseg ; start a new code segment


 array: .db 1,2,3,4,5 ;initialize pmemory with 8-bit value
 String: .db “morning!”,0
 .dw 0, oxEEEE ;initialize pmemory with 16 bit
 // equ directive assigns a value to a label, which is a constant and can not change

. .equ TRUE=1
 // set directive assigns a value to a label, which can be changed
. .set my_offset = 0x10

Electrical and Computer Engineering


Dalhousie University 21
Macro Directive: Example

 A macro is a name assigned to a group of


instructions of directives.

 .macro add3
 add @0, @1
 adc @2,@0
 .endmacro
 Add three number together.
 @0,@1,@2 are the first,second and third marro
parameter.
 Add3 r15,r16,r17

Electrical and Computer Engineering


Dalhousie University 22
AVR Assembly Program Template
 After reserving space for handling reset
and interrupts, assembly program (using AVR
assembler) looks like:

Electrical and Computer Engineering


Dalhousie University 23
Software Development Issue

 Effective software development involves


 Systematic software development methodology
 Developing algorithms for solving problems
 Developing reusable software
 Using software tools for debugging
 Implementing good programming style
 Top down design with hierarchical refinement
 Testing

Electrical and Computer Engineering


Dalhousie University 24
Writing Programs to Perform Arithmetic
 Example: Write a program to add the 8-bit numbers
stored at data memory locations 0x20 and 0x21, and
save the sum at data memory location 0x22.
 Example: Write a program that adds 20 to data
memory locations 0x21.

.include <XXX.inc> .include <XXX.inc>


.org 0x00 .org 0x00
Jmp start Jmp start
.org 0xF6 .org 0xF6
Start: lds r1,0x20 Start: ldi r16,20
lds r2,0x21 lds r2,0x21
add r2,r1 add r2,r16
sts 0x22,r2 sts 0x21,r2

Electrical and Computer Engineering


Dalhousie University 25
Writing Programs to Perform Arithmetic
(cont’d.)

 The carry/borrow flag: SREG register bit 7


 Affected by all addition/subtraction instructions
 Set to 1 or 0 dependent on carry out
 Multiprecision addition
 Two numbers longer than 8 bits are added one byte at
a time proceeding from least significant byte (lsb) to
most significant byte (msb)

Electrical and Computer Engineering


Dalhousie University 26
Writing Programs to Perform Arithmetic
(cont’d.)
 The C flag and subtraction
 Set to 1 when subtrahend larger than minuend
 Set to 0 when minuend larger than subtrahend
 Multiprecision subtraction:
 subtraction of numbers longer than one byte for
an 8-bit microcontroller
 Multiplication and division

Electrical and Computer Engineering


Dalhousie University 27
Writing Programs to Perform Arithmetic
(cont’d.)
.include <m2560def.inc>
.cseg
.org 0x00
rjmp start
.org 0xF6
start: lds r0,0x200 ; fetch the lsbs
lds r1,0x204 ; "
Example Write a program to add add r0,r1 ; add them
the 32-bit numbers stored at data sts 0x208,r0 ; save the lsb of sum
memory locations 0x200-0x203 lds r0,0x201
and 0x204-0x207, respectively, lds r1,0x205
adc r0,r1
and store the sum at 0x208- sts 0x209,r0
0x20B. lds r0,0x202
lds r1,0x206
adc r0,r1
sts 0x20A,r0
lds r0,0x203 ; fetch the msbs
lds r1,0x207 ; "
adc r0,r1 ; add them
sts 0x20B,r0 ; save the msb of sum
// end of program

Electrical and Computer Engineering


Dalhousie University 28
Multiplication and Division (cont’d.)

Table 3.3 AVR multiply instructions

Electrical and Computer Engineering


Dalhousie University 29
Multiplication

.include <m2560def.inc>
Example Write a program to .cseg
.org 0x00
multiply the 8-bit numbers stored
rjmp start
at data memory locations 0x200 .org 0xF6
and 0x204, respectively, and store start: lds r2,0x200 ; fetch the number
the sum at 0x208-0x209. lds r3,0x204 ; "
mul r2,r3 ; multiply them
sts 0x208,r0 ; save the lsb of sum
sts 0x209,r1 ; save the msb of sum
// end of program

Electrical and Computer Engineering


Dalhousie University 30
Multiplication and Division (cont’d.)

 Fractional multiplication often used in digital


signal processing
 AVR does not provide divide instruction
 Programmer must write a subroutine to implement
division

Electrical and Computer Engineering


Dalhousie University 31
Accessing Data in Data and Program
Memory
 Accessing data stored in program memory
Step 1: Place address of data in program memory in the
Z register
Step 2: Execute an lpm or elpm instruction
lpm r1,z ;load memory content into r1

 Note:
 To access data in program memory, we need to use z register.
Since the location counter of program memory counts words instead
of bytes, a label in the program memory represents a word
address(=byte address/2). We should multiply a word address by 2
to translate it to byte address (num<<1)

Electrical and Computer Engineering


Dalhousie University 32
Writing Programs to Perform Arithmetic
(cont’d.)

.include <m2560def.inc>
.cseg
Example: Write a program to .org 0x00
rjmp start
load data from program memory .org 0xF6
and store at 0x208 start: ldi ZL, low(Parray <<1)
ldi ZH, high(Parray <<1)
// setpointer ZL,ZH, (parrary<<1)
lpm r0,Z
sts 0x208,r0

Parray: .db 11,12,13,14,15,16


.db 18,21,11,13,15,55
.db 56,78,99,77,66,55
// end of program

Electrical and Computer Engineering


Dalhousie University 33
Writing Program Loops

 The infinite loop: sequence of instructions


in which microcontroller stays forever
 Implemented with unconditional jump instructions:
rjmp, ijmp, eijmp, and jmp
 The for-loop: finite loop
 Syntax
For i = n1 to n2 do S or
For i = n2 downto n1 do S, where i is loop index

Electrical and Computer Engineering


Dalhousie University 34
Writing Program Loops

Loop: ......
......
rjmp loop

Electrical and Computer Engineering


Dalhousie University 35
Writing Program Loops (cont’d.)
 The while-loop: finite loop

Note:
- logical expression
C
- statement S

Figure 3.3 The WHILE … DO construct

Electrical and Computer Engineering


Dalhousie University 36
Writing Program Loops (cont’d.)
 The repeat-until loop: finite loop
 Repeat-S-until-C: instruction sequence below
performs operation N times

Electrical and Computer Engineering


Dalhousie University 37
Writing Program Loops (cont’d.)

Electrical and Computer Engineering


Dalhousie University 38
Shift and Rotate Instructions

Table 3.7 AVR shift and rotate instructions

Example on Board

Electrical and Computer Engineering


Dalhousie University 39
Boolean Instructions

in r16, PORTB
ori r16, 0x02
out PORTB, r16

SER Rd
Table 3.8 A summary of AVR Boolean instructions

Electrical and Computer Engineering


Dalhousie University 40
Boolean Instructions

 Example:
 in r16, portB ;read portB
 andi r16,0x0F ;clear upper 4bit
 out portB, r16 ;store back

Electrical and Computer Engineering


Dalhousie University 41
Bit Manipulating Instructions

 Used to change the value of a bit or copy a


bit from one register to another
 See Table 3.9 A summary of the AVR bit
manipulation instructions

Electrical and Computer Engineering


Dalhousie University 42
Bit Manipulating Instructions

Electrical and Computer Engineering


Dalhousie University 43
Create Time Delay Using Program Loops

 Overview
 CPU clock controls AVR instruction execution
 Each AVR instruction is completed in one to five CPU
clock cycles (See Appendix A)
 A time delay can be created by repeating a sequence
of instructions for a certain number of times.

Electrical and Computer Engineering


Dalhousie University 44
Create Time Delay Using Program Loops
(cont’d.)

 Using a program loop to create time delay


Step 1: Select sequence of instructions that take a
certain number of CPU clock cycles to execute
Step 2: Repeat the instruction sequence for an
appropriate number of times
 Loop time delays are inaccurate due to some
overhead

Electrical and Computer Engineering


Dalhousie University 45
Create Time Delay: Example
ldi r18,10
loop2: ldi r17,200 ; set external loop count to 200
loop1: ldi r16,250 ; set loop count to 250
loop0: push r0 ; 2 CPU clock cycles
pop r0 ; 2 CPU clock cycles
push r0
pop r0
push r0
pop r0
Example: create a time push
pop
r0
r0
delay of 1 second: push
pop
r0
r0
push r0
pop r0
push r0
Note: 16 MHz pop
nop
r0
; 1 CPU clock cycle
dec r16 ; 1 CPU clock cycle
brne loop0 ; take 2 (1) CPU clock cycles when branch is
taken (not taken)
dec r17
brne loop1
dec r18
brne loop2

Electrical and Computer Engineering


Dalhousie University 46
Part II.2 Hardware and Software
Development Tools for the AVR

Electrical and Computer Engineering


Dalhousie University 47
Outline

i. Hardware Development Tools


ii. Software Development Tools
iii. AVR IDE
iv. Development Tips

Electrical and Computer Engineering


Dalhousie University 48
Development Tools for the Atmel AVR

 Microcontroller development tools categories


 Hardware tools to support device programming,
program execution, and software debugging
 Software tools to allow programs to be entered,
assembled/compiled, linked, and executed.

Electrical and Computer Engineering


Dalhousie University 49
Hardware Development Tools

 Most useful hardware tools for learning AVR


MCU: microcontroller demo board, programmer, and
debug adapter
 Choosing a Demo Board for Learning the AVR
 Desirable peripheral functions: I/O ports, interrupts,
timer functions, universal asynchronous receiver
transmitter (UART) port, serial peripheral interface
(SPI), two-wire interface (TWI), A/D converter

Electrical and Computer Engineering


Dalhousie University 50
Choosing a Demo Board for Learning the
AVR (cont’d.)

 Signal pins available to the user so that he or she can


experiment with other peripheral chips
 Some people recommend using a bare kit that only
makes I/O signals available to the user
 Forces the user to do more wiring; learn more
 Difficulty may frustrate user
 Connector to connect a debug adapter or programmer
so that the user can download the program onto the
demo board for execution

Electrical and Computer Engineering


Dalhousie University 51
Hardware Development Tools (cont’d.)

 The EasyAVR M1280 Demo Boards: made by


AVRVI
 Stingray XMega Demo Board: from Xbit Inc.
 Arduino Demo Kits: open-source electronics
prototyping platform
 Debug Adapters from Atmel: AVR Dragon,
JTAGICE3, JTAGICE mkII, and AVR ONE!
 Dalhousie home made board (Lab kit)

Electrical and Computer Engineering


Dalhousie University 52
Software Development Tools

 Text editor to enter the program


 Assembler and compiler to assemble and
compile the program
 Linker to resolve variables and subroutines
cross-referencing and memory assignment
 Simulator and debugger to debug the
software
 Project manager to coordinate the overall
debug activities

Electrical and Computer Engineering


Dalhousie University 53
Software Development Tools

 Integrated development environment (IDE):


single software package that includes
assembler, compiler, linker, librarian,
simulator, debugger, and project manager

Electrical and Computer Engineering


Dalhousie University 54
Using the AVR Studio IDE (Lab1)

 Steps for developing a program


Step 1: Create a project
Start→All Programs→Atmel AVR tools→AVR Studio 6.2
Step 2: Enter the program
Step 3: Assemble (or build) the project
Syntax or semantic errors listed
Step 4: Program execution and debugging

Electrical and Computer Engineering


Dalhousie University 55
Program Execution and Debugging
(cont’d.)

 Methods to start program execution and


debugging in the AVR Studio
 Start debugging: immediately starts an emulation
session
 Start debugging and break: breakpoint set at the entry
point of the produced executable file
 Start without debugging: launches the debugging tool,
but not the emulation session

Electrical and Computer Engineering


Dalhousie University 56
Program Execution and Debugging
(cont’d.)

 Program window: yellow arrow at the left-hand side of


the points to the instruction (jmp start) at address 0x00
 Watch window: available only in debug session
 Setup watch list: track changes of variables’ values

Electrical and Computer Engineering


Dalhousie University 57
Program Execution and Debugging
(cont’d.)

 Target MCU: reset before running the program


 Breakpoint:
 address of an instruction where program execution
stops
 User can set breakpoints in start without debugging
mode and the start-debugging-and-break mode
 Properties: hit count, condition, and action

Electrical and Computer Engineering


Dalhousie University 58
Program Execution and Debugging
(cont’d.)

 Run to cursor:
 quickly find out if program executes correctly up to the
cursor position
 Stepping over instructions
 Step into: causes the MCU to execute one instruction
at a time
 Step over: if the instruction being stepped is not a call
instruction, the MCU only executes one instruction and
stops

Electrical and Computer Engineering


Dalhousie University 59
Stepping Over Instructions (cont’d.)

 Step over (cont’d.): if instruction being stepped is


a call instruction, then the MCU completes the
execution of the whole subroutine and stops at
the instruction after the call instruction
 Step out: if the MCU is executing a subroutine,
this command causes the MCU to complete the
execution of the current subroutine and return to
the caller of this subroutine

Electrical and Computer Engineering


Dalhousie University 60
Tips for Assembly Program Debugging

 Syntax and semantic errors


 Misspelling of instruction mnemonics
 Symbol not terminated with a colon character when it
is defined
 Missing operands
 Invalid register
 Undefined Symbols
 Logical errors: HARD TO FIND

Electrical and Computer Engineering


Dalhousie University 61
Tips for Assembly Program Debugging
(cont’d.)

 General debug strategy


 Determine whether the program runs correctly:
 may use the Run-to-Cursor feature to test the program
 Locate any error:
 Run-to-Cursor, single-stepping instructions, and Watch
Window may assist user
 Fix the error:
 must first identify type of error

Electrical and Computer Engineering


Dalhousie University 62
Tips for Assembly Program Debugging
(cont’d.)

 Common program logical errors


 Forgetting initializing program variables
 Using the same register for multiple variables at the
same time
 Using the wrong instruction for a certain purpose
 Operand size mismatch

Electrical and Computer Engineering


Dalhousie University 63
Common Program Logical Errors
(cont’d.)

 Missing a return instruction in a subroutine or


interrupt service routine
 Forgetting to pass parameters to the subroutine
being called
 Incorrect program algorithm

Electrical and Computer Engineering


Dalhousie University 64
Project File Structure

 AVR Studio IDE: creates a directory of the


project name under the selected directory
 Example: c:\books\avr\programs\ch04\tutor1
 AVR Studio Solution file and directory created
within this directory
c:\books\avr\programs\ch04\tutor1\tutor1
 Under this directory: Debug directory, assembly
program file (.asm extenstion), and assembler project
file

Electrical and Computer Engineering


Dalhousie University 65
Part II.3 Advanced Assembly Programming
and Subroutine Calls

Electrical and Computer Engineering


Dalhousie University 66
Outline

i. Introduction
ii. Subroutine calls
iii. Stacks
iv. Examples

Electrical and Computer Engineering


Dalhousie University 67
Introduction

 Same sequence of instructions commonly


executed in several places of the same program
 Macros: each call duplicates the same sequence of
instructions in places where the macro is invoked
increasing the program size
 Subroutine: call causes change to program flow

Electrical and Computer Engineering


Dalhousie University 68
Introduction (cont’d.)
 Most popular software development
methodology: “top-down design with
hierarchical refinement”
 Made possible by subroutine mechanism:
subroutine-call and return-from-subroutine
instructions
 Macros and subroutines support software
reuse

Electrical and Computer Engineering


Dalhousie University 69
Subroutine (cont’d.)
 When subroutine-call instruction is executed, the
processor:
 Saves the return address in the stack
 Loads the starting address of the subroutine into the
program counter
 Processor control is transferred to the subroutine
 After execution, control resumes with instruction
following subroutine call

Electrical and Computer Engineering


Dalhousie University 70
The Stack Data Structure
 Stack: data structure from which elements can
be accessed only from its top
 Uses push and pull (or pop) operations
 AVR stack grows from high address toward lower
address; stack pointer (SP) points to the byte
immediately above the top byte of the stack
 Stack memory space is limited: danger of stack
overflow and stack underflow
 Overflow: pushes data too many times, thus sp outside
the stack area
 Underflow: pop too many times, thus sp points below
bottom
Electrical and Computer Engineering
Dalhousie University 71
The Stack Data Structure (cont’d.)

 Initializing the stack pointer: must occur before


stack can be used
 Stack data structure must be created inside the on-
chip SRAM area
 Ldi temp, low(RAMED); temp is one register r16-r31
 Out SPL, temp ;initialize SP
 Ldi temp, high(RAMED)
 Out SPH, temp
 Note: SPL and SPH for Mega and CPU_SPL and
CPU_SPH for Xmega.

Electrical and Computer Engineering


Dalhousie University 72
Instructions for Stack Operation (cont’d.)

 Instructions for stack operation


 Push Rd instruction places the contents of the
Rd register at the location pointed to by the SP
and then decrements SP by 1
 Pop Rd instruction increments SP by 1 and then
copies the contents of the memory location
pointed to by the SP to the Rd register
 Example:
 Push r1
 Pop r0

Electrical and Computer Engineering


Dalhousie University 73
An Example of Subroutine

 Subroutine is a sequence of instructions that


can be called from many places of a program
 Sequence of instructions can be converted to a
subroutine by
 Adding a label (name of the subroutine) to the first
instruction of the sequence.
 Adding a ret instruction as the last instruction of the
sequence

Electrical and Computer Engineering


Dalhousie University 74
An Example of Subroutine (cont’d.)

Instruction sequence to swap r16, r17 contents:

Converted to a subroutine:

Electrical and Computer Engineering


Dalhousie University 75
Issues Related to Subroutine Calls

 Parameter passing
 Caller of the subroutine may pass parameters, using
registers (r0 to r31 used with the AVR), stack, or
global memory
 Local variable allocation and deallocation
 Use CPU registers for local variables when possible;
use stack if more space is needed
 Subroutine should deallocate stack space used by
local variables before returning to the caller

Electrical and Computer Engineering


Dalhousie University 76
Issues Related to Subroutine Calls (cont’d.)

allocate k byte from stack:

in r18,SPL
in r19,SPH ;Get the SP
sbiw r18,k ;allocate K byte
out SPL, r18
out SPH,r19

Figure 5.2 Structure of the AVR stack frame

Electrical and Computer Engineering


Dalhousie University 77
Issues Related to Subroutine Calls (cont’d.)

 Result returning
 Subroutine may return its computation result in
registers, stack, or global memory
 Accessing local variables in the stack
 Data-indirect-with displacement addressing mode
 Register usage issue
 Must avoid caller-callee interference
 Callee: subroutine being called

Electrical and Computer Engineering


Dalhousie University 78
Register Usage Issue (cont’d.)

Table 5.1 Recommendation for register usage

Electrical and Computer Engineering


Dalhousie University 79
Issues Related to Subroutine Calls (cont’d.)

Table 5.2 Subroutine call instructions

Electrical and Computer Engineering


Dalhousie University 80
Issues Related to Subroutine Calls (cont’d.)

//call K subroutine // EICALL subroutine // ICALL subroutine // RCALL subroutine


/* calls a subroutine pointed to /* calls a subroutine pointed to /* the range of constant k 11bit is
Ldi r18,0x10 by the Z pointer and the EIND by the Z pointer between -2048 and 2048. The
call loopk resister in the I/O space */ instruction allows the program to
.... */ calls a subroutine k words away.
.... ldi r30,0x12 */
Ldi r16,0x10 ldi r31,0x11 rcall looprcall
Loopk: adi r18, 5 out EIND, r16 icall ...
... ldi r30,0x12 //call the subroutine at 0x1112 ...
ret ldi r31,0x11 Looprcall:sub r30,0x12
eicall ...
//call the subroutine at 0x101112 ...
ret

Electrical and Computer Engineering


Dalhousie University 81
Writing Subroutines to Perform
Multiprecision Arithmetic

 Writing subroutines to perform 16-bit unsigned


multiplication
 To multiply two 16-bit unsigned numbers, the multiplier
and the multiplicand must be broken down into 8-bit
chunks, and four 8-bit by 8-bit multiplications are
performed
 Example:

Electrical and Computer Engineering


Dalhousie University 82
Writing Subroutines to Perform
Multiprecision Arithmetic

Electrical and Computer Engineering


Dalhousie University 83
Writing Subroutines to Perform
Multiprecision Arithmetic
Example : eg05_01.asm

Write a subroutine to multiply two unsigned 16


bit integers passed in r16:r17 and r18:r19
and return the production in r22,r23,r24,r25.
r17 and r19 hold the upper byte of two numbers
to be multiplied and r25 down to r22 hold the
most significant to the least significant bytes of
the product

Electrical and Computer Engineering


Dalhousie University 84
Writing Subroutines to Perform Multiprecision
Arithmetic (cont’d.)

 Writing a subroutine to perform 16-bit signed


multiplication
 n-bit MCU: the result of any arithmetic operation is
equal to the remainder of the initial result divided by 2n
(i.e., it is performing a modulo-2n operation)

Electrical and Computer Engineering


Dalhousie University 85
Writing a Subroutine to Perform
16-bit Signed Multiplication (cont’d.)

Four possibilities for the multiplication of signed numbers


Case 1: Both operands are positive, op1=P,op2=Q
Use unsigned multiplication
Case 2: First operand is negative -P, second operand is positive Q
-P*Q=(2n-P)*Q=2n*Q-P*Q=22n-P*Q+2n*Q
Case 3:First operand is positive P, second operand is negative -Q
P*(-Q)=P*(2n-Q)=2n*P-P*Q=22n-P*Q+2n*P
Case 4: Both operands are negative –P,-Q
(-P)*(-Q)=(2n-P)*(2n-Q)=22n-2n*P-2n*Q+P*Q=P*Q+22n-2n*P+22n-2n*Q
=P*Q+2n*(2n-P)+2n*(2n-Q)

Electrical and Computer Engineering


Dalhousie University 86
Writing a Subroutine to Perform
16-bit Signed Multiplication (cont’d.)

 N bit multiplication steps


 Step 1: Multiply two operands disregard their signs
 Step 2: If op1 is negative, then subtract op2 from the upper
half of product
 Step3: if op2 is negative, then subtract op1 from the upper
half of the product

Electrical and Computer Engineering


Dalhousie University 87
Writing Subroutines to Perform
Multiprecision Arithmetic
Example : eg05_02.asm

Write a subroutine to multiply two signed 16 bit


integers passed in r16:r17 and r18:r19
and return the production in r22,r23,r24,r25.
r17 and r19 hold the upper byte of two numbers
to be multiplied and r25 down to r22 hold the
most significant to the least significant bytes of
the product

Electrical and Computer Engineering


Dalhousie University 88
Writing Subroutines to Perform
Multiprecision Arithmetic (cont’d.)

 Writing subroutines to perform unsigned


multiprecision division
 Repeated-shift-and-subtract method: widely used
division method
 Initialization phase
 Shift-and-subtract phase

Electrical and Computer Engineering


Dalhousie University 89
Writing Subroutines to Perform Multiprecision
division: Comparison Method
start

Load dividend and divisor;


clear quotient;
first n bits of divident to P.Q. ;
init. bit counter

P.Q. Y
-divisor
>=0?

P.Q. <-- P.Q.-divisor


N

Shift P.Q. left one bit and then append


next bit of the dividend; increase bit
counter;

N Y
Done? stop

Electrical and Computer Engineering


Dalhousie University 90
Writing Subroutines to Perform
Multiprecision division

Divisor

P Q 0
01011 100010010

Set Q0 M=01011
M Subtr Shift

Control Logic
n n+1

B A
A-B
Bout

Electrical and Computer Engineering


Dalhousie University 91
Writing Subroutines to Perform Multiprecision
division: Comparison Method
B P Q operation
1 0 0 0 0 0 1 0 0 0 1 0 0 1 0 load M,Q, clear P
1 0 0 0 0 1 0 0 0 1 0 0 1 0 0 shift P.Q
1 0 0 0 1 0 0 0 1 0 0 1 0 0 0 shift
1 0 0 1 0 0 0 1 0 0 1 0 0 0 0 shift
1 0 1 0 0 0 1 0 0 1 0 0 0 0 0 shift
0 1 0 0 0 1 0 0 1 0 0 0 0 0 0 subtr.+set Q0
1 0 0 1 1 0 0 0 1 0 0 0 0 0 1 shift
0 0 1 1 0 0 0 1 0 0 0 0 0 1 0 subtr. +set Q0
1 0 0 0 0 1 0 1 0 0 0 0 0 1 1 shift
1 0 0 0 1 0 1 0 0 0 0 0 1 1 0 shift
1 0 0 1 0 1 0 0 0 0 0 1 1 0 0 shift
1 0 1 0 1 0 0 0 0 0 1 1 0 0 0

Electrical and Computer Engineering


Dalhousie University 92
Writing Subroutines to Perform
Multiprecision Arithmetic
Example : eg05_03.asm

Write a subroutine to divide an unsigned 16 bit


integer into another 16 bit unsigned integer.
Dividend and divisor are passed in r16:r17 and
r18:r19, respectively. Reminder and quotient are
to be returned in r22:r23,r24:r25, respectively.

Electrical and Computer Engineering


Dalhousie University 93
Writing a Subroutine

 Converting an internal binary number into a BCD


string
 Binary number in the computer memory must be
converted into a BCD string before being output
 BCD string uses the ASCII code to represent each
decimal digit (Skip)

Electrical and Computer Engineering


Dalhousie University 94
Writing a Subroutine to Perform
16-bit Signed Multiplication (cont’d.)

 Signed Division Operation


 One complication for signed division: must also set the
sign of the remainder
 Equation: Dividend = Quotient X Divisor + Remainder
 Correctly signed division algorithm negates the
quotient if the signs of the operands are opposite and
makes the sign of the nonzero remainder match that of
the dividend (Skip)

Electrical and Computer Engineering


Dalhousie University 95
Writing Subroutines to Perform
Multiprecision Arithmetic (cont’d.)

 Finding the square root: method based on


successive approximation

Electrical and Computer Engineering


Dalhousie University 96
Figure 5.5 Successive-approximation method for finding square root

Electrical and Computer Engineering


Dalhousie University 97
Finding the square root
Example : eg05_05.asm

Write a subroutine to implement the square


root algorithm. This algorithm will find the
square root of a 32-bit unsigned integer. The
integer is passed in r19-r16, and the square root
is returned in r22-r23.

Electrical and Computer Engineering


Dalhousie University 98
Writing a Subroutine

 Prime test subroutine


 Not extremely useful for embedded applications
 Good example for software reuse

Electrical and Computer Engineering


Dalhousie University 99
Prime Test Subroutine (cont’d.)

 Algorithm
Step 1: Let num, k, and isprime represent the number
to be tested, the loop index, and the flag to indicate if
num is a prime number
Step 2: isprime ← 0; tlimit ← square root of num;
Step 3: for k = 2 to tlimit do
if ((num % k) == 0) then return;
isprime ← 1;
return;

Electrical and Computer Engineering


Dalhousie University 100
Prime Test Subroutine (cont’d.)

Example : eg05_06.asm

Write a subroutine to determine whether an


unsigned 16 bit integer is a prime number

In this example, sqroot16 and div16u will be


reused.

Electrical and Computer Engineering


Dalhousie University 101
Subroutines with Local Variables in Stack

 Subroutine to convert a BCD string to a binary


number
 To allow the MCU to manipulate text data that
represent numeric values, they must first be
converted into binary values
 Conversion subroutine must also perform error
checking for invalid text data characters (Skip)

Electrical and Computer Engineering


Dalhousie University 102
Subroutines with Local Variables in Stack
(cont’d.)

 Bubble sort: simple, widely known, but inefficient,


sorting method
 Basic underlying idea: go through the array or file
sequentially several times; each iteration consists of
comparing each element in the array or file with its
successor (x[i] with x[i+1]) and interchanging them if
they are not in proper order (either ascending or
descending)

Electrical and Computer Engineering


Dalhousie University 103
Bubble Sort (cont’d.)
Each number bubbles up to its proper position with
each successive iteration until entire array is sorted

Electrical and Computer Engineering


Dalhousie University 104
Bubble Sort (Improved)

Example :
eg05_08.asm

Bubble sort subroutine

Electrical and Computer Engineering


Dalhousie University 105
Example

E5.8 Write a subroutine that tests whether a


number has a specified property.
The square of the sum of the upper half and
the lower half of the given number is equal to
the original number. The number to be tested is
in r16-r17, and the results (0 or 1) is returned in
register r22.

Electrical and Computer Engineering


Dalhousie University 106
Example

sumSqEqu:push r17 ; save the number to be tested


; The sumSqEqu subroutine push r16
ldi r18,100 ; separate the upper and lower two digits
tests whether the square of clr r19 ; by dividing the number by 100
call div16U ; “
the sum of the upper and add r22,r24 ; add the upper and lower halves
lower half equals the original mul r22,r22 ; compute the square of the sum
pop r16 ; get back the number to be tested
number. The number is passed pop r17 ; “
cp r0,r16 ;
in r16~r17 and the result is cpc r1,r17
returned in r22. brne false
ldi r22,1
ret
false: clr r22
ret
.include "div16U.asm"
//end of program

Electrical and Computer Engineering


Dalhousie University 107
Example
.def dlpcnt = r20
.def tmpL = r0
.def tmpH = r1
div16U: ldi dlpcnt,16 ; set up divide iteration count
movw r24,r16 ; place dividend in Q register
clr r23 ; load 0 in R register
The subroutine divides the 16-bit clr r22 ; "
dvloop: lsl r24 ; shift R:Q to the left one place
unsigned numbers contained in rol r25 ; "
r18~r19 into the 16-bit unsigned rol r22 ; "
rol r23 ; "
number contained in r16~r17 and movw tmpL,r22 ; transfer R to temporary registers
sub tmpL,r18 ; compute R - S
returns the quotient in r25~r24 sbc tmpH,r19 ; "
and the remainder in r23~r22. brmi less ; branch if divisor is larger
movw r22,tmpL ; save the difference in R
ori r24,0x01 ; set the lsb of Q to 1
rjmp nxtb
less: andi r24,0xFE ; set the lsb of Q to 0
nxtb: dec dlpcnt
brne dvloop
ret

Electrical and Computer Engineering


Dalhousie University 108
Part II.4 C Language Programming

Electrical and Computer Engineering


Dalhousie University 109
Outline

i. Introduction to C
ii. Types, Operators, and Expressions
iii. Control Flow
iv. Input and Output
v. Functions and Program Structure
vi. Pointers, Arrays, Structures, Unions, and Type
Definition
vii. Using the AVR Studio IDE to Develop C Programs
(Lab1 & Lab2)

Electrical and Computer Engineering


Dalhousie University 110
Introduction to C

 Review of the C language


 Introduction to using the C language to
program the AVR peripheral functions
 C language is quickly replacing assembly language
in every embedded application
 Improved programming productivity: allows the user to
work on program logic at a level much higher than that of
the assembly language

Electrical and Computer Engineering


Dalhousie University 111
Introduction to C: Example

(1) #include <avr/io.h>


(2) #include <util/delay.h>
(3) int main(void) //program begins
(4) {
(5) DDRB = 1<<0; //configure PORTB
(6)
(7) while(1) //stay in an infinite loop
(8) {
(9) PORTB = 0x00; //output to PORTB
(10) _delay_ms(500); //Delay 500ms
(11) PORTB = 1<<0; //output to PORTB
(12) _delay_ms(500); //delay 500ms
(13) }
(14) }

Electrical and Computer Engineering


Dalhousie University 112
Types, Operators, and Expressions

 Variable naming conventions:


 Start with a letter or underscore character followed by
zero or more letters, digits, or underscore characters
 Cannot contain arithmetic signs, dots, apostrophes, C
keywords, or special symbols
 Underscore not advisable as first character;
uppercase and lowercase letters are distinct
 Note:
 Variable must be declared before they can be used.

Electrical and Computer Engineering


Dalhousie University 113
Types, Operators, and Expressions (cont’d.)

 Data types: void, char, int, float (32bit), and


double (64 bit)
 Variable declarations: type and a list of one or
more variables of that type
 Int i,j,k;
 Constants: characters, integers, floating-point
numbers, and strings
 Constants int c=0;

Electrical and Computer Engineering


Dalhousie University 114
Types, Operators, and Expressions (cont’d.)
 Arithmetic operators

Table 6.3 Arithmetic operators in C


Example:
x= ++y;
K=5+j++;

Electrical and Computer Engineering


Dalhousie University 115
Types, Operators, and Expressions (cont’d.)

 Bitwise operators: & AND; | OR; ^ XOR;


~ NOT; >> right shift; << left shift
 Example:
 P1 = P1 & 0x40; P1 & = 0x40; //P1 8bit
 P2 = P2 | 0xFE; P2 | = 0xFE; // P2 is 8 bit
 P3 = P3 ^ 0xFF; P3 ^ = 0xFF;
 P4 = ~ P4; P4 ~ =P4;
 P5 = P5 >> 2; P5 >> =2;
 P6 = P6 << 1; P6 << =1;

Electrical and Computer Engineering


Dalhousie University 116
Relational and Logical Operators (cont’d.)
Relational and logical operators: used in expressions
to compare the values of two operands

Example:

if(!(PORTA & 0x80))


Statement;

Table 6.5 Relational and logical operators in C

Electrical and Computer Engineering


Dalhousie University 117
Types, Operators, and Expressions (cont’d.)

 Precedence of
operators: order in
which operators are
processed
 Operators at the same
level are evaluated from
left to right

Electrical and Computer Engineering


Dalhousie University 118
Control Flow

 If statement: statement associated with the if


statement executed based upon the outcome of
a condition
 If-else statement: one statement executed if a
condition is nonzero and a different statement if
the condition is zero
 Multiway conditional statement: cascaded series
of if-else statements

Electrical and Computer Engineering


Dalhousie University 119
Control Flow: Example

 if (expression)  if (k>0) return 1;


 Statement1  else if(k==0) return 0;
 else  else return -1;
 Statement 2

Electrical and Computer Engineering


Dalhousie University 120
Control Flow (cont’d.)

 Switch statement: multiway decision based on


the value of a control expression
 For-loop statement
Syntax: for (expr1; expr2; expr3)
statement;
Where expr1 and expr3 are assignments or function
calls, and expr2 is a relational expression

Electrical and Computer Engineering


Dalhousie University 121
Control Flow: Example

 Switch (index){
 sum=0;
 Case 10:
 Out=100;
 for(i=1;i<100;i++)
 Case 20:  sum=sum+i;
 Out=200;
 Case 30:
 Out=400;
 default:
 Out=0;
 }
Electrical and Computer Engineering
Dalhousie University 122
Control Flow (cont’d.)

 While statement: value of the expression is


checked prior to each execution of the statement
within the loop
 Do-while statement: body statements execute at
least once; tests the termination condition at the
end of the statement
 Goto statement: transfers control to a labeled
statement

Electrical and Computer Engineering


Dalhousie University 123
Control Flow: Example

 while (expression)  do
 statement  statement
 while(expression)
 How about this
one?
 while(1)

Electrical and Computer Engineering


Dalhousie University 124
Input and Output
 Input and output functions
 int getchar ( ): returns a character when it is called
 char abc;
 abc = getchar();
 int putchar (int): outputs a character on the standard
output device
 putchar(‘d’);
 int puts (const char *s): outputs the string pointed to
by s on the standard output device
 putchar(‘‘dddddere\n’’);

Electrical and Computer Engineering


Dalhousie University 125
Input and Output Functions (cont’d.)

− int printf (formatting string, arg1, arg2, …,


argn):
• Converts, formats, and prints its arguments on the
standard output under the control of a formatting string
• arg1, arg2, …, argn represent individual output data items

 printf(“%d,%2.1d, %3.2f, %i\n”,x1,x2,x3,x4);

Electrical and Computer Engineering


Dalhousie University 126
Table 6.8 Commonly used conversion characters for data output

Electrical and Computer Engineering


Dalhousie University 127
Functions and Program Structure
 Syntax of a function definition
return_type function_name (declarations of arguments)
{
declarations and statements
}
 Function prototype: used to declare a function
return_type function_name (declarations of arguments)
 Note:
 A function can not be called before it has been defined. This

dilemma is solved by using the function prototype statement.


 int sqroot(unsigned int y); //before main( ) is a function prototype
statement.
Electrical and Computer Engineering
Dalhousie University 128
Functions and Program Structure (cont’d.)
 Writing a C program with multiple functions
 Calling a function: write the name of the function
and replace the argument declarations by actual
arguments or values
 Example
 #include <avr\io.h>  int sqroot(unsigned int y);
 int sqroot(unsigned int y);  {
 void main(void)
 {
 int k=100;
 sqroot(k);  }
 }

Electrical and Computer Engineering


Dalhousie University 129
Pointers, Arrays, Structures, Unions, and Type
Definition
 Pointers and addresses
 Pointer: holds the address of another variable

 Example show how to declare pointer and


how to use it
 char cx, cy; //define cx and cy of char type
 char *cp; //define cp pointer of a character
 cp = &cx; //assigns the address of the variable cx to cp
 cy = *cp; //cy gets the value of cp

Electrical and Computer Engineering


Dalhousie University 130
Pointers, Arrays, Structures, Unions, and Type Definition
(cont’d.)
 Arrays: consist of multiple elements of the same
type and same storage class
 Pointers and arrays
 Array subscripting operations can also be done with
pointers
 Passing arrays to a function
 Array name used as an argument to pass an array to
a function
 Initializing arrays
 Syntax for initializing an array:
array_declarator = { value-list };
Electrical and Computer Engineering
Dalhousie University 131
Pointers, Arrays, Structures, Unions, and Type
Definition
 Initializing array
 Pointer &
 char grade[4] =
arrays {‘A’,’B’,’C’,’D’};
 int x, a[10];  int level[5] =
 int *ap; {1,2,3,4,5};
 ap = &a[0];  cmyaddress[] =“1360
 x = *ap; barrington street”;
 /*ap is the address of  char *myaddress
a[0] and x is the =“1360 barrington
content of a[0]*/
street”;

Electrical and Computer Engineering


Dalhousie University 132
Pointers, Arrays, Structures, Unions, and Type Definition
(cont’d.)

 Structures: group of related variables that can be


accessed through a common name
 Each item within a structure has its own data type
 struct point {
 int x;

 int y;

 int z;

 };

Electrical and Computer Engineering


Dalhousie University 133
Pointers, Arrays, Structures, Unions, and Type Definition
(cont’d.)

 Unions: variable that may hold (at different times)


objects of different types and sizes, with the
compiler keeping track of size and alignment
requirements
 union point {
 int x;
 int y;
 int z;
 int color;
 int thinkness;
 }

Electrical and Computer Engineering


Dalhousie University 134
Pointers, Arrays, Structures, Unions, and Type Definition
(cont’d.)

 The typedef statement: provides a capability that


enables assigning an alternate name to a data
type
 example
 typedef char letter;
 letter ax,bx,cx;

Electrical and Computer Engineering


Dalhousie University 135
Pointers, Arrays, Structures, Unions, and Type Definition
(cont’d.)

 Enumerated data types: defines a variable and


specifies the valid values that can be stored into
that variable
 example
 enum level(high, middle, low);
 To declare an enumerate type:
 enum level mylevel, hislevel, herlevel;

Electrical and Computer Engineering


Dalhousie University 136
Miscellaneous Items

 Automatic/external/static/volatile
 Automatic variables: come into existence when the
function is entered and disappear when it is left
 External variables: defined outside of any function and
thus are available potentially to many functions

Electrical and Computer Engineering


Dalhousie University 137
Miscellaneous Items (cont’d.)
 Static: when used with a local variable declaration
inside a block or a function, causes the variable to
maintain its value between entrances to the block or
function
 Volatile variable: value can be changed by something
other than user code, particularly related to PORT
definitions
 Scope rules
 The scope of a name is the part of the program within
which the name can be used

Electrical and Computer Engineering


Dalhousie University 138
Miscellaneous Items (cont’d.)

 Type casting: causes the program to treat a


variable of one type as though it contains data of
another type
 int a,b,c,d;
 double e,f;
 e=((double)a)*((double)c);

Electrical and Computer Engineering


Dalhousie University 139
Miscellaneous Items (cont’d.)

 Pointer to functions
Example: int (*funcPtr) (int kx);
 Variable funcPtr of type “pointer to function that
returns an int and that takes one int argument”
funcPtr = primeTest; // assign function name to pointer

Electrical and Computer Engineering


Dalhousie University 140
The C Preprocessor
 Preprocesor
 Part of C compilation process
 Recognizes and analyzes special statements that begin with a
pound sign, #, in first nonspace character on a line
 The #define statement: used to assign symbolic names to
program constants
 #define TOP 1000
 #define not !
 #define xor ^
 Can be used to define a macro definition
 #define CUBIC(x) x*x*x;

 y = CUBIC(x);

Electrical and Computer Engineering


Dalhousie University 141
The C Preprocessor (cont’d.)

 The ## operator: used in macro definitions to join


two tokens (a token can be a character or a
string)
 the #include statement
 #include <avr\io.h>

Electrical and Computer Engineering


Dalhousie University 142
The C Preprocessor (cont’d.)

 Conditional compilation: often used to create one


program that can be compiled to run on different
computer systems
 The #IFDEF, #ENDIF,#ELSE,#IFNDEF,#IF, and #ELIF
statements
 #if defined(YY) && YY

 #define XX 24

 #else

 #define XX 23

 #endif

Electrical and Computer Engineering


Dalhousie University 143
Using the AVR Studio C Compiler

 ATMEL AVR module types: AVR CPU core,


SRAM, Flash, EEPROM, I/O ports, and a
number of peripheral modules
 AVR peripheral register naming convention
 Peripheral register categories: control, status, and
data registers; names reflect category, e.g., CTRL and
STATUS
 counter register is names CNT
 two bytes are named CNTL, CNTH

Electrical and Computer Engineering


Dalhousie University 144
Using the AVR Studio C Compiler (cont’d.)

 AVR peripheral register bit naming convention


 Bits of a group will always have a number suffix
 Bits not part of a bit group will never have a number
suffix
 Example
 Timer/counter register D-CTRLD:

 EVACT2,EVACT1,EVACT0, EVDLY,

EVSEL3,EVSEL2,EVSEL1,EVSEL0

Electrical and Computer Engineering


Dalhousie University 145
Using the AVR Studio C Compiler (cont’d.)

 Accessing AVR Mega device peripheral registers


in C: gcc compiler uses #define statement to
associate every peripheral register with its I/O
address or memory address#
 example: definition for SPCR register:
 #define SPIE 7 //bit 7
 #define DORD 5//bit5
 #define CPOL 3//bit3
 #define SPR0 1//bit 1
Electrical and Computer Engineering
Dalhousie University 146
Using the AVR Studio IDE to Develop C
Programs

 Step 1: Create a new project to manage the


programming task
 Step 2: Enter C functions in file(s)
 Step 3: Add C files into the project
 Step 4: Compile (build) project; eliminate
syntax/semantic errors
 Step 5: Execute and debug the project
 Example
Electrical and Computer Engineering
Dalhousie University 147
Multiple-File Project

 Reasons for using multiple files


 Code reuse to reduce application development time
 Divide and conquer: allows a complex project to be
split into several smaller and manageable subprojects

Electrical and Computer Engineering


Dalhousie University 148

You might also like