You are on page 1of 129

ARM CortexM3(i)

Department of Electronics
Academic Year 2014/15
(ver 12-09-2014)
Topic 2
Cortex M3 Processor: Software Tips
Digital Electronic Systems
Department of Electronics
2.1. Introduction to Cortex-M3
3.1.1. ARM Overview
3.1.2. ARM Cortex-M3 Processor
2.2. Programmers Model and Registers
2.2.1. General Purpose Registers (GPRs)
2.2.2. Stack Pointer, Link Register and Program Counter (SP,LR,PC)
2.2.3. Special Registers (SRs)
2.3. Operation Modes and Privilege Levels
2
Index
Digital Electronic Systems
Department of Electronics
2.4. Instruction Overview and Addressing Modes
2.4.1. Assembler Basics
2.4.2. Addressing Modes
2.5. Instruction Descriptions
2.5.1. Moving Data
2.5.2. Processing Data
2.5.3. Branches
2.5.3. Instruction Set
2.6. Stack
2.7. I/O Ports
3
Index
Digital Electronic Systems
Department of Electronics
First ARM was developed by Acorn RISC Machine (1983-1985)
From a first design by Berkeleys students (Berkeley RISC I)
In 1990 the firm becomes Advanced RISC Machines Ltd.
English firm founded by Apple Comp., Acorn Comp. Group and VLSI Technology
Nowadays ARM Ltd.
The company is only dedicated to develop RISC processors
One of the best known companies in the world in this topic
Develops 75% of embedded RISC processors for the world market
4
2.1 Introduction
Digital Electronic Systems
Department of Electronics
ARM Ltd does not produce processors, it only designs them
then it gives licenses to produce them
Example: ARM technology is used in their chips by: Philips, Atmel,
Freescale (previously produced by Motorola), Cirrus Logic, Hyundai, Intel,
Oki, Samsung, Sharp, Lucent, 3Comp, HP, IBM, Sony,
5
2.1 Introduction
Digital Electronic Systems
Department of Electronics
ARM is a:
RISC Microprocessor (P)
17/18 32 bit visible registers in its programmers model (37 total)
Cache Memory (depending on the version)
Von Neuman architecture (ARM7)
Harvard architecture (ARM9 and forward)
6
2.1 Introduction: ARM Overview
Digital Electronic Systems
Department of Electronics
The first of the Cortex generation of processors released by ARM
In 2006, 32-bit microcontroller
Improved code density
Can be easily programmed using the C language
Greater performance efficiency: more work without increasing frequency or power
Low power consumption: enabling longer battery life, critical in portable products
The Cortex-M3 processor builds on the success of the ARM7
Nonmaskable interrupts for critical tasks
Deterministic nested vector exceptions
Atomic bit manipulation
Optional Memory Protection Unit (MPU)
7
2.1 Introduction: ARM Cortex-M3Processor
Digital Electronic Systems
Department of Electronics
Background of ARM and ARM Architecture
8
2.1 Introduction: ARM Cortex-M3Processor
Digital Electronic Systems
Department of Electronics
ARM v7 Processor Profiles
A Profile (ARMv7-A):
Processors to handle complex applications such as high-end embedded operating
systems
These processors require the highest processing power, virtual memory system support
with Memory Management Units (MMUs)
Example: mobile phones
R Profile (ARMv7-R):
High-performance processors targeted for real-time applications
M Profile (ARMv7-M):
Processors targeting low-cost applications in which processing efficiency is important and
cost, power consumption, low exception latency, and ease of use are critical
Specially indicated for industrial control applications, including real-time control
systems
9
2.1 Introduction: ARM Cortex-M3Processor
Digital Electronic Systems
Department of Electronics
ARM Cortex-M3 Processor Applications
Low-cost microcontrollers
Automotive
Data communications
Industrial control
Consumer products
10
2.1 Introduction: ARM Cortex-M3Processor
Digital Electronic Systems
Department of Electronics
ARM Cortex-M3 Based uC
11
2.1 Introduction: ARM Cortex-M3Processor
Digital Electronic Systems
Department of Electronics
About the programmers model
12
2.2 Programmers Model and Registers
Digital Electronic Systems
Department of Electronics
13
2.2 Programmers Model and Registers
Data types supported by
the processor
32-bit words
16-bit halfwords
8-bit bytes
Digital Electronic Systems
Department of Electronics
Registers:
Cortex-M3 processors have sixteen 32 bit registers R0 to R15
R0 to R12: General-Purpose Registers GPRs
R13 is the Stack Pointer (SP): it is banked, with only one R13 visible at a time
R14 is the Link Register (LR): used in subroutines and exception handlers
R15 is the Program Counter (PC)
General-Purpose Registers (GPRs): Low and High GPRs
Low Register are R0 to R7: They can be accessed by all 16-bit Thumb
instructions and all 32-bit Thumb-2 instructions.
High Registers are R8R12: They are accessible by all Thumb-2 instructions but
not by all 16-bit Thumb instructions
14
2.2 Programmers Model and Registers: GPRs
Digital Electronic Systems
Department of Electronics
Registers R13: Stack Pointers (SPs)
Cortex-M3 contains two stack pointers, named R13
Main Stack Pointer (MSP)
Process Stack Pointer (PSP)
They are banked so that only one is visible at a time depending on the processor
privilege level
When using the register name R13, you can only access the current stack pointer
The lowest two bits in the stack pointers are always 0, which means they are
always word aligned
15
2.2 Programmers Model and Registers: SP
Digital Electronic Systems
Department of Electronics
Register R14: Link Register (LR)
Inside an assembler program, it is written as either R14 or LR
LR is used to store the return PC when a subroutine or function is called
Subroutines are part of source code within a larger program, that perform a specific
task, and can be called from different places during the execution of the program
(functions in high-level programming languages)
They are used when a part of the source code is repeated several times:
STRUCTURED PROGRAMMING.
A call instruction is used in the source code where the subroutine has to be
executed. The returning address from the subroutine is saved in order to continue
with the next instruction that follows the call instruction (return PC).
To finish the subroutine, a return instruction is executed.
16
2.2 Programmers Model and Registers: LR
Digital Electronic Systems
Department of Electronics
Register R14: Link Register (LR)
The return address could be saved:
o In specific registers: The nesting depth is limited, but the returning process is
faster.
o In memory: There is a memory area reserved for saving return address.
For example, when using the BL -branch with link- instruction
main ;Mainprogram

BLfunction1 ;Callsfunction1usingBranchwithLinkinstruction
;PC=function1andLR =thenextinstructioninmain

function1
;Programcodeforfunction1
BX LR ;Return
LR has to be manually stored to correctly perform nested subroutines
17
2.2 Programmers Model and Registers: LR
Digital Electronic Systems
Department of Electronics
Register R14: Link Register (LR)
For example, when using the BL -branch with link- instruction
main ;Mainprogram

BLfunction1 ;Callsfunction1usingBranchwithLinkinstruction
;PC=function1andLR =thenextinstructioninmain

function1
;Programcodeforfunction1
BX LR ;Return
LR has to be manually stored to correctly perform nested subroutines (to call a
subroutine from another).
18
2.2 Programmers Model and Registers: LR
Digital Electronic Systems
Department of Electronics
Register R15: Program Counter (PC)
Inside an assembler program, it is written as either R15 or PC
When reading its value we obtain the current instruction address plus 4
(because of the pipelined nature of the Cortex-M3 processor). For example:
0x1000: MOV R0,PC ;R0 =0x1004
Writing to the PC will cause a branch (but LRs do not get updated)
Since an instruction address must be half word aligned, the LSB (bit 0) in the PC
is always 0
19
2.2 Programmers Model and Registers: PC
Digital Electronic Systems
Department of Electronics
Special Registers:
They have special functions and can be accessed only by special instructions
They cannot be used for normal data processing
20
2.2 Programmers Model and Registers: SRs
Digital Electronic Systems
Department of Electronics
Program Status Registers: PSRs
Provide ALU flags (zero flag, carry flag), execution status, and current executing
exception number.
Subdivided into three status registers:
Application PSR (APSR)
Interrupt PSR (IPSR)
Execution PSR (EPSR)
21
2.2 Programmers Model and Registers: SRs
Digital Electronic Systems
Department of Electronics
Program Status Registers: APSR, IPSR
22
2.2 Programmers Model and Registers: SRs
Digital Electronic Systems
Department of Electronics
Program Status Registers: EPSR
Two overlapped fields: ICI and IT
Interruptible-continuable instruction field, ICI
Load Multiple (LDM) operations and Store Multiple (STM) operations are interruptible
ICI field holds the information required to continue LDM or STM from the interrupted point
If-then state field, IT
IT field contains the execution state bits for the If-Then instruction (see in the table)
The EPSR is not directly accessible. Two events can modify it:
An exception occurring during an LDM or STM instruction
Execution of the If-Then instruction
23
2.2 Programmers Model and Registers: SRs
Digital Electronic Systems
Department of Electronics
Program Status Registers: EPSR
24
2.2 Programmers Model and Registers: SRs
Digital Electronic Systems
Department of Electronics
Program Status Registers
PSRs can be accessed:
With the name xPSR when they are accessed as a collective item
Separately with the names APSR, IPSR and EPSR
Reading all PSRs is possible by using the MRS instruction
Writing APSR is possible by using the MSR instruction. EPSR and IPSR are read-
only
For example:
MRS r0,APSR ;ReadFlagstateintoR0
MRSr0,IPSR ;ReadInterruptstate
MRSr0,EPSR ;ReadExecutionstate
MSRAPSR,r0 ;WriteFlagstate
25
2.2 Programmers Model and Registers: SRs
Digital Electronic Systems
Department of Electronics
Interrupt Mask Registers:
PRIMASK: Disable all exceptions except the nonmaskable interrupt (NMI) and Hard
Fault exception
FAULTMASK: Disable all exceptions except the NMI. Changes the priority level to -1
BASEPRI: Disable all exceptions of a specific priority or lower priority level
26
2.2 Programmers Model and Registers: SRs
Digital Electronic Systems
Department of Electronics
Interrupt Mask Registers
They are accessed with MRS and MSR instructions
For example:
MRSr0,BASEPRI ;ReadBASEPRIregisterintoR0
MRS r0,FAULTMASK ;ReadFAULTMASKregisterintoR0
MSR PRIMASK,r0 ;WriteR0into PRIMASK register
They cannot be set in the user access level
Control Register: CONTROL
Used to define the stack pointer selection and the privilege level
Well study the Control Register in the following section
27
2.2 Programmers Model and Registers: SRs
Digital Electronic Systems
Department of Electronics
The Cortex-M3 processor has two privilege levels:
User level: Unprivileged, execution limits or excludes access to some resources
Privileged level: execution has access to all of the resources
Also it has two operation modes:
Thread mode
Is entered on Reset, and can be entered in an exception return
Thread mode can be privileged or user
Handler mode
Is entered as a result of an exception
Handler mode is always privileged
28
2.3. Operation Modes and Privilege Levels
Digital Electronic Systems
Department of Electronics
If changed from privileged to user in Thread mode, it cannot change back
to privileged
Only in Handler mode the privilege of Thread mode can be changed
Once it enters the user level, the only way to switch back to privileged is
by triggering an exception and changing this in the exception handler
29
2.3. Operation Modes and Privilege Levels
Digital Electronic Systems
Department of Electronics
The privilege level is set in the Control Register:
Used to define the stack pointer selection and the privilege level
CONTROL register is accessed with MRS and MSR. For example:
MRSR0,CONTROL ;ReadCONTROLregisterintoR0
MSRCONTROL,R0 ;WriteR0intoCONTROLregister
30
2.3. Operation Modes and Privilege Levels
Digital Electronic Systems
Department of Electronics
31
2.3. Operation Modes and Privilege Levels
User Level
Thread
Thread
Handler
Exception
RESET
Summary
Digital Electronic Systems
Department of Electronics
The privilege level in a generic processor
Example
Needed to implement operating system (OS) based
apps
Some bits in a special register define the privilege level
At least 2 levels:
User level: accessed by user apps
Without access to hardware
OS calls (TRAP, Service Call) are needed
Privileged level: accessed by OS apps
Exception Handlers: Access to hardware through
peripheral drivers
Other OS app
32
2.3. Operation Modes and Privilege Levels
HARDWARE
Final User App
OS App
Exception
OS App
OS Call OS Call
Privileged
Level
User Level
Thread
Thread
Handler
Digital Electronic Systems
Department of Electronics
The Instruction Set
The Cortex-M3 supports Thumb (16-bit instructions) and Thumb-2 (32-bit
instructions) instruction sets
Thumb-2 instruction set
32-bit and 16-bit instructions can be used together for high code density and high
efficiency
It is flexible, powerful and easy to use
It is possible to handle all processing requirements in one operation state
Is a superset of the previous 16-bit Thumb instruction set
33
2.4 Instruction Overview and Addressing Modes
Digital Electronic Systems
Department of Electronics
Assembler Language: Basic Syntax
The following instruction formatting is commonly used:
label:opcode operand1,operand2,...;Comments
The number of operands in an instruction depends on the type of instruction
The operand syntax format can also differ from operands (e.g. with immediate data)
The opcode can be followed by a suffix
Conditional execution suffixes are usually used for branch instructions
Other instructions can also be used with the conditional execution suffixes (inside an IF-THEN
instruction block)
34
2.4.1 Instruction Overview: Assembler
Digital Electronic Systems
Department of Electronics
Assembler Language: Unified Assembler Language syntax
Unified Assembler Language (UAL) developed to support Thumb-2 instruction set
It allows selection of 16-bit and 32-bit instructions
An example of using UAL or not:
ADDR0,R1 ;R0=R0+R1,usingTraditionalThumbsyntax
ADDR0,R0,R1 ;EquivalentinstructionusingUALsyntax
The traditional Thumb syntax can still be used
With Thumb instruction syntax, some instructions change the flags in APSR,
even if the S suffix is not used. For example:
AND R0,R1 ;TraditionalThumbsyntax
ANDSR0,R0,R1 ;EquivalentUALsyntax(Ssuffixisadded)
35
2.4.1 Instruction Overview: Assembler
Digital Electronic Systems
Department of Electronics
UAL size suffixes
Specify which instruction you want by adding N and Wsuffixes:
ADDS R0,#1 ;Use16bitThumbinstructionbydefaultforsmallersize
ADDS.NR0,#1 ;Use16bitThumbinstruction(N=Narrow)
ADDS.WR0,#1 ;Use32bitThumb2instruction(W=wide)
If no suffix is given, the assembler tool can choose either instruction, but usually
defaults to 16-bit Thumb code to get a smaller size
Depending on the tool support, you may also use the .N (narrow) suffix to specify a
16-bit Thumb instruction
In most cases, applications will be coded in C, and then compilers will use 16-bit
instructions if possible due to smaller code size
Nevertheless, 32-bit Thumb-2 instruction are used
With immediate data that exceeds a certain range
When the operation can be better handled with the 32-bit instruction
36
2.4.1 Instruction Overview: Assembler
Digital Electronic Systems
Department of Electronics
32-bit Thumb-2 instructions can be half word aligned
For example:
0x1000: LDRR0,[R1] ;a16bitinstructions(occupy0x10000x1001)
0x1002: ADDSR0,R0,R1 ;a32bitThumb2instruction(occupy0x10020x1005)
37
2.4.1 Instruction Overview: Assembler
Dir. Opcode Mnemotcnico
Digital Electronic Systems
Department of Electronics
Cortex-M3 supports the following addressing modes:
Immediate
Register (Direct to Register)
Indirect
Offset or Base+Offset (Indirect & Indirect+Offset)
Indexed or Base+Index+Offset
Pre-indexed
Post-indexed
PC-relative
38
2.4.2 Instruction Overview: Addressing Modes
Digital Electronic Systems
Department of Electronics
Immediate
Data is the operand
Syntax is: #number
Can only be used for the source operand
Usable in any type of instruction
For example:
ADDR0,#0x12 ;R0=R0+0x12(hexadecimal)
MOVR1,#A ;SetR1=ASCIIcharacter A
If transferring a 32-bit operand, LDR can be used with a different syntax:
For example:
LDRR1,=0x10200000;SetR1=0x10200000
39
2.4.2 Instruction Overview: Addressing Modes
Digital Electronic Systems
Department of Electronics
Register (Direct to Register)
Data is INTO a register: EA = Rx
Syntax is: Rx
Usable in any type of instruction
For example:
MSRCONTROL,R12 ;SetCONTROL=R12
ADDR0,R1 ;R0=R0+R1
40
2.4.2 Instruction Overview: Addressing Modes
Digital Electronic Systems
Department of Electronics
Immediate and direct to register addressing mode simulation
41
2.4.2 Instruction Overview: Addressing Modes
Digital Electronic Systems
Department of Electronics
Indirect
Data is INTO the memory address pointed by a register: EA = content of Rx
Syntax is: [Rx]
ONLY applicable in transfer instructions with LDR and STR
For example:
LDRR0,[R3] ;SetR0 =contentofmemoryaddresspointedbyR3
STRR3,[R2] ;SetcontentofmemoryaddresspointedbyR2 =R3
42
2.4.2 Instruction Overview: Addressing Modes
Digital Electronic Systems
Department of Electronics
Indirect addressing mode simulation
43
2.4.2 Instruction Overview: Addressing Modes
Before simulation
After simulation
Digital Electronic Systems
Department of Electronics
Offset or Base+Offset (Indirect+Offset)
Data is INTO the memory address as follows: EA = content of Rx + offset
Syntax is: [Rx,#offset]
The register is unaltered
ONLY applicable in transfer instructions with LDR and STR
Useful to get parameters within a table
For example:
LDRR0,[R1,#24] ;SetR0=contentofmemoryaddresspointedbyR1+24
LDRR0,[SP,#4] ;SetR0=contentofmemoryaddresspointedbySP+4
44
2.4.2 Instruction Overview: Addressing Modes
Digital Electronic Systems
Department of Electronics
Offset or Base+Offset addressing mode simulation
45
2.4.2 Instruction Overview: Addressing Modes
Before simulation
After simulation
Digital Electronic Systems
Department of Electronics
Indexed or Base+Index(shifted)
Data is INTO the memory address as follows: EA = content of Rx + RIndex(shifted)
Syntax is: [Rx,RIndex,LSL#n] ; n=1,2,3 to shift RIndex before EA is obtained
Both registers are unaltered
ONLY applicable in transfer instructions with LDR and STR
For example:
LDRR0,[R1,R2,LSL#2];SetR0=contentofmemoryadd.pointedbyR1+R2*4
46
2.4.2 Instruction Overview: Addressing Modes
Digital Electronic Systems
Department of Electronics
Indexed or Base+Index(shifted) addressing mode simulation
47
2.4.2 Instruction Overview: Addressing Modes
= 0x10000000 + 4 x 4
Digital Electronic Systems
Department of Electronics
Pre-indexed
Data is located in the same EA as in Indirect+Offset: EA = content of Rx+offset
Syntax: [Rx,#offset]!
The register IS ALTERED BEFORE the access is performed
ONLY applicable in transfer instructions with LDR and STR
For example:
LDRR0,[R2,#2]! ;SetR2=R2+2
;SetR0 =contentofmemoryadd.pointedbyR2+2
STRD.WR0,R1,[R2,#0]! ;SetR2=R2+0
;Setthecontentofmemoryadd.pointedbyR2+0 =R0
;Setthecontentofmemoryadd.pointedbyR2+0+4 =R1
48
2.4.2 Instruction Overview: Addressing Modes
Digital Electronic Systems
Department of Electronics
Pre-indexed addressing mode simulation
49
2.4.2 Instruction Overview: Addressing Modes
Before simulation
After simulation
Digital Electronic Systems
Department of Electronics
Post-indexed
Data is located in the same EA as in Indirect: EA = content of Rx
Syntax: [Rx],#offset
The register IS ALTERED AFTER the access is performed
ONLY applicable in transfer instructions with LDR and STR
For example:
LDRR0,[R2],#2 ;SetR0=contentofmemoryadd.pointedbyR2
;SetR2=R2+2
50
2.4.2 Instruction Overview: Addressing Modes
Digital Electronic Systems
Department of Electronics
Post-indexed addressing mode simulation
51
2.4.2 Instruction Overview: Addressing Modes
Before simulation
After simulation
Digital Electronic Systems
Department of Electronics
Multiple transfers with Pre-indexed and Post-indexed
With LDM and STM instructions
Operates similarly and uses similar syntax
Suffix IA (increment after) indicates post-index
Suffix DB (decrement before) pre-index
With ! the register IS ALTERED after the instruction is completed
For example:
LDMIA.WR0!,{R2,R5} ;SetR2=contentofmemoryadd.pointedbyR0
;R0 =R0 +4
;SetR5=contentofmemoryadd.pointedbyR0
;R0 =R0 +4
STMDB.WR0!,{R2R4} ;SetR0=R0 4,andcontentofmemoryadd.pointedbyR0 = R4
;SetR0=R0 4,andcontentofmemoryadd.pointedbyR0 =R3
;SetR0=R0 4,and contentofmemoryadd.pointedbyR0 =R2
52
2.4.2 Instruction Overview: Addressing Modes
Digital Electronic Systems
Department of Electronics
Multiple transfers with Post-indexed addressing mode simulation (with !)
53
2.4.2 Instruction Overview: Addressing Modes
Before simulation
After simulation
Digital Electronic Systems
Department of Electronics
Multiple transfers with Pre-indexed and Post-indexed
Without ! the register IS NOT ALTERED after the instruction is completed
For example:
LDMIA.WR0,{R2,R5} ;SetR2=contentofmemoryadd.pointedbyR0
;SetR5=contentofmemoryadd.pointedbyR0 +4
STMDB.WR0,{R2,R5} ;Setcontentofmemoryadd.pointedbyR0 4=R5
;Setcontentofmemoryadd.pointedbyR0 8=R2
54
2.4.2 Instruction Overview: Addressing Modes
Digital Electronic Systems
Department of Electronics
Multiple transfers with Pre-indexed addressing mode simulation (without !)
55
2.4.2 Instruction Overview: Addressing Modes
Before simulation
After simulation
Digital Electronic Systems
Department of Electronics
PC-relative
Data is an address as follows: EA = content of PC + offset
Only used with specific instructions (branches and load address)
Syntax is: [PC,#offset]
For example:
LDRR0,[PC,#12] ;SetR0 =content of PC+12
56
2.4.2 Instruction Overview: Addressing Modes
Digital Electronic Systems
Department of Electronics
Instruction List:
Moving Instructions
Data Processing Instructions
Branch Instructions
Other 32-Bit Instructions
All included in the Instruction Set
57
2.5 Instruction Description
Digital Electronic Systems
Department of Electronics
Data Moving
One of the most basic functions in a processor
In the Cortex-M3, data transfers can be one of the following types:
Moving an immediate data value into a register
Moving data between two registers
Moving data between a register and a special register
Moving data between memory and a register
Moving data between a register and the stack
58
2.5.1 Instruction Description: Moving
Digital Electronic Systems
Department of Electronics
Moving an immediate data value into a register
Transferring immediate data can be accomplished in different ways:
MOV without suffix for small values, 8-bit transfers (Thumb instruction)
For example: MOVR3,#5;Move value 5intoregisterR3
For larger values (over 8 bits), you might need to use a Thumb-2 move instruction:
For example: MOVR3,#0xAABB;Move value 0xAABBintoregisterR3
For 32-bit immediate data transfers when the data can be represented by 0-255 shifted left
by 0-23 or duplicated in all, odd or even bytes you can use MOV instruction
For example: MOVR3,#0x10000000;Move value 0x10000000toregisterR3
Pseudo-instruction LDR with ARM assembler
For example: LDRR3,= 0x12345678;Move data0x12345678toregisterR3
Note: If the data is a program address value , it will automatically set the LSB to 1
59
2.5.1 Instruction Description: Moving
Digital Electronic Systems
Department of Electronics
Moving an immediate data value into a register
MOVR3,#0x10000000;R3=0x10000000OK
MOVR5,#0x10000010;Assembling error
60
2.5.1 Instruction Description: Moving
Digital Electronic Systems
Department of Electronics
Moving an immediate data value into a register
Pseudo-instruction LDR with ARM assembler
61
2.5.1 Instruction Description: Moving
0x00000030
Digital Electronic Systems
Department of Electronics
Moving data between two registers
For example: MOVR8,R3 ;Move data value fromregisterR3toregisterR8
Moving data between register and special register
For example: MSRCONTROL,R0;MovedatafromR0intoCONTROLregister
MRSR0,CONTROL;MovedatafromCONTROLregistertoR0
Moving data between memory and register
Instructions for accessing memory are LDR (Load) and STR (Store)
Load (LDR) transfers data from memory to registers
For example: LDRR0,[R3];MovedatavaluefromaddresspointedbyR3toR0
Store (STR) transfers data from registers to memory
For example: STRR0,[R3] ;MovedatavaluefromR0 toaddresspointedbyR3
The transfers can be in different data sizes (byte, half word, word, and double)
62
2.5.1 Instruction Description: Moving
Digital Electronic Systems
Department of Electronics
All options of memory accesses with offset
63
2.5.1 Instruction Description: Moving
Digital Electronic Systems
Department of Electronics
All options of memory accesses with pre-indexing
64
2.5.1 Instruction Description: Moving
Digital Electronic Systems
Department of Electronics
All options of memory accesses with post-indexing
65
2.5.1 Instruction Description: Moving
Digital Electronic Systems
Department of Electronics
Multiple Load and Store operations; LDM and STM
66
2.5.1 Instruction Description: Moving
Digital Electronic Systems
Department of Electronics
Moving data between stack and registers
Instructions for accessing the stack: PUSH and POP
PUSH transfers data from registers to stack
POP transfers data from stack to registers
67
2.5.1 Instruction Description: Moving
Digital Electronic Systems
Department of Electronics
Processing Data
The Cortex-M3 provides many different instructions for data processing
Many data operation instructions can have multiple instruction formats, depending on
the operands addressing mode
For example: ADD instruction operate between two registers / register and immediate data:
ADD R0,R1 ;R0=R0+R1,Thumbinstruction
ADD R0,#0x12 ;R0=R0+0x12,Thumbinstruction
ADD.W R0,R1,R2 ;R0=R1+R2,Thumb2instruction
68
2.5.2 Instruction Description: Processing
Digital Electronic Systems
Department of Electronics
Processing Data
Processing data can change the flags in PSR (normally they should)
16-bit Thumb processing instructions change the flags in the PSR
32-bit Thumb-2 change the flags if S suffix is used or keep them unchanged if not
For example:
ADD.WR0,R1,R2 ;R0=R1+R2.Flagunchanged
ADDS.WR0,R1,R2 ;R0=R1+R2.Flagchange
Types of Instructions for Data Processing
Arithmetic
Logic & Bit Manipulation
Shift & Rotation
MAC
69
2.5.2 Instruction Description: Processing
Digital Electronic Systems
Department of Electronics
Arithmetic Instructions:
70
2.5.2 Instruction Description: Processing
Digital Electronic Systems
Department of Electronics
Logic & Bit Manipulation Instructions:
71
2.5.2 Instruction Description: Processing
^
^
Rm
Rm
(
~
Rm)
(
~
Rm)
Rm
Digital Electronic Systems
Department of Electronics
Shift & Rotation Instructions:
Why Is There Rotate Right But Not Rotate Left? It can be replaced with a different
offset
For example, rotate left by 4-bit rotate right by 28- bit
Gives the same result and takes the same amount of time to execute
72
2.5.2 Instruction Description: Processing
Digital Electronic Systems
Department of Electronics
MAC Instructions:
The Cortex-M3 supports signed or unsigned instructions that give 64-bit results
32-bit multiply instructions
32-bit multiply accumulate instructions (MAC)
73
2.5.2 Instruction Description: Processing
Digital Electronic Systems
Department of Electronics
Other Processing Data Instructions
Signed data from byte or half word to word
Reversing data bytes in a register
74
2.5.2 Instruction Description: Processing
Digital Electronic Systems
Department of Electronics
Branch is a Instruction for changing the program flow.
Types of Branches
Unconditional branch
For example: Blabel ;Branchtoalabeledaddress
Subroutine Call
For example: BLlabel ;Callasubroutine(function)locatedatthelabeledaddress
Conditional branch
For example: BEQlabel;Branchtoalabeledaddress
75
2.5.3 Instruction Description: Branch
Digital Electronic Systems
Department of Electronics
Unconditional Branch
The basic branch instructions are:
BXreg ;Branchtoanaddressspecifiedbyaregister
Blabel ;Branchtoalabeledaddress
Subroutine Call
To call a function, the branch and link instructions should be used:
BLlabel ;Branchtoalabeledaddressandsavereturn address inLR
BLXreg ;Branchtoanaddressspecifiedbyaregisterand savereturn
addressinLR
The return address will be stored in LR and the function can be terminated
using:
BXLR ;Returntothecallingprocess
;CAREFULWITHLRMANIPULATION(nestedfunctions)
76
2.5.3 Instruction Description: Branch
Digital Electronic Systems
Department of Electronics
Conditional Branches
Conditional Branches always have the following structure:
Instruction to prepare the branch: ANY processing instruction that modifies the state flags in the SR
Branch instruction: control instruction that performs the branch conditional on the value of a state
flag or a combination of flags
Conditional branches in ARM processors use the following flags in the APSR:
77
2.5.3 Instruction Description: Branch
Digital Electronic Systems
Department of Electronics
Conditional Branches: Conditions for Branches
According to the value of the flags or combination of flags in APSR
78
2.5.3 Instruction Description: Branch
Digital Electronic Systems
Department of Electronics
Conditional Branches: Conditions for Branches
Many other instructions may use conditional operations:
For example:
LDRNE R0,[R2,#6] ;IFZ=0setR0 =contentofmemoryadd.pointedbyR2+6
79
2.5.3 Instruction Description: Branch
Digital Electronic Systems
Department of Electronics
Conditional Branches: Common instructions to prepare the branch
CMP (Compare): subtracts two values and updates the flags (just like SUBS), but the
result is not stored in any register. It can have the following formats:
CMPR0,R1 ;CalculateR0 R1andupdateflags
CMPR0,#0x12 ;CalculateR0 0x12andupdateflags
CMN (Compare Negative): compares one value to the negative (twos complement)
of a second value; the flags are updated, but the result is not stored in any register. It
can have the following formats:
CMNR0,R1 ;CalculateR0 (R1)andupdateflags
CMNR0,#0x12 ;CalculateR0 (0x12)andupdateflags
TST (Test): ANDs two values and updates the flags, but the result is not stored. It can
have the following formats:
TSTR0,R1 ;CalculateR0&R1andupdateflags
TSTR0,#0x12 ;CalculateR0&0x12andupdateflags
80
2.5.3 Instruction Description: Branch
Digital Electronic Systems
Department of Electronics
Conditional Branches. Examples:
Using these conditions, branch instructions can be written as:
CMPrx,ry ; Instructiontopreparethebranch
BEQlabel ;BranchtoaddresslabelifZflagisset
Thumb-2 instructions can be used if the branch target is further away:
BEQ.Wlabel ;Branchto32bitaddresslabelifZflagisset
81
2.5.3 Instruction Description: Branch
Digital Electronic Systems
Department of Electronics
Special Instructions in Conditional Branches. Improving the pipe use
IF-THEN-ELSE structures
CMPR0,R1 ;CompareR0and R1
ITTEEGT ;IfR0>R1Then (first2statementsexecuteif true, other2
statementsexecuteiffalse)
MOVGTR2,R0;R2=R0(GT)
MOVGTR3,R1;R3=R1(GT)
MOVLER2,R0;Else R2=R1(LE)
MOVLER3,R1;R3=R0(LE)
Use the same defined branch conditions, otherwise, we will get a syntax error
82
2.5.3 Instruction Description: Branch
Digital Electronic Systems
Department of Electronics
Special Instructions in Conditional Branches. Improving the pipe use
Two instructions in the Cortex-M3 to reduce the number of instructions in the two
most used conditional branches:
CBZ (Compare and Branch if Zero)
CBNZ (Compare and Branch if Nonzero)
Only for forward branches
For example: i=5;
while (i!=0)
{ func1(); ;call afunction
i;}
This can be compiled into:
MOV R0,#5 ;Setloopcounter
loop1 CBZR0,loop1exit ;ifloopcounter=0thenexittheloop
BLfunc1 ;callafunction
SUBR0,#1 ;loopcounterdecrement
Bloop1 ;next loop
loop1exit
83
2.5.3 Instruction Description: Branch
Digital Electronic Systems
Department of Electronics
32-Bit Load and Store Instructions
84
2.5.4 Instruction Set
Digital Electronic Systems
Department of Electronics
32-Bit Data Processing Instructions
85
2.5.4 Instruction Set
Digital Electronic Systems
Department of Electronics
32-Bit Data Processing Instructions
86
2.5.4 Instruction Set
Digital Electronic Systems
Department of Electronics
32-Bit Data Processing Instructions
87
2.5.4 Instruction Set
Digital Electronic Systems
Department of Electronics
32-Bit Data Processing Instructions
88
2.5.4 Instruction Set
Digital Electronic Systems
Department of Electronics
32-Bit Branch Instructions
89
2.5.4 Instruction Set
Digital Electronic Systems
Department of Electronics
Other 32-Bit Instructions
90
2.5.4 Instruction Set
Digital Electronic Systems
Department of Electronics
2.6 Stacking: Concept
Concept:
A stack is a simple data structure that allows data to be stored and
retrieved in an organised way.
It is described as LIFO (Last In, First Out) structure in which the last
item placed onto a stack is the first item that can be retrieved.
An analogy is to think of the automatic plate warming devices. When a
plate is lifted off, the spring mechanism pushes up the remaining
plates so that they become more accessible. To reach the bottommost
plate, all the other plates must be removed first.
Digital Electronic Systems
Department of Electronics
2.6 Stacking: Concept
Concept:
Usually a stack refers not only to the structure, but also to the portion
of RAM that is being used to store temporary data.
When data is added to the stack, it is said to be pushed onto the
stack. When data is removed from the stack, it is said to be popped off
the stack.
In a typical PUSH operation, the contents of one or more registers will
be placed onto the stack. The memory address location where the first
item is to be stored will be held in another register.
This register is known as the stack pointer (SP)
Digital Electronic Systems
Department of Electronics
2.6 Stacking: Concept
There are four different stack implementations. These are
categorised by two axes, namely Ascending versus
Descending and Empty versus Full:
An Ascending stack grows upwards. It starts from a low memory
address and, as items are pushed onto it, progresses to higher
memory addresses.
A Descending stack grows downwards. It starts from a high memory
address, and as items are pushed onto it, progresses to lower memory
addresses. The previous examples have been of a Descending stack.
Digital Electronic Systems
Department of Electronics
2.6 Stacking: Concept
There are four different stack implementations. These are
categorised by two axes, namely Ascending versus
Descending and Empty versus Full:
In an Empty stack, the stack pointer points at the next free (empty)
location on the stack, i.e. the place where the next item to be pushed
onto the stack will be stored.
In a Full stack, the stack pointer points at the topmost item in the
stack, i.e. the location of the last item to be pushed onto the stack.
Digital Electronic Systems
Department of Electronics
2.6 Stacking: Concept
Stack implementations:
Digital Electronic Systems
Department of Electronics
2.6 Stacking: Example of stack usage
System features:
32-bit microprocessor and 16Mb of addressing capacity.
General purpose registers R0 to R15; status register SR, program
counter PC, and stack pointer SP.
4-bank memory map.
Full descending stack.
Instructions for stack managing, PUSH (data onto the stack) and POP
(data from the stack), call to subroutine BSR label.
Stack start-address 0x100000.
Digital Electronic Systems
Department of Electronics
2.6 Stacking: Example of stack usage
Calling a subroutine
Address Mem. Content
0x100000 xxxxxxxx
0x0FFFFC 0x000104
0x0FFFF8
0x0FFFF4
0x0FFFF0
SP initial
SP at the
beginning of
the
subroutine
When calling a subroutine
the returning address is
automatically saved onto
the stack.
Address Instruction
0x000100 BSR func_suma
0x000104 ADD #1,R2
Digital Electronic Systems
Department of Electronics
2.6 Stacking: Example of stack usage
Context saving
The registers that are modified by the subroutine have to be saved
onto the stack at the beginning of the subroutine, and they are
restored at the end.
Address Instruction
0x000100 BSR func_suma
0x000104 ADD #1,R2
Digital Electronic Systems
Department of Electronics
2.6 Stacking: Example of stack usage
Context saving
Address Mem. Content
0x100000 xxxxxxxx
0x0FFFFC 0x000104
0x0FFFF8 Value of R0
0x0FFFF4 Value of R1
0x0FFFF0 Value of R2
SP Initial
SP after
PUSH R2
Address Subroutine code
0x000400 PUSH R0
0x000404 PUSH R1
0x000408 PUSH R2
; main body of the
subroutine
0x000470 POP R2
0x000474 POP R1
0x000478 POP R0
Digital Electronic Systems
Department of Electronics
2.6 Stacking: Example of stack usage
Passing arguments through the stack
When a subroutine needs
arguments for its execution, they
can be passed through the stack or
through the registers.
Example: two data values stored in
the addresses 0x0F0000 and
0x0F0004 (5 y 8, respectively), and
an address for storing the result
(0x0F0008) are saved onto the
stack.
Address Instruction
0x000100 MOV 0x0F0000,R0
0x000104 PUSH R0
0x000108 MOV 0x0F0004,R0
0x00010C PUSH R0
0x0001F0 MOV #0x0F0008,R0
0x0001F4 PUSH R0
0x0001F8 BSR func_suma
0x0001FC ADD #1,R2
Digital Electronic Systems
Department of Electronics
2.6 Stacking: Example of stack usage
Passing arguments through the stack
Address Mem. Content
0x100000 xxxxxxxx
0x0FFFFC 0x000005
0x0FFFF8 0x000008
0x0FFFF4 0x0F0008
0x0FFFF0 0x0001F8
0x0FFFEC Value of R0
0x0FFFE8 Value of R1
0x0FFFE4 Value of R2
SP initial
SP after
PUSH R2
Address Subroutine code
0x000400 PUSH R0
0x000404 PUSH R1
0x000408 PUSH R2
; Main body of the
subroutine
0x000470 POP R2
0x000474 POP R1
0x000478 POP R0
Digital Electronic Systems
Department of Electronics
Basic operations of the stack
Data in registers is saved into stack memory by a PUSH operation
and can be restored to registers later by a POP operation
The SP is adjusted automatically in PUSH and POP so that multiple data PUSH will
not cause old stacked data to be erased
Notice the order of PUSH / POP: The POP order must be the reverse of PUSH
Stack operations as Context change and Parameter passing
Can be simplified, thanks to multiple load and store PUSH and POP instructions
The processor automatically reverses in POP the ordering of the register list in PUSH
102
2.6 Stacking: The Cortex-M3
Digital Electronic Systems
Department of Electronics
Stack implementation
PUSH and POP operations can only be performed over registers
Each PUSH/POP operation transfers 4 bytes of data (the whole word of the
register)
Thus, SP decrements/increments by 4 with each PUSH/POP operation (respectively)
or a multiple of 4 if more than 1 register is stacked
Stacking and Unstacking operates similarly and uses similar syntax to multiple
transfers:
Address register is always SP (MSP or PSP) implicitly (not used in the syntax)
SP IS ALWAYS ALTERED, though ! is not used in the syntax
103
2.6 Stacking: The Cortex-M3
Digital Electronic Systems
Department of Electronics
Stacking in an exception handler (ISR)
When entering in an ISR, a number of registers will be pushed automatically, and
R13 will be used as the SP for this stacking process
Similarly, the pushed registers will be restored automatically when exiting from
the ISR, and the SP will also be adjusted
104
2.6 Stacking: The Cortex-M3
Digital Electronic Systems
Department of Electronics
The Cortex-M3 uses a full-descending stack operation model
SP points to the last data pushed to the stack
SP decrements before a PUSH and increments after a POP
105
2.6 Stacking: The Cortex-M3
SP Stack
decrease
Digital Electronic Systems
Department of Electronics
SP
SP
Stacking a single register:
PUSH{R0};R13 =R134,thenMemory[R13]=R0
POP{R0};R0 =Memory[R13],thenR13 =R13+4
Context saving:
subroutine_1
PUSH{R0R7,R14};Saveregisters
;Doyourprocessing
POP{R0R7,R14} ;Restoreregisters
BXR14 ;Returntocallingfunction
106
2.6 Stacking: Examples of use
SP
Digital Electronic Systems
Department of Electronics
Stacking examples
Context saving
107
2.6 Stacking: Examples of use
Digital Electronic Systems
Department of Electronics
Stacking examples
Context change with multiple load and store PUSH and POP instructions
For nested subroutines (functions) LR has also to be stacked
108
2.6 Stacking: Examples of use
Digital Electronic Systems
Department of Electronics
109
2.6 Stacking: Examples of use
Save the LR if you need to call a subroutine within another one
Digital Electronic Systems
Department of Electronics
The Two-Stack model
Cortex-M3 has two SPs: the MSP and the PSP
The SP register to be used is controlled by CONTROL[1]
When CONTROL[1]=0, the MSP is used for both Thread mode and Handler mode:
The main program and the exception handlers share the same stack memory region
This is the default setting after power-up
110
2.6 Stacking: Two-Stack model
Digital Electronic Systems
Department of Electronics
When CONTROL[1]=1, the PSP is used for thread mode
The main program and the exception handler can have separate stack memory regions
Automatic stacking will use PSP when branching to the exception handler
Stacking operations inside the handler will use MSP
It is possible to perform read/write operations directly to the MSP and PSP, without
any confusion of which R13 you are referring to
If the processor is in privileged level, you can access MSP and PSP values
111
2.6 Stacking: Two-Stack model
Digital Electronic Systems
Department of Electronics
112
2.7 I/O Ports: Concept
I/O Port
Parallel ports provide the ability to input or output binary data with a single bit
allocated to each pin within the port.
They are called parallel ports because the initial chips that provided this support
grouped several pins together to create a controllable data port.
The individual bits and pins within the port can usually be used independently of
each other.
These ports are used to provide parallel interfaces, output signals or inputs signals.
Digital Electronic Systems
Department of Electronics
113
2.7 I/O Ports: Concept
I/O Port
The port is controlled by two registers:
a data direction register which defines whether each pin is an output or an input and
a data register which is used to set an output value by writing to it and to obtain an input value by
reading from it.
Digital Electronic Systems
Department of Electronics
114
2.7 I/O Ports: Concept
Multi-function I/O Port
Usually, the pins are described as
general-purpose input output (GPIO)
and can be shared with other
peripherals. For example, a pin may be
used as part of a serial port as a control
signal.
The function that the pin performs is set
up internally through the use of a
function register.
Digital Electronic Systems
Department of Electronics
115
2.7 I/O Ports: LPC1768: Pin connect block
Pin connect block
It allows most pins of the microcontroller to have more than one potential function.
This block has two configuration registers:
Pin function select register (PINSEL).
Pin mode select register (PINMODE).
Pin function select register (PINSELx)
The PINSEL registers control the functions of the device pins.
Pairs of bits in these registers correspond to specific device pins.
Digital Electronic Systems
Department of Electronics
116
2.7 I/O Ports: LPC1768: Pin connect block
Pin function select registers (PINSELx)
Example: PINSEL0 register (Dir 0x4002 C000) controls the functions of the low Port
0 (P0.0 a P0.15). If you write to the two least significant bits:
00, P0.0 pin is connected to the line 0 of GPIO port 0 (GPIO Port 0.0)
01, P0.0 pin is connected to the RD1 line of the CAN1 controller
10, P0.0 pin is connected to the TXD3 line of the UART3
11, P0.0 line is connected to the SDA1 line of the I2C1 bus
Digital Electronic Systems
Department of Electronics
117
2.7 I/O Ports: LPC1768: Pin connect block
Pin function select registers (PINSELx)
Pin function select register PINSEL0 bit description
Digital Electronic Systems
Department of Electronics
118
2.7 I/O Ports: LPC1768: Pin connect block
Pin mode select registers (PINMODE)
They control the input mode of all ports. Three bits are used to control the mode of a
port pin, two in a PINMODE register, and an additional one in a PINMODE_OD
register. PINMODE0:9 registers configure the on-chip pull-up/pull-down resistor
feature.
Repeater mode enables the pull-up resistor if the pin is at a logic high and enables
the pull-down resistor if the pin is at a logic low. This causes the pin to retain its last
known state if it is configured as an input and is not driven externally.
Digital Electronic Systems
Department of Electronics
119
2.7 I/O Ports: LPC1768: Pin connect block
Pin mode select registers (PINMODE)
The PINMODE_OD0:4 registers control the open drain mode for ports.
Digital Electronic Systems
Department of Electronics
120
2.7 I/O Ports: LPC1768: GPIO
General Purpose I/O Ports
LPC17xx microcontrollers family have five general purpose input output ports P0, P1,
P2, P3 y P4, with different numbers of lines.
Digital Electronic Systems
Department of Electronics
121
2.7 I/O Ports: LPC1768: GPIO
General Purpose I/O Ports
The GPIO Ports are controlled by a set of registers that are located in the peripheral
bus.
Digital Electronic Systems
Department of Electronics
122
2.7 I/O Ports: LPC1768: GPIO
General Purpose I/O Ports
The GPIO Ports are controlled by a set of registers that are located in the peripheral
bus.
Digital Electronic Systems
Department of Electronics
123
2.7 I/O Ports: LPC1768: GPIO
GPIO port Direction register (FIOxDIR)
This word-accessible register is used to control the direction of the pins when they
are configured as GPIO port pins.
Ejemplo: FIO1DIR = 0x 00FF0000; 1623 pins of the port 1 are output
FIO0DIR: bit 0 controls P0.0bit 30 controls P0.30
FIO1DIR: bit 16 controls P1.16bit 30 controls P1.30
Digital Electronic Systems
Department of Electronics
124
2.7 I/O Ports: LPC1768: GPIO
GPIO port Pin value register (FIOxPIN)
This register provides the value of port pins that are configured to perform only digital
functions. It returns '1 'if the pin is at high level and a '0' if it is low.
Writing to the FIOxPIN register transmits each bit value written to its corresponding
pin.
Writing to the FIOxPIN register stores the value in the port output register, bypassing
the need to use both the FIOxSET and FIOxCLR registers to obtain the entire written
value.
Access to a port pin via the FIOxPIN register is conditioned by the corresponding bit
of the FIOxMASK register.
Digital Electronic Systems
Department of Electronics
125
2.7 I/O Ports: LPC1768: GPIO
GPIO port Pin value register (FIOxPIN)
Digital Electronic Systems
Department of Electronics
126
2.7 I/O Ports: LPC1768: GPIO
GPIO port output Set register (FIOxSET)
This register is used to produce a HIGH level output at the port pins configured as
GPIO in an OUTPUT mode.
Digital Electronic Systems
Department of Electronics
127
2.7 I/O Ports: LPC1768: GPIO
GPIO port output Clear register (FIOxCLR)
This register is used to produce a LOW level output at port pins configured as GPIO
in an OUTPUT mode. Writing 1 produces a LOW level at the corresponding port pin
and clears the corresponding bit in the FIOxSET register. Writing 0 has no effect.
Digital Electronic Systems
Department of Electronics
128
2.7 I/O Ports: LPC1768: GPIO
GPIO port Mask register (FIOxMASK)
This register is used to select port pins that will and will not be affected by write
accesses to the FIOxPIN, FIOxSET or FIOxCLR register. Mask register also filters
out ports content when the FIOxPIN register is read.
Digital Electronic Systems
Department of Electronics
129
2.7 I/O Ports: LPC1768: GPIO
Example: Configuration, read and write port
#include <stdio.h>
#include <LPC17xx.H> /* Definiciones para el LPC17xx */
main()
{
int value;
LPC_GPIO0 ->FIODIR =0x0000000F; //Los pines P0.[0..3] configurados como salidas,
//P0.[4..31] como entradas
LPC_GPIO0->FIOCLR=0x0000000F; //Ponemos a cero los pines P0.[0..3].
//Tambin servira para poner los pines P0.[0..3] a cero: LPC_GPIO0->FIOPIN=0x00000000;
LPC_GPIO0->FIOSET=0x00000001; //Activar la salida P0.0
LPC_GPIO0->FIOSET=0x0000000A; //Activar las salidas P0.1 y P0.3
LPC_GPIO0->FIOSET |=((1<<3)| (1<<1));
LPC_GPIO0->FIOCLR=0x00000001; //Desactivar la misma salida P0.0
value =((LPC_GPIO0->FIOPIN & (1 <<4))>>4); // Lee el estado del pin P0.4 (Nota 1)
}

You might also like