Date post: | 26-Dec-2015 |
Category: |
Documents |
Upload: | pakoloko92 |
View: | 27 times |
Download: | 0 times |
ARM Cortex M3(i)
Department of Electronics
Academic Year 2014/15(ver 12-09-2014)
Topic 2Cortex M3 Processor: Software Tips
Digital Electronic Systems Department of Electronics
2.1. Introduction to Cortex-M33.1.1. ARM Overview3.1.2. ARM Cortex-M3 Processor
2.2. Programmer’s Model and Registers2.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 Modes2.4.1. Assembler Basics2.4.2. Addressing Modes
2.5. Instruction Descriptions2.5.1. Moving Data2.5.2. Processing Data 2.5.3. Branches2.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 Berkeley’s students (Berkeley RISC I)
In 1990 the firm becomes Advanced RISC Machines Ltd.English firm founded by Apple Comp., Acorn Comp. Group and VLSI TechnologyNowadays 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 programmer’s 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 microcontrollerImproved code densityCan be easily programmed using the C languageGreater 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 ARM7Nonmaskable interrupts for critical tasksDeterministic nested vector exceptionsAtomic bit manipulationOptional Memory Protection Unit (MPU)
7
2.1 Introduction: ARM Cortex-M3 Processor
Digital Electronic Systems Department of Electronics
Background of ARM and ARM Architecture
8
2.1 Introduction: ARM Cortex-M3 Processor
Digital Electronic Systems Department of Electronics
ARM v7 Processor ProfilesA Profile (ARMv7-A):
Processors to handle complex applications such as high-end embedded operating systemsThese 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 criticalSpecially indicated for industrial control applications, including real-time control systems
9
2.1 Introduction: ARM Cortex-M3 Processor
Digital Electronic Systems Department of Electronics
ARM Cortex-M3 Processor ApplicationsLow-cost microcontrollersAutomotiveData communicationsIndustrial controlConsumer products
10
2.1 Introduction: ARM Cortex-M3 Processor
Digital Electronic Systems Department of Electronics
ARM Cortex-M3 Based uC
11
2.1 Introduction: ARM Cortex-M3 Processor
Digital Electronic Systems Department of Electronics
About the programmer’s model
12
2.2 Programmer’s Model and Registers
Digital Electronic Systems Department of Electronics
13
2.2 Programmer’s Model and Registers
Data types supported by the processor
32-bit → words16-bit → halfwords8-bit → bytes
Digital Electronic Systems Department of Electronics
Registers: Cortex-M3 processors have sixteen 32 bit registers R0 to R15R0 to R12: General-Purpose Registers GPRsR13 is the Stack Pointer (SP): it is banked, with only one R13 visible at a timeR14 is the Link Register (LR): used in subroutines and exception handlersR15 is the Program Counter (PC)
General-Purpose Registers (GPRs): Low and High GPRsLow 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 R8–R12: They are accessible by all Thumb-2 instructions but not by all 16-bit Thumb instructions
14
2.2 Programmer’s 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 Programmer’s 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 LRLR 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 Programmer’s 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 ; Main program…BL function1 ; Calls function1 using Branch with Link instruction
; PC = function1 and LR = the next instruction in main…function1… ; Program code for function 1BX LR ; Return
LR has to be manually stored to correctly perform nested subroutines17
2.2 Programmer’s 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 ; Main program…BL function1 ; Calls function1 using Branch with Link instruction
; PC = function1 and LR = the next instruction in main…function1… ; Program code for function 1BX LR ; Return
LR has to be manually stored to correctly perform nested subroutines (to call a subroutine from another).
18
2.2 Programmer’s 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 PCWhen 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 Programmer’s Model and Registers: PC
Digital Electronic Systems Department of Electronics
Special Registers:They have special functions and can be accessed only by special instructionsThey cannot be used for normal data processing
20
2.2 Programmer’s Model and Registers: SRs
Digital Electronic Systems Department of Electronics
Program Status Registers: PSRsProvide 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 Programmer’s Model and Registers: SRs
Digital Electronic Systems Department of Electronics
Program Status Registers: APSR, IPSR
22
2.2 Programmer’s Model and Registers: SRs
Digital Electronic Systems Department of Electronics
Program Status Registers: EPSRTwo overlapped fields: ICI and ITInterruptible-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, ITIT 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 instructionExecution of the If-Then instruction
23
2.2 Programmer’s Model and Registers: SRs
Digital Electronic Systems Department of Electronics
Program Status Registers: EPSR
24
2.2 Programmer’s Model and Registers: SRs
Digital Electronic Systems Department of Electronics
Program Status RegistersPSRs 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 instructionWriting APSR is possible by using the MSR instruction. EPSR and IPSR are read-onlyFor example:
MRS r0, APSR ; Read Flag state into R0MRS r0, IPSR ; Read Interrupt stateMRS r0, EPSR ; Read Execution stateMSR APSR, r0 ; Write Flag state
25
2.2 Programmer’s 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 exceptionFAULTMASK: Disable all exceptions except the NMI. Changes the priority level to -1BASEPRI: Disable all exceptions of a specific priority or lower priority level
26
2.2 Programmer’s Model and Registers: SRs
Digital Electronic Systems Department of Electronics
Interrupt Mask RegistersThey are accessed with MRS and MSR instructionsFor example:
MRS r0, BASEPRI ; Read BASEPRI register into R0MRS r0, FAULTMASK ; Read FAULTMASK register into R0MSR PRIMASK, r0 ; Write R0 into PRIMASK register
They cannot be set in the user access level
Control Register: CONTROLUsed to define the stack pointer selection and the privilege levelWe’ll study the Control Register in the following section
27
2.2 Programmer’s 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 resourcesPrivileged 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 exceptionHandler 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:
MRS R0, CONTROL ; Read CONTROL register into R0MSR CONTROL, R0 ; Write R0 into CONTROL register
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 appsSome bits in a special register define the privilege levelAt least 2 levels:
User level: accessed by user appsWithout access to hardwareOS calls (TRAP, Service Call) are needed
Privileged level: accessed by OS appsException 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 CallOS Call
Privileged Level
User Level
Thread
Thread
Handler
Digital Electronic Systems Department of Electronics
The Instruction SetThe Cortex-M3 supports Thumb (16-bit instructions) and Thumb-2 (32-bit instructions) instruction setsThumb-2 instruction set
32-bit and 16-bit instructions can be used together for high code density and high efficiencyIt is flexible, powerful and easy to useIt 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 SyntaxThe following instruction formatting is commonly used:
label: opcode operand1, operand2,... ; Comments
The number of operands in an instruction depends on the type of instructionThe 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 instructionsOther 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 syntaxUnified Assembler Language (UAL) developed to support Thumb-2 instruction setIt allows selection of 16-bit and 32-bit instructionsAn example of using UAL or not:
ADD R0, R1 ; R0 = R0 + R1, using Traditional Thumb syntaxADD R0, R0, R1 ; Equivalent instruction using UAL syntax
The traditional Thumb syntax can still be usedWith Thumb instruction syntax, some instructions change the flags in APSR,even if the S suffix is not used. For example:
AND R0, R1 ; Traditional Thumb syntaxANDS R0, R0, R1 ; Equivalent UAL syntax (S suffix is added)
35
2.4.1 Instruction Overview: Assembler
Digital Electronic Systems Department of Electronics
UAL size suffixesSpecify which instruction you want by adding N and W suffixes:
ADDS R0, #1 ; Use 16‐bit Thumb instruction by default for smaller sizeADDS.N R0, #1 ; Use 16‐bit Thumb instruction (N=Narrow)ADDS.W R0, #1 ; Use 32‐bit Thumb‐2 instruction (W=wide)
If no suffix is given, the assembler tool can choose either instruction, but usuallydefaults to 16-bit Thumb code to get a smaller sizeDepending on the tool support, you may also use the .N (narrow) suffix to specify a16-bit Thumb instructionIn most cases, applications will be coded in C, and then compilers will use 16-bitinstructions if possible due to smaller code sizeNevertheless, 32-bit Thumb-2 instruction are used
With immediate data that exceeds a certain rangeWhen 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: LDR R0,[R1] ; a 16‐bit instructions (occupy 0x1000‐0x1001)
0x1002: ADDS R0,R0,R1 ; a 32‐bit Thumb‐2 instruction (occupy 0x1002‐0x1005)
37
2.4.1 Instruction Overview: Assembler
Dir. Opcode Mnemotécnico
Digital Electronic Systems Department of Electronics
Cortex-M3 supports the following addressing modes:ImmediateRegister (Direct to Register)IndirectOffset or Base+Offset (Indirect & Indirect+Offset)Indexed or Base+Index+OffsetPre-indexedPost-indexedPC-relative
38
2.4.2 Instruction Overview: Addressing Modes
Digital Electronic Systems Department of Electronics
Immediate Data is the operandSyntax is: #numberCan only be used for the source operandUsable in any type of instructionFor example:
ADD R0, #0x12 ; R0 = R0+0x12 (hexadecimal)
MOV R1, #’A’ ; Set R1 = ASCII character ‘A’
If transferring a 32-bit operand, LDR can be used with a different syntax:For example:
LDR R1,=0x10200000 ; Set R1 = 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 = RxSyntax is: RxUsable in any type of instructionFor example:
MSR CONTROL, R12 ; Set CONTROL = R12
ADD R0, 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
IndirectData is INTO the memory address pointed by a register: EA = content of RxSyntax is: [Rx]ONLY applicable in transfer instructions with LDR and STRFor example:
LDR R0,[R3] ; Set R0 = content of memory address pointed by R3
STR R3,[R2] ; Set content of memory address pointed by R2 = 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 + offsetSyntax is: [Rx,#offset]The register is unalteredONLY applicable in transfer instructions with LDR and STRUseful to get parameters within a tableFor example:
LDR R0,[R1,#24] ; Set R0 = content of memory address pointed by R1+24
LDR R0,[SP,#4] ; Set R0 = content of memory address pointed by SP+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 obtainedBoth registers are unalteredONLY applicable in transfer instructions with LDR and STRFor example:
LDR R0,[R1,R2,LSL#2] ; Set R0 = content of memory add. pointed by R1+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-indexedData is located in the same EA as in Indirect+Offset: EA = content of Rx+offsetSyntax: [Rx,#offset]!The register IS ALTERED BEFORE the access is performedONLY applicable in transfer instructions with LDR and STRFor example:LDR R0,[R2,#2] ! ; Set R2 = R2 + 2
; Set R0 = content of memory add. pointed by R2+2
STRD.W R0,R1,[R2,#0] ! ; Set R2 = R2 + 0
; Set the content of memory add. pointed by R2+0 = R0
; Set the content of memory add. pointed by R2+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-indexedData is located in the same EA as in Indirect: EA = content of RxSyntax: [Rx],#offsetThe register IS ALTERED AFTER the access is performedONLY applicable in transfer instructions with LDR and STRFor example:LDR R0,[R2],#2 ; Set R0 = content of memory add. pointed by R2
; Set R2 = 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-indexedWith LDM and STM instructionsOperates similarly and uses similar syntaxSuffix IA (increment after) indicates post-indexSuffix DB (decrement before) pre-indexWith ! the register IS ALTERED after the instruction is completed For example:
LDMIA.W R0!,{R2,R5} ; Set R2 = content of memory add. pointed by R0; R0 = R0 + 4
; Set R5 = content of memory add. pointed by R0
; R0 = R0 + 4
STMDB.W R0!,{R2‐R4} ; Set R0 = R0 ‐ 4, and content of memory add. pointed by R0 = R4
; Set R0 = R0 ‐ 4, and content of memory add. pointed by R0 = R3; Set R0 = R0 ‐ 4, and content of memory add. pointed by R0 = 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-indexedWithout ! the register IS NOT ALTERED after the instruction is completed For example:
LDMIA.W R0,{R2,R5} ; Set R2 = content of memory add. pointed by R0
; Set R5 = content of memory add. pointed by R0 + 4
STMDB.W R0,{R2,R5} ; Set content of memory add. pointed by R0 ‐ 4 = R5
; Set content of memory add. pointed by R0 ‐ 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-relativeData is an address as follows: EA = content of PC + offsetOnly used with specific instructions (branches and load address)Syntax is: [PC,#offset]For example:
LDR R0,[PC,#12] ; Set R0 = content of PC+12
56
2.4.2 Instruction Overview: Addressing Modes
Digital Electronic Systems Department of Electronics
Instruction List:
Moving InstructionsData Processing InstructionsBranch InstructionsOther 32-Bit Instructions
All included in the Instruction Set
57
2.5 Instruction Description
Digital Electronic Systems Department of Electronics
Data MovingOne of the most basic functions in a processorIn the Cortex-M3, data transfers can be one of the following types:
Moving an immediate data value into a registerMoving data between two registers Moving data between a register and a special registerMoving data between memory and a registerMoving 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: MOV R3, #5 ; Move value 5 into register R3
For larger values (over 8 bits), you might need to use a Thumb-2 move instruction:
For example: MOV R3, #0xAABB ; Move value 0xAABB into register R3
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: MOV R3, #0x10000000 ; Move value 0x10000000 to register R3
Pseudo-instruction LDR with ARM assembler
For example: LDR R3, = 0x12345678 ; Move data 0x12345678 to register R3
Note: If the data is a program address value , it will automatically set the LSB to 159
2.5.1 Instruction Description: Moving
Digital Electronic Systems Department of Electronics
Moving an immediate data value into a registerMOV R3, #0x10000000 ; R3= 0x10000000 OKMOV R5, #0x10000010 ; Assembling error
60
2.5.1 Instruction Description: Moving
Digital Electronic Systems Department of Electronics
Moving an immediate data value into a registerPseudo-instruction LDR with ARM assembler
61
2.5.1 Instruction Description: Moving
0x00000030
Digital Electronic Systems Department of Electronics
Moving data between two registersFor example: MOV R8, R3 ; Move data value from register R3 to register R8
Moving data between register and special register For example: MSR CONTROL, R0 ; Move data from R0 into CONTROL register
MRS R0, CONTROL ; Move data from CONTROL register to R0
Moving data between memory and registerInstructions for accessing memory are LDR (Load) and STR (Store)
Load (LDR) transfers data from memory to registers
For example: LDR R0, [R3] ; Move data value from address pointed by R3 to R0
Store (STR) transfers data from registers to memory
For example: STR R0, [R3] ; Move data value from R0 to address pointed by R3
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 POPPUSH transfers data from registers to stackPOP transfers data from stack to registers
67
2.5.1 Instruction Description: Moving
Digital Electronic Systems Department of Electronics
Processing DataThe Cortex-M3 provides many different instructions for data processingMany data operation instructions can have multiple instruction formats, depending onthe operands’ addressing modeFor example: ADD instruction operate between two registers / register and immediate data:
ADD R0, R1 ; R0 = R0+R1, Thumb instructionADD R0, #0x12 ; R0 = R0 + 0x12, Thumb instructionADD.W R0, R1, R2 ; R0 = R1+R2, Thumb‐2 instruction
68
2.5.2 Instruction Description: Processing
Digital Electronic Systems Department of Electronics
Processing DataProcessing data can change the flags in PSR (normally they should)
16-bit Thumb processing instructions change the flags in the PSR32-bit Thumb-2 change the flags if S suffix is used or keep them unchanged if not
For example:
ADD.W R0, R1, R2 ; R0=R1+R2. Flag unchangedADDS.W R0, R1, R2 ; R0=R1+R2. Flag change
Types of Instructions for Data ProcessingArithmeticLogic & Bit ManipulationShift & RotationMAC
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 offsetFor 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 BranchesUnconditional branchFor example: B label ; Branch to a labeled address
Subroutine CallFor example: BL label ; Call a subroutine (function) located at the labeled address
Conditional branchFor example: BEQ label ; Branch to a labeled address
75
2.5.3 Instruction Description: Branch
Digital Electronic Systems Department of Electronics
Unconditional BranchThe basic branch instructions are:
BX reg ; Branch to an address specified by a register B label ; Branch to a labeled address
Subroutine CallTo call a function, the branch and link instructions should be used:
BL label ; Branch to a labeled address and save return address in LR BLX reg ; Branch to an address specified by a register and save return
address in LR
The return address will be stored in LR and the function can be terminated using:
BX LR ; Return to the calling process; CAREFUL WITH LR MANIPULATION (nested functions)
76
2.5.3 Instruction Description: Branch
Digital Electronic Systems Department of Electronics
Conditional BranchesConditional Branches always have the following structure:
Instruction to prepare the branch: ANY processing instruction that modifies the state flags in the SRBranch instruction: control instruction that performs the branch conditional on the value of a stateflag 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 BranchesAccording 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 BranchesMany other instructions may use conditional operations:For example:
LDRNE R0, [R2, #6] ; IF Z=0 set R0 = content of memory add. pointed by R2+6
79
2.5.3 Instruction Description: Branch
Digital Electronic Systems Department of Electronics
Conditional Branches: Common instructions to prepare the branchCMP (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:
CMP R0, R1 ; Calculate R0 – R1 and update flagsCMP R0, #0x12 ; Calculate R0 – 0x12 and update flags
CMN (Compare Negative): compares one value to the negative (two’s complement) of a second value; the flags are updated, but the result is not stored in any register. It can have the following formats:
CMN R0, R1 ; Calculate R0 – (‐R1) and update flagsCMN R0, #0x12 ; Calculate R0 – (‐0x12) and update flags
TST (Test): ANDs two values and updates the flags, but the result is not stored. It can have the following formats:
TST R0, R1 ; Calculate R0 & R1 and update flagsTST R0, #0x12 ; Calculate R0 & 0x12 and update flags
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:
CMP rx,ry ; Instruction to prepare the branchBEQ label ; Branch to address ‘label’ if Z flag is set
Thumb-2 instructions can be used if the branch target is further away:BEQ.W label ; Branch to 32‐bit address ‘label’ if Z flag is set
81
2.5.3 Instruction Description: Branch
Digital Electronic Systems Department of Electronics
Special Instructions in Conditional Branches. Improving the pipe useIF-THEN-ELSE structures
CMP R0, R1 ; Compare R0 and R1ITTEE GT ; If R0 > R1 Then (first 2 statements execute if true, other 2
statements execute if false)MOVGT R2, R0 ; R2 = R0 (GT)MOVGT R3, R1 ; R3 = R1 (GT)MOVLE R2, R0 ; Else R2 = R1 (LE)MOVLE R3, 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 useTwo instructions in the Cortex-M3 to reduce the number of instructions in the twomost used conditional branches:
CBZ (Compare and Branch if Zero)CBNZ (Compare and Branch if Nonzero)
Only for forward branchesFor example: i = 5;
while (i != 0 ){ func1(); ; call a functioni‐‐;}
This can be compiled into:MOV R0, #5 ; Set loop counter
loop1 CBZ R0, loop1exit ; if loop counter = 0 then exit the loopBL func1 ; call a functionSUB R0, #1 ; loop counter decrementB loop1 ; 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, programcounter 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 subroutineAddress Mem. Content
0x100000 xxxxxxxx0x0FFFFC 0x0001040x0FFFF80x0FFFF40x0FFFF0
SP initial
SP at the beginning of the subroutine
When calling a subroutinethe returning address isautomatically saved ontothe stack.
Address Instruction0x000100 BSR func_suma0x000104 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 savedonto the stack at the beginning of the subroutine, and they are restored at the end.
Address Instruction0x000100 BSR func_suma0x000104 ADD #1,R2
Digital Electronic Systems Department of Electronics
2.6 Stacking: Example of stack usage
Context saving
Address Mem. Content0x100000 xxxxxxxx0x0FFFFC 0x0001040x0FFFF8 Value of R00x0FFFF4 Value of R10x0FFFF0 Value of R2
SP Initial
SP after PUSH R2
Address Subroutine code0x000400 PUSH R00x000404 PUSH R10x000408 PUSH R2
; main body of thesubroutine
0x000470 POP R20x000474 POP R10x000478 POP R0
Digital Electronic Systems Department of Electronics
2.6 Stacking: Example of stack usage
Passing arguments through the stack
When a subroutine needsarguments for its execution, theycan be passed through the stack orthrough 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 thestack.
Address Instruction0x000100 MOV 0x0F0000,R00x000104 PUSH R00x000108 MOV 0x0F0004,R00x00010C PUSH R00x0001F0 MOV #0x0F0008,R00x0001F4 PUSH R00x0001F8 BSR func_suma0x0001FC ADD #1,R2
Digital Electronic Systems Department of Electronics
2.6 Stacking: Example of stack usage
Passing arguments through the stack
Address Mem. Content0x100000 xxxxxxxx0x0FFFFC 0x0000050x0FFFF8 0x0000080x0FFFF4 0x0F00080x0FFFF0 0x0001F80x0FFFEC Value of R00x0FFFE8 Value of R10x0FFFE4 Value of R2
SP initial
SP after PUSH R2
Address Subroutine code0x000400 PUSH R00x000404 PUSH R10x000408 PUSH R2
; Main body of thesubroutine
0x000470 POP R20x000474 POP R10x000478 POP R0
Digital Electronic Systems Department of Electronics
Basic operations of the stackData in registers is saved into stack memory by a PUSH operation…and can be restored to registers later by a POP operationThe SP is adjusted automatically in PUSH and POP so that multiple data PUSH will not cause old stacked data to be erasedNotice the order of PUSH / POP: The POP order must be the reverse of PUSHStack operations as Context change and Parameter passing
Can be simplified, thanks to multiple load and store PUSH and POP instructionsThe 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 implementationPUSH and POP operations can only be performed over registersEach 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 stackedStacking 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 processSimilarly, 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 modelSP points to the last data pushed to the stackSP 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 = R13‐4, then Memory [R13] = R0POP {R0} ; R0 = Memory [R13], then R13 = R13+4
Context saving:
subroutine_1
PUSH {R0‐R7, R14} ; Save registers
… ; Do your processing
POP {R0‐R7, R14} ; Restore registers
BX R14 ; Return to calling function
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 useSave the LR if you need to call a subroutine within another one
Digital Electronic Systems Department of Electronics
The Two-Stack modelCortex-M3 has two SPs: the MSP and the PSPThe 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 regionThis 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 handlerStacking 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 PortParallel 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 PortThe 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 PortUsually, 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 blockIt 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 controller10, P0.0 pin is connected to the TXD3 line of the UART311, 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_ODregister. 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 PortsLPC17xx 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 PortsThe 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 PortsThe 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; 16‐23 pins of the port 1 are output
FIO0DIR: bit 0 controls P0.0…bit 30 controls P0.30FIO1DIR: bit 16 controls P1.16…bit 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 port’s 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].//También serviría 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.3LPC_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)
}