TLS2130 Presentation v1.6p
TLS2130 Presentation v1.6p
TLS2130 Presentation v1.6p
C
for dsPIC
and PIC24
Getting Started with MPLAB
C
for dsPIC
and PIC24
Author: Rob Ostapiuk
Microchip Technology Inc.
TLS 2130
TLS 2130
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 2
Agenda
C in an Embedded Environment
Very Short Review of 16-bit Architecture
MPLAB
Architecture
Data RAM
Peripherals
I/O Ports
Data
Space
Program
Flash
Program
Space
16-bit CPU 24-bit
16-bit Y
Program
Bus
Data
Buses
PSV Window
and
Table Access
16-bit 16-bit
16-bit X
The Y data bus is only available on the dsPIC30 and dsPIC33 families.
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 7
SFR Space
X Data RAM
Unimplemented
Data Memory Map
16-bit PIC
Architecture
0x0801
Y Data RAM
Dual Port RAM
MSB LSB
16-bits LSB
Address
MSB
Address
0x0000 0x0001
0x07FE
0x0800
0x07FF
0x1FFE
0x8000 0x8001
0xFFFE 0xFFFF
NEAR
Data Memory
8KB
SFR Space
2KB
SRAM Space
Dual Port
DMA RAM
2KB
Optional window
into Program
Memory using PSV
32KB
NOTE: PIC24
devices don't
differentiate
between X and
Y data RAM
DIRECTLY
ADDRESSIBLE
POINTERS
REQUIRED
0x1FFF
0x2000 0x2001
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 8
Program Memory Map
16-bit PIC
Architecture
Reset Vector
Primary Interrupt
Vector Table
Alternate Interrupt
Vector Table
User Flash
Data EEPROM (dsPIC30F)
Flash Configuration Words
Configuration Registers
Device ID
24-bits
0x000000
0x000004
0x000200
0x7FFFFE
MSW LSW
0x000001
0x000005
0x000201
0x7FFFFF
0xFFFFFE 0xFFFFFF
0x0000FE 0x0000FF
LSW
Address
MSW
Address
Program Counter
Increments by 2
(program word
address is always
even)
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 9
Program Space Visibility Window
16-bit PIC
Architecture
0x8000
0xFFFF
Any 32kB
segment of
flash program
memory
Store constant
data here
PSV Window:
Read data in
flash as if it
were in RAM
(only lower 16-bits)
Read constant
data here
24-bit Program Memory
(Flash)
16-bit Data Memory
(RAM)
9FD3
9FD3
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 10
Programmer's Model
16-bit PIC
Architecture
Divide Quotient
Divide Remainder
X Address Pointer
X Address Pointer
Y Address Pointer
Y Address Pointer
MAC Pre-fetch Offset
MAC Write Back Pointer
Frame Pointer
Stack Pointer
15 0
W0
W1
W2
W3
W4
W5
W6
W7
W8
W9
W10
W11
W12
W13
W14
W15
W Registers:
General Purpose
Data Registers or
Address Pointers
WREG in File Register Operations
DSP Operand Registers
DSP Address Registers
Stack Pointer Limit
SPLIM
MPLAB
C for dsPIC
and PIC24
MPLAB
C for dsPIC
and PIC24
Toolset Overview
Toolset Overview
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 12
MPLAB
C for dsPIC
and PIC24
Overview
ANSI x3.1989 compliant
Optimizing compiler
Includes language extensions for
Microchips 16-bit architectures
Ported from GCC (GNU) compiler from the
Free Software Foundation
Works as a component of MPLAB
IDE
MPLAB MPLAB
C30 Student Edition is available for free C30 Student Edition is available for free
from the Microchip web site. from the Microchip web site.
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 13
.a
Linker
.o
Development Tools Data Flow
C Compiler
(and Preprocessor)
Archiver
(Librarian)
MPLAB IDE
Debug Tool
C Source Files
Assembly Source Files
Assembly Source Files
Object
Files
Object File Libraries
(Archives)
Linker Script
COFF Debug File
Executable
Compiler
Driver
Program
Assembler
.h
C Header Files
.inc
Assembly Include Files
.gld
.hex
.cof
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 14
MPLAB
C for dsPIC
and PIC24
Header Files
One header file per device:
Provides access to registers as C variables
Defines labels for bit manipulation
Defines macros to utilize instructions not
normally accessible from C
p24FJ128GA010.h
C:\ProgramFiles\Microchip\MPLABC30\Support\PIC24F\h
Header files are included as part of the
MPLAB C30 installation and are located in
the following directory:
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 15
MPLAB
C for dsPIC
and PIC24
Linker Scripts
One linker script file per device:
Defines memory sections and boundaries
Associates ISR names with interrupt vectors
Equates register variables with addresses
p24FJ128GA010.gld
C:\ProgramFiles\Microchip\MPLABC30\Support\PIC24F\gld
Linker Script files are included as part of the
MPLAB C30 installation and are located in
the following directory:
.gld
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 16
MPLAB
C for dsPIC
and PIC24
Startup and Initialization
goto __reset
Interrupt Vectors
__reset:
... ...
... ...
call _main
_main:
... ...
... ...
... ...
.c
.o
crt0.o or crt1.o (from libpic30.a)
main.c
Program Memory
C Runtime Environment Setup Code
Inserted automatically by LINK30 Linker
(Source files: crt0.s and crt1.s)
Your C code's main() routine.
Included by you in your project and
placed in memory by LINK30 Linker
Reset Vector (Address 0x000000)
Populated automatically by LINK30 Linker
Calls runtime environment setup code in
crt0.o ( __reset label)
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 17
MPLAB
C for dsPIC
and PIC24
Data Representation
Multibyte quantities are stored in "little
endian" format:
LSB is stored at lowest address
LSb is stored at lowest numbered bit position
0 15
4321
4321
8765
8765
How the value 0x87654321 is stored
In Data Memory (RAM) @ 0x100 In Working Registers W4 & W5
0x0FE
0x100
0x102
0x104
0x0FF
0x101
0x103
0x105
W4
W5
43
43
21
21
87
87
65
65
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 18
MPLAB
C for dsPIC
and PIC24
Integer Data Types
Type Bits Min Max
char char, signed , signed char char
8 8 - -128 128 127 127
unsigned unsigned char char
8 8 0 0 255 255
short short, signed , signed short short
16 16 - -32768 32768 32767 32767
unsigned unsigned short short
16 16 0 0 65535 65535
int int, signed , signed int int
16 16 - -32768 32768 32767 32767
unsigned unsigned int int
long, signed long, signed long long
unsigned unsigned long long
long long long long, signed , signed long long long long
unsigned unsigned long long long long
16 16 0 0 65535 65535
32 32 - -2 2
31 31
2 2
31 31
- - 1 1
32 32 0 0 2 2
32 32
- - 1 1
64 64 - -2 2
63 63
2 2
63 63
- - 1 1
64 64 0 0 2 2
64 64
- - 1 1
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 19
MPLAB
C for dsPIC
and PIC24
Floating Point Data Types
Type Bits E Min E Max N Min N Max
float float
double double * *
long double long double
32 32
32 32
64 64
- -126 126
- -126 126
- -1022 1022
127 127
127 127
1023 1023
2 2
- -126 126
2 2
- -126 126
2 2
- -1022 1022
2 2
127 127
2 2
127 127
2 2
1023 1023
Type Bits |Min| |Max|
float float
double double * *
long double long double
32 32
32 32
64 64
1.175494 1.175494 10 10
- -38 38
1.175494 1.175494 10 10
- -38 38
2.22507385 2.22507385 10 10
- -308 308
3.40282346 3.40282346 10 10
38 38
3.40282346 3.40282346 10 10
38 38
1.79769313 1.79769313 10 10
308 308
E = Exponent
N = Normalized (approximate)
* double is equivalent to long double if fno-shortt-double command line option is used
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 20
MPLAB
C for dsPIC
and PIC24
Pointers
All pointers are 16-bits in size, regardless
of whether they are data pointers or
program pointers
Constants in flash viewed via PSV
Jump tables sometimes used for program
pointers (handles)
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 21
Labcenter Proteus VSM
Virtual Prototyping
for all PIC MCU
families
Simulate complete
embedded systems
Develop and debug
your firmware on
virtual hardware
Test and verify
before ordering your
prototype
www.labcenter.com
Schematic
simulation of
Microchip
evaluation board
Lab Exercise 1
Lab Exercise 1
Creating an MPLAB
C Based Project
with MPLAB IDE Step-by-step
Creating an MPLAB
C Based Project
with MPLAB IDE Step-by-step
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 23
Lab Exercise 1
Creating an MPLAB
C Based Project
Purpose
The purpose of this lab is to illustrate the steps required to create an
MPLAB C30 based project within the MPLAB Integrated Development
Environment. You will learn how to select the compiler as the build tool,
which files must be included in your project, how to allocate a heap and
what code must be included in your source file.
Procedure
Open MPLAB and start the project
wizard by selecting from the menu:
Project Project Wizard
Click to continue
Next>
After the Project Wizard opens,
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 24
Lab Exercise 1
Creating an MPLAB
C Based Project
In the Device combo box, select:
PIC24FJ128GA010
Click to continue
Next>
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 25
Lab Exercise 1
Creating an MPLAB
C Based Project
In the Active Toolsuite combo box, select:
Microchip C30 Toolsuite
Click to continue
Next>
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 26
Lab Exercise 1
Creating an MPLAB
C Based Project
Click and navigate to:
Browse
C:\MTT\TLS2130\Lab1
Then name the file Lab1.mcp
C:\MTT\TLS2130\Lab1\Lab1
CreateNewProjectFile
Click to continue
Next>
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 27
Lab Exercise 1
Creating an MPLAB
C Based Project
C:\MTT\TLS2130\Lab1
Add source files to the project. In
the left hand list box, navigate to:
Select the file Lab1.c
Click
Add>>
Select the file TLS2130.a
Click
Add>>
Add library file to the
project:
Click to continue
Next>
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 28
Lab Exercise 1
Creating an MPLAB
C Based Project
Click
Finish
Lab 1 Project Tree
View Project
If the project tree isn't visible,
select from the menu:
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 29
Lab Exercise 1
Creating an MPLAB
C Based Project
Open the project build options by selecting from the menu:
Project BuildOptions Project
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 30
Lab Exercise 1
Creating an MPLAB
C Based Project
Select the MPLABLINK30
tab at the top of the window.
In the Heapsize box, enter a
value of 128 bytes.
The value of 128 bytes is
somewhat arbitrary. Your
application may require a
larger or smaller heap, or
possibly no heap at all.
Click
OK
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 31
Lab Exercise 1
Creating an MPLAB
C Based Project
Device specific header file (required to access device features)
Standard C and Microchip library header files (if used)
Header files for your own libraries (if used)
Add the minimum required framework to your soruce code in Lab1.c.
In the project tree, double click on the file Lab1.c
Lab1.c
15
16
17
#include the header files required by your application.
#include <p24fj128ga010.h>
#include <stdio.h>
#include "TLS2130.h"
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 32
_CONFIG1(FWDTEN_OFF & JTAGEN_OFF)
Lab Exercise 1
Creating an MPLAB
C Based Project
Use _CONFIG1 and _CONFIG2 macros (defined in header file)
Bitwise AND list of option constants (defined in header file)
Unspecified options will use their default settings
Add the minimum required framework to your soruce code in Lab1.c.
Lab1.c
19
Setup device configuration bits in code
This is the minimum required configuration for the Explorer 16 Demo Board.
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 33
Lab Exercise 1
Creating an MPLAB
C Based Project
Enable MPLAB REAL ICE by selecting from the menu:
Debugger SelectTool ProteusVSM
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 34
Lab Exercise 1
Creating an MPLAB
C Based Project
Select Debug mode.
Click BuildAllbutton.
If no errors reported,
Click StartSimulation
button.
When programming
completes,click Reset
button.
Click Runbutton.
Click Haltbutton.
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 35
Lab Exercise 1
Creating an MPLAB
C Based Project
Results
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 36
Lab Exercise 1
Creating an MPLAB
C Based Project
Minimum steps to setup a C based project:
Follow standard MPLAB
Configuration Bits
How to Set PIC
Configuration Bits
Using the _CONFIG1() and _CONFIG2() Macros
Using the _CONFIG1() and _CONFIG2() Macros
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 38
What are Configuration Bits?
Used to setup device
features:
Code Protect
Watchdog Timer
JTAG
Oscillator Options
Debug Options
More
Reset Vector
Primary Interrupt
Vector Table
Alternate Interrupt
Vector Table
User Flash
Data EEPROM (dsPIC30F)
Flash Configuration Words
Configurations Registers
Device ID
24-bit Program Memory
CONFIG1 and CONFIG2 Located in
program memory space, outside
range of executable code space
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 39
Flash Configuration Word 1
CONFIG1
CONFIG1 (PIC24FJ128GA010)
bit 23 bit 16
U-1
- - - - - - - -
U-1 U-1 U-1 U-1 U-1 U-1 U-1
Upper Third:
bit 15 bit 8
r-0
r JTAGEN GCP GWRP DEBUG COE - ICS
R/PO-1 R/PO-1 R/PO-1 R/PO-1 R/PO-1 U-1 R/PO-1
Middle Third:
bit 7 bit 0
R/PO-1
FWDTEN WINDIS - FWPSA WDTPS3 WDTPS2 WDTPS1 WDTPS0
R/PO-1 U-1 R/PO-1 R/PO-1 R/PO-1 R/PO-1 R/PO-1
Lower Third:
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 40
Flash Configuration Word 1
_CONFIG1(x) Macro
Defined in device specific header files
x is formed by anding together constants
representing configuration bit values
Omitted bits retain their default value
_CONFIG1(x) Macro Definition
#define _CONFIG1(x)
__attribute__((section("__CONFIG1.sec,code")))
int _CONFIG1 = (x);
Example
_CONFIG1(FWDTEN_OFF & JTAGEN_OFF)
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 41
_CONFIG1(x)
Parameter List Options
JTAG JTAGEN_OFF Disabled
JTAGEN_ON Enabled
ICD Pins Select ICS_PGx1 EMUC/EMUD share PGC1/PGD1
ICS_PGx2 EMUC/EMUD share PGC2/PGD2
Clip-On Emulation COE_ON Enabled
COE_OFF Disabled
Background Debug BKBUG_ON Enabled
BKBUG_OFF Disabled
Code Protect GCP_ON Enabled
GCP_OFF Disabled
Write Protect GWRP_ON Enabled
GWRP_OFF Disabled
Windowed WDT WINDIS_ON Enabled
WINDIS_OFF Disabled
Watchdog Timer FWDTEN_OFF Disabled
FWDTEN_ON Enabled
_CONFIG1(x) Macro Parameter List Options for PIC24FJ128GA010 (Part 1)
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 42
_CONFIG1(x)
Parameter List Options Continued
Watchdog Prescaler FWPSA_PR32 1:32
FWPSA_PR128 1:128
Watchdog Postscaler WDTPS_PS1 1:1
WDTPS_PS2 1:2
WDTPS_PS4 1:4
WDTPS_PS8 1:8
WDTPS_PS16 1:16
WDTPS_PS32 1:32
WDTPS_PS64 1:64
WDTPS_PS128 1:128
WDTPS_PS256 1:256
WDTPS_PS512 1:512
WDTPS_PS1024 1:1024
WDTPS_PS2048 1:2048
WDTPS_PS4096 1:4096
WDTPS_PS8192 1:8192
WDTPS_PS16384 1:16384
WDTPS_PS32768 1:32768
_CONFIG1(x) Macro Parameter List Options for PIC24FJ128GA010 (Part 2)
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 43
Flash Configuration Word 2
CONFIG2
CONFIG2 (PIC24FJ128GA010)
bit 23 bit 16
U-1
- - - - - - - -
U-1 U-1 U-1 U-1 U-1 U-1 U-1
Upper Third:
bit 15 bit 8
R/PO-1
IESO - - - - FNOSC2 FNOSC1 FNOSC0
U-1 U-1 U-1 U-1 R/PO-1 R/PO-1 R/PO-1
Middle Third:
bit 7 bit 0
R/PO-1
FCKSM1 FCKSM0 OSCIOFCN - - - POSCMD1 POSCMD0
R/PO-1 R/PO-1 U-1 U-1 U-1 R/PO-1 R/PO-1
Lower Third:
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 44
Flash Configuration Word 2
_CONFIG2(x) Macro
Defined in device specific header files
x is formed by anding together constants
representing configuration bit values
Omitted bits retain their default value
_CONFIG2(x) Macro Definition
#define _CONFIG2(x)
__attribute__((section("__CONFIG2.sec,code")))
int _CONFIG2 = (x);
Example
_CONFIG2(FNOSC_PRIPLL & POSCMOD_HS & OSCIOFNC_OFF)
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 45
_CONFIG2(x)
Parameter List Options
Two Speed Startup IESO_OFF Disabled
IESO_ON Enabled
Oscillator Type POSCMOD_EC External Clock
POSCMOD_XT XT Oscillator
POSCMOD_HS HS Oscillator
POSCMOD_NONE Primary Disabled
OSC2/RC15 Function OSCIOFNC_ON RC15
OSCIOFNC_OFF OSCO or F
OSC
/2
Oscillator Selection FNOSC_FRC Fast RC Oscillator
FNOSC_FRCPLL Fast RC Oscillator with divide and PLL
FNOSC_PRI Primary Oscillator (XT, HS, EC)
FNOSC_PRIPLL Primary Oscillator (XT, HS, EC) with PLL
FNOSC_SOSC Secondary Oscillator
FNOSC_LPRC Low Power RC Oscillator
FNOSC_FRCDIV Fast RC Oscillator with divide
Clock Switching & Monitor FCKSM_CSECME Both Enabled
FCKSM_CSECMD Only Clock Switching Enabled
FCKSM_CSDCMD Both Disabled
_CONFIG2(x) Macro Parameter List Options for PIC24FJ128GA010
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 46
How to Set PIC
Configuration Bits
_CONFIGn(x) macros must be used
anywhere after the #include for the
device specific header file
Example
/******************************************************
* PROGRAM: main.c
* AUTHOR: Clem Finch
******************************************************/
#include <p24fj128ga010.h>
#include "TLS2130.h"
_CONFIG1(FWDTEN_OFF & JTAGEN_OFF);
_CONFIG2(FNOSC_PRIPLL & POSCMOD_HS & OSCIOFNC_OFF);
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 47
Where is all this stuff defined?
Parameter labels for _CONFIGn(x) macros:
At the end of the device specific header files
(e.g. p24fj128ga010.h)
CONFIGn Register Descriptions:
In the data sheet under "Special Features" in
the "Configuration Bits" subsection
CONFIG Bits Functional Descriptions:
In the data sheet under the relevant section
(e.g. WDT under "Special Features" section in
"Watchdog Timer" subsection)
Lab Exercise 2
Lab Exercise 2
Setting PIC
IDE
Oscillator = HS, Primary with PLL
OSC2/RC15 Function = OSC2
Clock Switching & Monitor = Both Disabled
JTAG = Disabled
Watchdog Timer = Disabled
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 50
Lab Exercise 2
Setting PIC
I/O ports
1
Initialize Output
Latches to Known
State
Write to: LATx = 0;
LATxbits.LATxn = 0;
_LATxn = 0;
2
Configure Data
Direction of Pins
Write to: TRISx = 0x0023;
TRISxbits.TRISxn = 1;
_TRISxn = 1;
3a
Write to outputs
Write to: LATx = 0x00F0;
LATxbits.LATxn = 0;
_LATxn = 0;
3b
Read from inputs
Read from: myVar = PORTx;
myVar = PORTxbits.Rxn;
myVar = _Rxn;
LAT
LAT
TRIS
PORT
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 64
How to Read Input Pins
Switch Debouncing
Switch inputs must be debounced to
prevent multiple false detections while
switch contact settles
Debounce routine provided in TLS2130.a
Function prototype provided in TLS2130.h
t
v(t)
3.3V
0V
v
ih
v
il
Switch Open
Switch Closed
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 65
How to Read Input Pins
Switch Debouncing
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 66
How to Read Input Pins
Switch Debouncing
Written especially for this class
Takes port pin variable as parameter
Returns TRUE if switch is pressed
Returns FALSE if switch is not pressed
Function Prototype
Example
unsigned char SwitchPressed(volatile unsigned *sw, int bit);
if (SwitchPressed(&PORTD, 6))
{
// Do something if switch is pressed
}
Lab Exercise 3
Lab Exercise 3
Working with I/O Ports
Working with I/O Ports
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 68
Lab Exercise 3
Working with I/O Ports
Use the provided function SwitchPressed()
to read and debounce S3 which is
connected to bit 6 of PORTD
While S3 pressed, turn on LED on RA0
While S3 not pressed, turn off LED on RA0
Objective
Use the SwitchPressed() function to read S3. As long as S3
is pressed, LED D3 should be on. When S3 is released, LED
D3 should be off.
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 69
Lab Exercise 3
Working with I/O Ports
Procedure
Follow the directions in the lab manual starting on page 3-1.
On the lab PC
Open the lab workspace by selecting from the menu:
File OpenWorkspace
and select the file:
C:\MTT\TLS2130\Lab3\Lab3.mcw
If you currently have a project or workspace open,
close it now by selecting from the menu:
File CloseWorkspace
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 70
Lab Exercise 3
Working with I/O Pins
Results
D3
D3
LATAbits.LATA0 = 1 OR _LATA0 = 1
SwitchPressed(&PORTD, 6)
Read RD6 via provided function:
Write to RA0 using LATA:
S3
S3
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 71
Lab3.c One possible solution
#include <p24fj128ga010.h>
#include "TLS2130.h"
_CONFIG1(FWDTEN_OFF & JTAGEN_OFF)
int main(void)
{
_TRISA0 = 0;
while(1)
{
_LATA0 = 0;
while(SwitchPressed(&PORTD, 6))
_LATA0 = 1;
}
}
Lab Exercise 3
Working with I/O Pins
Make bit 0 of PORTA an output
Turn off LED on bit 0 of PORTA
Turn on LED on bit 0 of PORTA
Read switch
on bit 6 of
PORTD
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 72
Conclusions
Lab Exercise 3
Working with I/O Pins
TRIS registers determine I/O pin direction
LAT registers used to write outputs
PORT registers used to read inputs
Switch inputs must be debounced
Header files make it possible to work with an
entire register (REGNAME) or individual bits
(REGNAMEbits.BITNAME or _BITNAME)
The C Runtime Environment
The C Runtime Environment
A Foundation for C Programs
A Foundation for C Programs
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 74
Program Memory (Flash)
The Compilers Viewpoint
Fixed locations in
hardware
Reset Vector
Traps
Alternate Traps
Interrupt Vectors
Alternate Interrupt
Vectors
Vectors
.handle
.text
.dinit
.const
000000
7FFFFF
Vectors
24-bits
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 75
Program Memory (Flash)
The Compilers Viewpoint
Function Pointers
Allows use of 16-bit
pointers in RAM to
access 24-bit
program memory
addresses
Implements table of
GOTO instructions
Vectors
.handle
.text
.dinit
.const
000000
7FFFFF
Far Code Handles
24-bits
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 76
Program Memory (Flash)
The Compilers Viewpoint
User Code
All executable code is
placed here
Initialization code
placed here under the
section name .init
Vectors
.handle
.text
.dinit
.const
000000
7FFFFF
General Program Storage
24-bits
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 77
Program Memory (Flash)
The Compilers Viewpoint
Constants used to
initialize:
Initialized Variables
( e.g. int x = 10; )
Constants in RAM
Values copied into
RAM by startup code
Vectors
.handle
.text
.dinit
.const
000000
7FFFFF
Data Memory Initializers
24-bits
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 78
Program Memory (Flash)
The Compilers Viewpoint
Constants accessed
via 32kB PSV window
in RAM
Constants declared
with const keyword
Managed via auto PSV
feature
Vectors
.handle
.text
.dinit
.const
000000
7FFFFF
Constants in Flash
24-bits
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 79
Data Memory (RAM)
The Compilers Viewpoint
SFR
.nbss, .ndata,
.pbss, .ndconst
.bss, .data,
.dconst
heap
.const
stack
0000
2000
FFFF
N
E
A
R
F
A
R
8000
Special Function Registers
Hardware Registers
Fixed Addresses
16-bits
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 80
Data Memory (RAM)
The Compilers Viewpoint
SFR
.nbss, .ndata,
.pbss, .ndconst
.bss, .data,
.dconst
heap
.const
stack
0000
2000
FFFF
N
E
A
R
F
A
R
8000
Uninitialized Variables
e.g. int x;
.nbss in near space
.bss in far space
16-bits
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 81
Data Memory (RAM)
The Compilers Viewpoint
SFR
.nbss, .ndata,
.pbss, .ndconst
.bss, .data,
.dconst
heap
.const
stack
0000
2000
FFFF
N
E
A
R
F
A
R
8000
Initialized Variables
e.g. int x = 10;
.ndata in near space
.data in far space
Initial values copied
from .dinit in flash
by startup code
16-bits
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 82
Data Memory (RAM)
The Compilers Viewpoint
SFR
.nbss, .ndata,
.pbss, .ndconst
.bss, .data,
.dconst
heap
.const
stack
0000
2000
FFFF
N
E
A
R
F
A
R
8000
Persistent Variables
Data unaffected by
reset
Not modified by
startup code
Located in near
memory
16-bits
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 83
Data Memory (RAM)
The Compilers Viewpoint
SFR
.nbss, .ndata,
.pbss, .ndconst
.bss, .data,
.dconst
heap
.const
stack
0000
2000
FFFF
N
E
A
R
F
A
R
8000
Constants in RAM
.ndconst in near if small
model used
.dconst in far if large
model used
Created if -mconst-in-
code switch not used
Values copied
from .dinit in flash by
startup code
16-bits
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 84
Data Memory (RAM)
The Compilers Viewpoint
SFR
.nbss, .ndata,
.pbss, .ndconst
.bss, .data,
.dconst
heap
.const
stack
0000
2000
FFFF
N
E
A
R
F
A
R
8000
Heap
Allocated if a heap
declared in MPLAB
Size determined by
user
16-bits
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 85
Data Memory (RAM)
The Compilers Viewpoint
SFR
.nbss, .ndata,
.pbss, .ndconst
.bss, .data,
.dconst
heap
.const
stack
0000
2000
FFFF
N
E
A
R
F
A
R
8000
Stack
Automatically
allocated by linker
Occupies all
unallocated RAM
(by default)
Grows toward higher
addresses
16-bits
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 86
Data Memory (RAM)
The Compilers Viewpoint
SFR
.nbss, .ndata,
.pbss, .ndconst
.bss, .data,
.dconst
heap
.const
stack
0000
2000
FFFF
N
E
A
R
F
A
R
8000
Constants in Code
32kB PSV window
used to read
constants
from .const in flash
as if they were in RAM
No RAM exists above
address 8000h
16-bits
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 87
Data Memory (RAM) for DSP
The Compilers Viewpoint
.xbss, .xdata
.ybss, .ydata
0000
2000
FFFF
N
E
A
R
F
A
R
8000
X and Y Memory
Used by MAC Class
Instructions
Non-DSP instructions
see all memory as X
Size and address
range of Y memory
varies from one
device to another
.xbss, .xdata
Uninitialized
Initialized
16-bits
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 88
Startup and Initialization
goto __reset
Interrupt Vectors
__reset:
... ...
... ...
call _main
_main:
... ...
... ...
... ...
.c
.o
crt0.o or crt1.o (from libpic30.a)
main.c
Program Memory
C Runtime Environment Setup Code
Inserted automatically by LINK30 Linker
(Source files: crt0.s and crt1.s)
Your C code's main() routine.
Included by you in your project and
placed in memory by LINK30 Linker
Reset Vector (Address 0x000000)
Populated automatically by LINK30 Linker
Calls runtime environment setup code in
crt0.o ( __reset label)
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 89
Startup and Initialization
Tasks Performed by Default Startup Module crt0.o
Initialize Stack Pointer (W15)
Initialize Stack Pointer Limit Reg. (SPLIM)
Setup PSV window to view .const in flash
Clear uninitialized data sections
Copy data from .dinit in flash to
initialized data sections in RAM
Call items like user_init
Call main() with no parameters
If main() returns, reset processor
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 90
Startup and Initialization
Tasks Performed by Alternate Startup Module crt1.o
Performs all steps taken by crt0.o except:
Does NOT clear uninitialized data sections
Does NOT load initialized data sections with
values from .dinit
Alternate startup module is much smaller
Can be selected to conserve program
memory if data initialization is not required
The persistent data section The persistent data section .pbss .pbss is never is never
cleared or initialized by either startup module. cleared or initialized by either startup module.
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 91
Selecting the Alternate Startup Module crt1.o
Startup and Initialization
How to Select the Alternate Startup Module crt1.o
1 Open Project Settings
From the menu bar, select:
Project BuildOptions Project
2 Select Linker Options
From the tabs, select:
MPLABLINK30
3 Select Symbols & Output
From the Categories combo box select:
General
4 Disable data initialization
In the Output check box group, check:
Don'tinitializedatasections
2
4
3
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 92
Startup modules may be modified if needed
Source code (assembly) provided in:
C:\ Program Files\ Microchip\ MPLAB C30\ src\ pic30\ crt*.s
If main() needs to be called with parameters,
a conditional assembly directive may be
switched to provide this support
Custom code may be run before startup code
Startup and Initialization
Modifying the Startup Module
Memory Models
Memory Models
Object Allocation Schemes
Object Allocation Schemes
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 94
Memory Models
Overview
Option Memory Definition Description
Small Data Small Data
- -msmall msmall- -data data
Small Scalar Small Scalar
- -msmall msmall- -scalar scalar
Large Data Large Data
- -mlarge mlarge- -data data
Small Code Small Code
- -msmall msmall- -code code
Large Code Large Code
- -mlarge mlarge- -code code
Constants Constants
in Data in Data
- -mconst mconst- -in in- -data data
Constants Constants
in Code in Code
- -mconst mconst- -in in- -code code
Up to 8 KB of data memory. Up to 8 KB of data memory.
This is the default. This is the default.
Permits use of direct addressing for Permits use of direct addressing for
accessing data memory. accessing data memory.
Up to 8 KB of data memory. Up to 8 KB of data memory.
This is the default. This is the default.
Permits use of direct addressing for Permits use of direct addressing for
accessing scalars in data memory. accessing scalars in data memory.
Greater than 8KB of data memory. Greater than 8KB of data memory.
Up to 32 Kw of program memory. Up to 32 Kw of program memory.
This is the default. This is the default.
Greater than 32 Kw of program Greater than 32 Kw of program
memory. memory.
Constants located in data memory. Constants located in data memory.
Constants located in program Constants located in program
memory. memory. This is the default. This is the default.
Uses indirection for data references. Uses indirection for data references.
No jump table for function pointers. No jump table for function pointers.
Function calls use RCALL instruction. Function calls use RCALL instruction.
Function pointers might use jump table. Function pointers might use jump table.
Function calls use CALL instruction. Function calls use CALL instruction.
Values copied from program memory by Values copied from program memory by
startup code. startup code.
Values are accessed via Program Space Values are accessed via Program Space
Visibility (PSV) data window. Visibility (PSV) data window.
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 95
8kB
Memory Models
Small Data
Default Model
All data fits in first 8kB
Direct Addressing Used
(no pointers required)
Fastest data access
Smallest code to
access data
Data Memory (RAM)
0x0000
0x2000
NEAR
FAR
0xFFFF
0x8000
PSV Window
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 96
Non-Scalar
Data Goes Here
8kB
Memory Models
Small Scalar Data
Scalar data in first 8kB
Direct addressing used
with scalar data
(no pointers required)
Non-scalar data (arrays,
structures) in far space
Indirect addressing
(pointers) used with
non-scalar data
Data Memory (RAM)
0x0000
0x2000
NEAR
FAR
0xFFFF
0x8000
PSV Window
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 97
8kB
Memory Models
Large Data
All data cannot fit in
first 8kB
All data treated as if it
is in far space
All data accessed
indirectly (pointers)
Data Memory (RAM)
0x0000
0x2000
NEAR
FAR
0xFFFF
0x8000
PSV Window
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 98
Memory Models
Small Code
Default Model
All calls may jump
only 32k words
No jump table for
function pointers
Function calls use
rcall instruction
Program Memory (Flash)
0x000000
0x7FFFFF
32k
32k
You
are
here
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 99
Memory Models
Large Code
Calls are not within
32k words
Jump table may be
used for function
pointers
Function calls use
call instruction
Program Memory (Flash)
0x000000
0x7FFFFF
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 100
C30 Project Creation Build Optoins
Memory Models
How to Select the Memory Model
1 Open Project Build Options
From the menu bar, select:
Project BuildOptions Project
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 101
C30 Project Creation Build Options
Memory Models
How to Select the Memory Model
2 Go to Memory Models
Select the MPLABC30 tab
Select the MemoryModel category
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 102
C30 Project Creation Build Options
Memory Models
How to Select the Memory Model
3 Select Desired Models
(small) (code)
(small) (small)
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 103
Memory Models
Tips & Tricks
Inappropriate model for your program can
cause compile or link errors
As your program grows, you may need to
change the memory model
If desired, you have full control over where
objects are placed in memory
Use small model, but force some objects into
far memory
Compile different modules with different
models
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 104
Memory Models
Tips & Tricks
Compiler can often generate more
compact code if variables in near data
Option Tips for Optimal Memory Use
Use if all variables for the application can fit within 8KB Use if all variables for the application can fit within 8KB Small Data Small Data
Use if all scalar type variables (no arrays or structures) for Use if all scalar type variables (no arrays or structures) for
the application can fit within 8KB the application can fit within 8KB
Small Scalar Small Scalar
Large Data Large Data
1. Compile some individual modules using the Small Data or 1. Compile some individual modules using the Small Data or
Small Scalar option. Then include their compiled object Small Scalar option. Then include their compiled object
modules in the Large Data project. modules in the Large Data project.
2. Tag individual variables with the 2. Tag individual variables with the near near attribute attribute
Small Data or Small Data or
Small Scalar Small Scalar
If all data doesn If all data doesn t fit in near space, tag some variables with t fit in near space, tag some variables with
the the far far attribute attribute so others have space to fit in near data. so others have space to fit in near data.
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 105
Memory Models
Tips & Tricks
Functions that are near (within 32k radius)
may call each other more efficiently
1. Use if all functions are within 32kw of each other. 1. Use if all functions are within 32kw of each other.
2. Compile some modules using Small Code and include 2. Compile some modules using Small Code and include
their object files in a Large Code project. their object files in a Large Code project.
3. If not all functions are within 32kw of each other, tag some 3. If not all functions are within 32kw of each other, tag some
functions with the functions with the far far attribute attribute. .
Small Code Small Code
Option Tips for Optimal Memory Use
Large Code Large Code
1. Tag some functions with the 1. Tag some functions with the near near attribute attribute. An error will . An error will
be generated if the function cannot be reached by one of its be generated if the function cannot be reached by one of its
callers using the more efficient form of the function call. callers using the more efficient form of the function call.
Attributes
Attributes
GCCs Replacement for #pragma
GCCs Replacement for #pragma
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 107
Definition
Attributes
Used to describe variables or functions
Help compiler to generate optimized code
Help compiler to optimize memory use
Establish rules for how particular variables
or functions are to be handled with respect
to the C runtime environment
Attributes Attributes are used to tell the compiler about certain are used to tell the compiler about certain
behaviors or features of a variable, a function or a type. behaviors or features of a variable, a function or a type.
Attributes are specified using the keyword Attributes are specified using the keyword __attribute__ __attribute__
followed by a list of attributes within double parentheses. followed by a list of attributes within double parentheses.
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 108
Attributes
Why attributes are used instead of ISO C's #pragma
According to the GCC developers:
It is impossible to generate #pragma
commands from a macro
"There is no telling what the same #pragma
might mean in another compiler"
In short, attributes are much more
versatile than the traditional #pragma
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 109
Examples
Syntax
type type identifier identifier __attribute__(( __attribute__((attribute attribute- -list list)) )); ;
Variable Attributes
How to Declare a Variable with Attributes
Multiple attributes are separated by commas
within the double parentheses
Attributes may be before or after identifier
Note: There are two underscores before and
after the keyword __attribute__
int int a[10] __attribute__((section(".xdata"))) a[10] __attribute__((section(".xdata"))); ;
int int __attribute__((aligned(16))) b[10] __attribute__((aligned(16))) b[10]; ;
int int x __attribute__((near)) x __attribute__((near)); ;
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 110
Variable Attributes
Supported Attributes for Variables
address
aligned
deprecated
far
secure
near
noload
packed
persistent
reverse
section
sfr
space
transparent_union
unordered
unused
weak
Attributes may be specified with a leading and trailing Attributes may be specified with a leading and trailing
double underscore to distinguish them from other entities double underscore to distinguish them from other entities
in your code with the same name (e.g. in your code with the same name (e.g. __aligned__ __aligned__). ).
and many more
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 111
Examples
Syntax
type type identifier identifier() () __attribute__(( __attribute__((attribute attribute- -list list)) )) { { } }
Function Attributes
How to Declare a Function with Attributes
Multiple attributes are separated by commas
within the double parentheses
Attributes may be before or after identifier
Note: There are two underscores before and
after the keyword __attribute__
int int foo(void) __attribute__((address(0x100))) foo(void) __attribute__((address(0x100))) { { } }
int int __attribute__((address(0x500))) __attribute__((address(0x500))) bar(void) bar(void) { { } }
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 112
Function Attributes
Supported Attributes for Functions
address
alias
const
deprecated
far
format
format_arg
interrupt
near
no_instrument_function
noload
noreturn
section
shadow
unused
weak
Attributes may be specified with a leading and trailing Attributes may be specified with a leading and trailing
double underscore to distinguish them from other entities double underscore to distinguish them from other entities
in your code with the same name (e.g. in your code with the same name (e.g. __address__ __address__). ).
and many more
How to Override the
Default Characteristics of
Variables and Functions
How to Override the
Default Characteristics of
Variables and Functions
Using Attributes
Using Attributes
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 114
Examples
near Attribute Syntax
Locating Objects in Memory
How to place an object in near memory
Specifies that a function or variable should
be located in near memory
Treats a function or variable as if one of the
small memory models were being used
Should be accessed more efficiently
__attribute__((near)) __attribute__((near))
int int x __attribute__((near)) x __attribute__((near)); ;
int int foo foo( (void void) ) __attribute__((near)) __attribute__((near)) { { } }
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 115
8kB
Locating Objects in Memory
Manually Optimizing Data Memory Use
Use large data model
Tag frequently
accessed variables
with near attribute
Data Memory (RAM)
0x0000
0x2000
NEAR
FAR
0xFFFF
0x8000
PSV Window
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 116
Examples
near Attribute Syntax
Locating Objects in Memory
How to place an object in far memory
Specifies that a function or variable should
be located in far memory
Treats a function or variable as if one of the
large memory models were being used
Might require extra overhead
__attribute__((far)) __attribute__((far))
int int x __attribute__((far)) x __attribute__((far)); ;
int int foo foo( (void void) ) __attribute__((far)) __attribute__((far)) { { } }
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 117
8kB
Locating Objects in Memory
Manually Optimizing Data Memory Use
Use small data model
Let linker place most
variables in near space
(up to 8kB)
Tag infrequently
accessed variables
with far attribute
Makes room in near
space for frequently
accessed variables
Allows more than 8kB of
data with small model
Data Memory (RAM)
0x0000
0x2000
NEAR
FAR
0xFFFF
0x8000
PSV Window
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 118
Examples
space Attribute Syntax
Locating Objects in Memory
How to place a variable in X or Y data memory
Specifies that a variable should be located in
X (xmemory) or Y (ymemory) data memory
For dsPIC
devices only
Useful for variables operated on by MAC
class instructions
__attribute__((space( __attribute__((space(space space))) )))
int int coefficient[101] __attribute__((space(xmemory))) coefficient[101] __attribute__((space(xmemory))); ;
int int input[255] __attribute__((space(ymemory))) input[255] __attribute__((space(ymemory))); ;
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 119
Examples
space Attribute Syntax
Locating Objects in Memory
How to place a variable in EEPROM data memory
Specifies that a variable should be located in
EEPROM data memory
For dsPIC30 devices only
__attribute__((space(eedata))) __attribute__((space(eedata)))
int int coefficient[101] __attribute__((space(eedata))) coefficient[101] __attribute__((space(eedata))); ;
int int x __attribute__((space(eedata))) x __attribute__((space(eedata))); ;
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 120
Examples
space Attribute Syntax
Locating Objects in Memory
How to place a variable in DMA memory
Specifies that a variable should be located in
DMA data memory
For some PIC24 and dsPIC33 devices only
Many peripherals may read/write DMA
memory without intervention by program
__attribute__((space(dma))) __attribute__((space(dma)))
volatile int volatile int x __attribute__((space(dma))) x __attribute__((space(dma))); ;
volatile int volatile int input[16] __attribute__((space(dma))) input[16] __attribute__((space(dma))); ;
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 121
aligned Attribute Syntax
Locating Objects in Memory
How to align an object on a byte/word boundary
Specifies the minimum alignment for the variable,
measured in bytes
Useful on dsPIC
)
Overriding Default Behavior
Pre-defined Macros dsPIC
Devices
Same as PIC24 macros but
Provides separate macros for X and Y space
Provides macro for EEPROM Data Memory
(dsPIC30 only)
#define _XBSS(N) __attribute__((space(xmemory), aligned(N)))
#define _XDATA(N) __attribute__((space(xmemory), aligned(N)))
#define _YBSS(N) __attribute__((space(ymemory), aligned(N)))
#define _YDATA(N) __attribute__((space(ymemory), aligned(N)))
#define _EEDATA(N) __attribute__((space(eedata), aligned(N)))
#define _PERSISTENT __attribute__((persistent))
#define _NEAR __attribute__((near))
MPLAB C30 Compiler User's Guide (Rev E): Section 6.6.3, Page 83
MPLAB C30 Compiler User's Guide (Rev E): Section 6.6.3, Page 83
Interrupts
Interrupts
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 128
Definition
Interrupts
PIC24 / dsPIC interrupts are vectored
Interrupts require special functions to
service the events that cause them:
ISRs must not have any parameters
ISRs must not be called by the main code
ISRs should not call other functions
Interrupts Interrupts are events that cause your program to stop what are events that cause your program to stop what
it is doing in order to run an Interrupt Service Routine which it is doing in order to run an Interrupt Service Routine which
will handle the event by taking whatever action is required will handle the event by taking whatever action is required
before finally returning control to your main program. before finally returning control to your main program.
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 129
Interrupts
How to Declare an Interrupt Service Routine
No parameters and void return type (required)
Use pre-defined name (required)
Do NOT call from main line code (required)
Do not call other functions (recommended)
Interrupt Attribute Basic Syntax
void __attribute__((interrupt)) _ISRName(void)
{ }
Function Code Here
Example Interrupt Service Routine
void __attribute__((interrupt)) _INT0Interrupt(void)
{
//Ordinary C code goes here to handle interrupt
}
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 130
Interrupts
Interrupt Function Names
Interrupt Function names may be found in:
Device's Linker Script (e.g. p24fj128ga010.gld)
MPLAB
"instruction_n")
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 183
Example
Syntax
Inline Assembly
Extended Form
Works with optimizer better
More specific about which resources are used
Simplifies interaction between C and assembly
asm ( "template"
[:["constraint"(output_operand) [, ] ]
:["constraint"(input_operand) [, ] ]
:["clobbers" [, ] ] ]
);
asm ("mov %0, w0" : : "g" (myVar) : "W0");
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 184
Example
int x = 5, y = 2;
int foo(void)
{
int result;
asm("add %1, %2, %0"
: "=r" (result)
: "r" (x), "r" (y)
);
return result;
}
Inline Assembly
Passing C Variables
Before Operation:
0000
After Operation:
0007
result:
result:
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 185
a Claims WREG
b Divide support register W1
c Multiply support register W2
d General purpose data registers W1-W14
e Non-divide support registers W2-W14
g Any register, memory or immediate integer operand is allowed (except non-general registers)
i Any immediate integer operand (constant value) is allowed. Includes symbolic constants.
r A register operand is allowed provided that it is in a general register.
v AWB register W13
w Accumulator register A - B
x x pre-fetch registers W8-W9
y y pre-fetch registers W10-W11
z MAC pre-fetch registers W4-W7
0,1,9 An operand that matches the specified operand number is allowed.
T A near or far data operand.
U A near data operand.
Inline Assembly
Constraint Letters
Constraint Letters Supported by MPLAB C30
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 186
Inline Assembly Macros
Provide an easy way to execute specific
assembly language instructions that have
no C equivalent (builtins are even better)
Inline Assembly Macro Definitions
#define Nop() {__asm__ volatile ("nop");}
#define ClrWdt() {__asm__ volatile ("clrwdt");}
#define Sleep() {__asm__ volatile ("pwrsav #0");}
#define Idle() {__asm__ volatile ("pwrsav #1");}
Examples
Nop(); // Insert nop instruction
ClrWdt(); // Clear the watchdog timer
Sleep(); // Enter SLEEP mode
Idle(); // Enter IDLE mode
Mixing C and Assembly
Mixing C and Assembly
Multi-File Project Solutions
Multi-File Project Solutions
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 188
.a
Linker
.o
Development Tools Data Flow
C Compiler
(and Preprocessor)
Archiver
(Librarian)
MPLAB IDE
Debug Tool
C Source Files
Assembly Source Files
Assembly Source Files
Object
Files
Object File Libraries
(Archives)
Linker Script
COFF Debug File
Executable
Compiler
Driver
Program
Assembler
.h
C Header Files
.inc
Assembly Include Files
.gld
.hex
.cof
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 189
C_File.c
#include "p24fj128ga010.h"
unsigned int x = 0;
unsigned int foo();
int main(void)
{
foo();
while(1);
}
Using a C Variable in Assembly
In the C file
Declare a global or static variable in the usual
way (This won't work with non-static variables)
A global variable has a permanent address in
RAM and may be accessed as a register (or
sequential series of registers) in assembly
language.
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 190
ASM_File.s
.include "p24fj128ga010.inc"
.global _foo
.extern _x
_foo:
inc _x
return
.end
Using a C Variable in Assembly
In the Assembly file
Declare the variable name as .extern
Add an underscore in front of the variable name
Performs same function as extern keyword in C.
Note that the C variable name must be preceded
by an underscore here in the assembly file.
Any identifier that will be
used in both C and
assembly must have an
underscore in front of it in
the assembly code but not
in the C code.
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 191
Calling an Assembly Function
Function Call Conventions
For non-interrupt functions
Function Call Conventions
Frame Pointer*
Stack Pointer
15 0
W0
W1
W2
W3
W4
W5
W6
W7
W8
W9
W10
W11
W12
W13
W14
W15
Parameters passed to function in W0-W7
(Caller Saved)
Function may overwrite these
Parameters returned from function in W0-W4
(depending on size of return type)
W8-W13 Must be saved/restored if used
by the function (Callee Saved)
W14-W15 Must be saved/restored if used
by the function (Callee Saved)
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 192
C_File.c
#include "p24fj128ga010.h"
unsigned int x = 0;
extern unsigned int AddNumbers(unsigned int a,
unsigned int b);
int main(void)
{
x = AddNumbers(5, 3);
while(1);
}
Calling an Assembly Function
In the C File
Include function prototype for assembly function
Function name is same as ASM subroutine name
Function is called like an ordinary C function
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 193
Calling an Assembly Function
In the Assembly File
Declare the subroutine name as .global
Add an underscore '_' to the front of the name
Parameters usually passed in W registers
ASM_File.s
.include "p24fj128ga010.inc"
.global _AddNumbers
_AddNumbers:
add W0, W1, W0
return
.end
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 194
Calling an Assembly Function
Parameter Passing
Parameters are processed from left to right
Parameters are passed in the first available W
register with the proper alignment
C_File.c
#include "p24fj128ga010.h"
void foo(char a, int b, char c, long d, int e);
int main(void)
{
foo(0x11, 0x2222, 0x33, 0x44445555, 0x6666);
while(1);
}
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 195
Function Prototype: void foo(char a, int b, char c, long d, int e);
Function Call: foo(0x11, 0x2222, 0x33, 0x44445555, 0x6666);
Calling an Assembly Function
Parameter Passing
Parameter Passing Example
0011
2222
0033
6666
5555
4444
W0
W1
W2
W3
W4
W5
W6
W7
char a
int b
char c
int e
long d
Notice that d starts in W4 and
that e is in W3
Two word (32-bit) variables must start in an even numbered W register
Four word (64-bit) variables must start in W0 or W4
If all variables don't fit, then the stack is used for the overflow.
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 196
Calling an Assembly Function
Passing Non-Scalar Parameters
Non-Scalar parameters such as arrays and
structures will usually be passed as a pointer in
one of the W registers (data pointers are 16-bits)
Example
#include "p24fj128ga010.h"
void foo(char a[4]);
char num[4] = {0, 1, 2, 3};
int main(void)
{
foo(num);
while(1);
}
0804
W0
W1
W2
W3
W4
W5
W6
W7
char *num
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 197
Example: Additional Parameters Passed via Software Stack
Function Prototype: void foo(long a, long b, long c,
long d, long e, long f);
Calling an Assembly Function
Additional Parameters Passed via Stack
W0
W1
W2
W3
W4
W5
W6
W7
long a
long b
long c
long d
RETURN
ADDRESS
Calling Function's Data
n
n+2
n+4
n+6
n+8
n+10
n+12
n+14
Address Pointer Positions
long f
long e
n+16
n-2
Working
Registers
Stack
n is an even
address
SP (W15)
SP (W15)
FP (W14)
FP (W14)
Lab Exercise 7
Lab Exercise 7
Mixing C and Assembly
Mixing C and Assembly
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 199
Lab Exercise 7
Mixing C and Assembly
Assembly code is already written for you
Add in the necessary hooks in the C
source file so that you can call the
assembly functions
Objective
From the file Lab7.c, call the functions:
int AddFunction(int, int);
int MostSignificant1(int);
which are written in assembly language in the file
Lab7_asm.s. Display the output of the functions on the
Explorer 16's LCD.
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 200
Lab Exercise 7
Mixing C and Assembly
Procedure
Follow the directions in the lab manual starting on page 7-1.
On the lab PC
C:\MTT\TLS2130\Lab7\Lab7.mcw
Open the lab workspace by selecting from the
menu: File OpenWorkspace
and select the file:
If you currently have a project or workspace open,
close it now by selecting from the menu:
File CloseWorkspace
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 201
Lab Exercise 7
Mixing C and Assembly
Results
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 202
Lab Exercise 7
Mixing C and Assembly
.include "p24fj128ga010.inc"
.global _AddFunction
.global _MostSignificant1
.text
_AddFunction:
add w0,w1,w0 ; Add two integers
return ; Return result in W0
_MostSignificant1:
ff1l [w0], w0 ; Find first 1 from left
;(result counted from left)
subr w0, #16, w0 ; Adjust to give traditional bit
; position number from right
return ; Return result in W0
.end
Lab7_asm.s
Make assembly subroutine
names visible as functions in C
Parameters passed via W0-W7
(Only W0 and W1 used here)
Return value passed in W0
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 203
Lab Exercise 7
Mixing C and Assembly
Lab7.c One Possible Solution
int a, b, c;
int AddFunction(int x, int y);
int MostSignificant1(int *x);
int main(void)
{
lcdInit();
a = 5;
b = 3;
c = AddFunction(a, b); // c = a + b (in assembly file)
lcdPutInt(c, DEC); // Display value of c on first line of LCD
lcdPutCur(1,0); // Move cursor to second line of LCD
c = MostSignificant1(&a); // Find bit position of most significant 1
lcdPutInt(c, DEC); // Display value of c on second line of LCD
while (1);
}
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 204
Conclusions
Lab Exercise 7
Mixing C and Assembly
Functions written in assembly can easily be
integrated into a C based project
From C's perspective, assembly function is
no different from a C function
From assembly perspective, you must use
caution so as to not break the C code
Optimization Techniques
Optimization Techniques
Generating More Efficient Code
Generating More Efficient Code
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 206
Optimization Techniques
Compilers perform two kinds of optimization:
Speed Get more performance out of your code
Size Get more code into your microcontroller
Several techniques are used behind the scenes
to create optimized code
Usually, there is a tradeoff between size and
speed (occasionally you get both)
Additional optimization may be achieved
manually, by using built-in functions to take
advantage of architectural features that are not
easily accessed with ordinary C code
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 207
Compiler Optimizations
How to Enable MPLAB
Only)
Compiler does not directly support
separating variables into X and Y data
Section attribute may be used to explicitly
locate variables in X and Y spaces
float float buffer[32] __attribute__((__section__(".ydata"))) buffer[32] __attribute__((__section__(".ydata"))); ;
float float coeff[16] __attribute__((__section__(".xdata"))) coeff[16] __attribute__((__section__(".xdata"))); ;
References
References
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 236
Suggested Reading
Programming 16-bit Microcontrollers in C
by Lucio Di Jasio
ISBN-10: 0750682922
ISBN-13: 978-0750682923
http://www.flyingpic24.com
Thank You!
Thank You!