TLS2130 Presentation v1.6p

Download as pdf or txt
Download as pdf or txt
You are on page 1of 237

Getting Started with MPLAB

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

C30 Compiler Toolset Overview


Lab 1: Creating C30 Projects in MPLAB
How to Set Configuration Bits in Code
Lab 2: Setting Configuration Bits in Code
How to Read and Write Registers
How to Read and Write I/O Pins
Lab 3: "Hello, world" for Microcontrollers
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 3
Agenda
C Runtime Environment
Memory Models
Attributes
Interrupts
Lab 4: Writing Interrupt Service Routines
Working with Libraries
Lab 5: Using Peripheral Libraries
Lab 6: Creating Custom Libraries
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 4
Agenda
Mixing C and Assembly
Lab 7: Calling Assembly Functions from C
Optimization Techniques
Compiler Optimization
Coding Tips for Generating Optimal Code
Built-in Functions
16-bit Architecture
16-bit Architecture
A Brief Overview
A Brief Overview
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 6
Simplified Block Diagram
16-bit PIC

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

project setup steps


Select C30 as build tool
Add linker script for your device to project
#include device header file in source code
#include library header files (if required)
Add configuration bits setup in code
Allocate a heap (if required)
Conclusions
How to Set PIC

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

Configuration Bits in Code


Setting PIC

Configuration Bits in Code


2011 Microchip Technology Incorporated. All Rights Reserved. Slide 49
Lab Exercise 2
Setting PIC

Configuration Bits in Code


Setup the configuration registers with the
following options:
Objective
Use the _CONFIGn() macros to setup the configuration
registers and view the results in the Configuration Bits
window inside the MPLAB

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

Configuration Bits in Code


Procedure
Follow the directions in the lab manual starting on page 2-1.
On the lab PC
Open the lab workspace by selecting from the menu:
File OpenWorkspace
and select the file:
C:\MTT\TLS2130\Lab2\Lab2.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 51
Lab Exercise 2
Setting PIC

Configuration Bits in Code


Configuration Bits:
Should be set in code using the _CONFIG1(x) and
_CONFIG2(x) macros
Parameters consist of a series of option labels
bitwise ANDed together
Option labels are defined in the device specific
header file
Unspecified options retain their default settings
(as per the data sheet)
Conclusions
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 52
Lab Exercise 2
Setting PIC

Configuration Bits in Code


From the menu, open the configuration bits window:
Configure ConfigurationBits
Results
How to Read and Write Registers
How to Read and Write Registers
Word and Bit Access
Word and Bit Access
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 54
Examples
How to Read and Write Registers
Full 16-bit Word
Use the name of the register as you would an
ordinary int type variable
Variables defined in device specific header file
with register name as shown in datasheet
Syntax
REGNAME
PORTA = 0xFE31; // Write 0xFE31 to PORTA
AtoD_Result = ADC1BUF0; // Read A/D Result
TX1REG = 'a'; // Send 'a' out UART
if (RX1REG == 'x') { } // If received char is 'x'
while (RX1REG) { } // While char is not '\0'
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 55
Register Variable Declaration
Example for PIC24FJ128GA010
extern: PORTA is actually defined in linker
script
volatile: This variable may be altered by
something other than the code (i.e. the hardware
or an interrupt routine)
__attribute__((__sfr__)): Tag to indicate
that this is a special function hardware register
(more about attributes later)
PORTA Variable Declaration from p24fj128ga010.h Header File
extern volatile unsigned int PORTA __attribute__((__sfr__));
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 56
Examples
How to Read and Write Registers
Individual Bits and Bit Fields
Use the name of the register with the word 'bits'
in lower case attached to it
Use the name of the bit or bit field as specified in
the data sheet
Syntax
REGNAMEbits.BITNAME
LATAbits.LATA5 = 1; // Set bit 5 of PORTA
Flag = PORTAbits.RA5; // Read bit 5 of PORTA
while (!AD1CONbits.DONE) { } // While A/D converting
AD1CONbits.SSRC = 5; // Set 3-bit field = 5
//3-bits in bitfield: SSRC2 = 1, SSRC1 = 0, SSRC0 = 1
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 57
AD1CONbits Variable Declaration from p24fj128ga010.h Header File
Bit Field Variable Declaration
Example for PIC24FJ128GA010
__extension__ typedef struct tagAD1CON1BITS {
union {
struct {
unsigned DONE:1;
unsigned SAMP:1;
unsigned ASAM:1;
unsigned :2;
unsigned SSRC:3;
unsigned FORM0:1;
unsigned FORM1:1;
unsigned :3;
unsigned ADSIDL:1;
unsigned :1;
unsigned ADON:1;
};
struct {
unsigned :5;
unsigned SSRC0:1;
unsigned SSRC1:1;
unsigned SSRC2:1;
unsigned FORM:2;
};
};
} AD1CON1BITS;
extern volatile AD1CON1BITS AD1CON1bits __attribute__((__sfr__));
3-bit wide field
Primary Bit Names
Secondary Bit Names
Bit Field
Variable
Declaration
Bit Field Structure Definition
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 58
Excerpt from P24FJ128GA010.gld Linker Script File
Register and Bit Field Variables
Definition in Linker Script
Both REGNAME and REGNAMEbits
defined in linker script
Both are allocated at the same address
TRISA = 0x2C0;
_TRISA = 0x2C0;
_TRISAbits = 0x2C0;
PORTA = 0x2C2;
_PORTA = 0x2C2;
_PORTAbits = 0x2C2;
LATA = 0x2C4;
_LATA = 0x2C4;
_LATAbits = 0x2C4;
Assembly Label
C Labels
Eliminates need for a union in
header file
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 59
Examples
How to Read and Write Registers
Individual Bits and Bit Fields Shorthand Syntax
Use the bit name preceded by an underscore
Defined as a macro in the header file
May be used instead of structure syntax
Shorthand Syntax
_BITNAME
_LATA5 = 1; // Set bit 5 of PORTA
Flag = _RA5; // Read bit 5 of PORTA
while (!_DONE) { } // While A/D converting
_SSRC = 5; // Set 3-bit field = 5
//3-bits in bit field: SSRC2 = 1, SSRC1 = 0, SSRC0 = 1
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 60
For every bit in the device, there is a
#define in the device specific header file
in the form of:
Only works if header file is included
Allows access to all bits by bit name only
Register Variable Declaration
Example for PIC24FJ128GA010
Bit Access Shorthand Macro Definition
#define _BITNAME REGNAMEbits.BITNAME;
Data Input and Output
Data Input and Output
Working with I/O Ports
Working with I/O Ports
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 62
Data Input and Output
TRIS, PORT and LAT Registers
0 1 0 1 0 0 1 1
0 0 1 1 0 1 0 0
TRISx
LATx
Read
PORTx
Read
LATx
Write
PORTx
or LATx
Internal Data Bus
PORTx
(I/O Pins)
Data Direction
(1 = IN, 0 = OUT)
Pins are all inputs by
default (TRIS = 0xFFFF)
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 63
Data Input and Output
TRIS, PORT and LAT Registers
Steps for working with 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

in conjunction with assembly


operations that require aligned operands
Can improve the efficiency of some asm operations
__attribute__((aligned( __attribute__((aligned(alignment alignment))) )))
Example
int int x __attribute__((aligned(16))) x __attribute__((aligned(16))); ;
Align Align x x on a 16 on a 16- -byte boundary: byte boundary:
aligned aligned can only increase the alignment. To reduce it, use can only increase the alignment. To reduce it, use packed packed instead. instead.
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 122
What does it mean to align an address on a byte boundary?
Locating Objects in Memory
How to align an object on a byte/word boundary
Some operations require specific data
alignment
Modulo Addressing (circular buffers)
X X X X X X X X X 0 0 0 0 0 0 0
2 1 4 8
1
6
3
2
6
4
1
2
8
2
5
6
5
1
2
1
0
2
4
2
0
4
8
4
0
9
6
8
1
9
2
1
6
3
8
4
3
2
7
6
8
Possible addresses are of the form:
0xNN00 or 0xNN80 where N is any Hexadecimal Digit
int __attribute__((aligned(128))) x[50];
128 chosen because it is the smallest power of 2 that can hold 100 bytes (50 words)
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 123
Examples
address Attribute Syntax
Locating Objects in Memory
How to place an object at a specific address
Specifies the address where a function or
variable should be located
Use sparingly program will be harder to
optimize by linker
__attribute__((address( __attribute__((address(address address))) )))
int int x __attribute__((address(0x1840))) x __attribute__((address(0x1840))); ;
int int foo foo( (void void) ) __attribute__((address(0x3000))) __attribute__((address(0x3000))) { { } }
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 124
Examples
address Attribute Syntax
Overriding Default Behavior
How to make a variable persistent across resets
Prevents a variable from being overwritten
upon device reset
Places variable in the .pbss section which is
unaffected by the runtime startup code
__attribute__((persistent)) __attribute__((persistent))
int int x __attribute__((persistent)) x __attribute__((persistent)); ;
int int x _PERSISTENT x _PERSISTENT; ; //Shorthand macro defined in *.h //Shorthand macro defined in *.h
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 125
Memory Allocation Macros (PIC24)
Overriding Default Behavior
Pre-defined Macros PIC24 Devices
Defined in the header files
Simplifies the task of identifying where
you want to place an object in memory
#define _BSS(N) __attribute__((aligned(N)))
#define _DATA(N) __attribute__((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
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 126
Memory Allocation Macros (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

C30 User's Guide (Section 7.4)


MPLAB

C30 Online Help


Used by LINK30 to associate interrupt
function with the appropriate location in
the interrupt vector table
Linker puts the address of the interrupt
function in the appropriate location in the
interrupt vector table
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 131
Interrupt Functions
Partial List of Interrupt Function Names
IRQ # Alternate Name
N/A N/A
N/A N/A
N/A N/A
N/A N/A
N/A N/A
N/A N/A
N/A N/A
N/A N/A
0 0
1 1
2 2
3 3
Primary Name
_ReservedTrap0 _ReservedTrap0
_OscillatorFail _OscillatorFail
_AddressError _AddressError
_StackError _StackError
_MathError _MathError
_ReservedTrap5 _ReservedTrap5
_ReservedTrap6 _ReservedTrap6
_ReservedTrap7 _ReservedTrap7
_INT0Interrupt _INT0Interrupt
_IC1Interrupt _IC1Interrupt
_OC1Interrupt _OC1Interrupt
_T1Interrupt _T1Interrupt
_AltReservedTrap0 _AltReservedTrap0
_AltOscillatorFail _AltOscillatorFail
_AltAddressError _AltAddressError
_AltStackError _AltStackError
_AltMathError _AltMathError
_AltReservedTrap5 _AltReservedTrap5
_AltReservedTrap6 _AltReservedTrap6
_AltReservedTrap7 _AltReservedTrap7
_AltINT0Interrupt _AltINT0Interrupt
_AltIC1Interrupt _AltIC1Interrupt
_AltOC1Interrupt _AltOC1Interrupt
_AltT1Interrupt _AltT1Interrupt
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 132
Interrupt Functions
Partial List of Interrupt Function Names
IRQ # Alternate Name
4 4
5 5
6 6
7 7
8 8
9 9
10 10
11 11
12 12
13 13
14 14
15 15
Primary Name
_IC2Interrupt _IC2Interrupt
_OC2Interrupt _OC2Interrupt
_T2Interrupt _T2Interrupt
_T3Interrupt _T3Interrupt
_SPI1Interrupt _SPI1Interrupt
_U1RXInterrupt _U1RXInterrupt
_U1TXInterrupt _U1TXInterrupt
_ADCInterrupt _ADCInterrupt
_NVMInterrupt _NVMInterrupt
_SI2CInterrupt _SI2CInterrupt
_MI2CInterrupt _MI2CInterrupt
_CNInterrupt _CNInterrupt
_AltIC2Interrupt _AltIC2Interrupt
_Alt OC2Interrupt _Alt OC2Interrupt
_AltT2Interrupt _AltT2Interrupt
_AltT3Interrupt _AltT3Interrupt
_AltSPI1Interrupt _AltSPI1Interrupt
_AltU1RXInterrupt _AltU1RXInterrupt
_AltU1TXInterrupt _AltU1TXInterrupt
_AltADCInterrupt _AltADCInterrupt
_AltNVMInterrupt _AltNVMInterrupt
_AltSI2CInterrupt _AltSI2CInterrupt
_AltMI2CInterrupt _AltMI2CInterrupt
_AltCNInterrupt _AltCNInterrupt
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 133
Interrupts
What happens when an interrupt occurs?
Compiler managed
resources are automatically
pushed onto the stack
when an interrupt occurs
(if they are modified by the
interrupt)
You are responsible for
managing other resources
if you use them in your
interrupt service routine
Stack Before Interrupt
SP
09D8
09DA
09DC
09DE
09E0
09E2
09E4
09E6
09E8
09EA
09EC
09EE
09F0
09F2
09D4
09D6
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 134
WREG7
PSVPAG
Previous FP (W14)
PCH PCL
RCOUNT
WREG0
WREG1
WREG2
WREG3
WREG4
WREG5
WREG6
Interrupts
What happens when an interrupt occurs?
Stack After Interrupt
SP
09D8
09DA
09DC
09DE
09E0
09E2
09E4
09E6
09E8
09EA
09EC
09EE
09F0
09F2
09D4
09D6
SRL PCU
FP
PSVPAG is saved by default unless
no_auto_psv attribute is applied to
interrupt function:
Program Counter and low byte of
Status Register (MCU Status)
Repeat Count Register
W0 through W15
(Only those used in ISR)
Previous Frame Pointer Value
__attribute__((interrupt, no_auto_psv))
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 135
Example: Disassembly Listing of an ISR Context Save
4: 4: void void __attribute__ __attribute__(( ((interrupt interrupt)) )) _INT0Interrupt _INT0Interrupt( (void void) )
5: 5: { {
011B2 F80036 011B2 F80036 push.w push.w 0x0036 0x0036
011B4 BE9F80 mov.d 0x0000,[ 011B4 BE9F80 mov.d 0x0000,[0x001e++ 0x001e++] ]
011B6 BE9F82 mov.d 0x0004,[ 011B6 BE9F82 mov.d 0x0004,[0x001e++ 0x001e++] ]
011B8 BE9F84 mov.d 0x0008,[ 011B8 BE9F84 mov.d 0x0008,[0x001e++ 0x001e++] ]
011BA BE9F86 mov.d 0x000c,[ 011BA BE9F86 mov.d 0x000c,[0x001e++ 0x001e++] ]
011BC F80034 011BC F80034 push.w 0x0034 push.w 0x0034
011BE B3C000 mov.b #0x0,0x0000 011BE B3C000 mov.b #0x0,0x0000
011C0 8801A0 mov.w 0x0000,0x0034 011C0 8801A0 mov.w 0x0000,0x0034
011C2 FA0000 lnk #0x0 011C2 FA0000 lnk #0x0
Interrupts
What happens when an interrupt occurs?
-- -- Your ISR Code Here Your ISR Code Here -- --
Code generated for opening brace ' Code generated for opening brace '{ {' of ISR function: ' of ISR function:
Save RCOUNT Save RCOUNT
Save W4, W5 Save W4, W5
Save W6, W7 Save W6, W7
Save PSVPAG Save PSVPAG
0x001e 0x001e is W15 (Stack Pointer) is W15 (Stack Pointer)
Save W2, W3 Save W2, W3
Save W0, W1 Save W0, W1
Push to Push to
Top of Stack Top of Stack
Set PSVPAG Set PSVPAG
Allocate stack frame of 0 bytes Allocate stack frame of 0 bytes
(Saves W14 onto stack) (Saves W14 onto stack)
This code is only present if the no_auto_psv attribute is not specified.
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 136
Example: Disassembly Listing of an ISR Context Restore
12: 12: } }
011D0 FA8000 ulnk 011D0 FA8000 ulnk
011D2 F90034 pop.w 0x0034 011D2 F90034 pop.w 0x0034
011D4 BE034F mov.d [ 011D4 BE034F mov.d [-- --0x001e 0x001e],0x000c ],0x000c
011D6 BE024F mov.d [ 011D6 BE024F mov.d [-- --0x001e 0x001e],0x0008 ],0x0008
011D8 BE014F mov.d [ 011D8 BE014F mov.d [-- --0x001e 0x001e],0x0004 ],0x0004
011DA BE004F mov.d [ 011DA BE004F mov.d [-- --0x001e 0x001e],0x0000 ],0x0000
011DC F90036 011DC F90036 pop.w pop.w 0x0036 0x0036
011DE 064000 retfie 011DE 064000 retfie
Interrupts
What happens when an interrupt occurs?
-- -- Your ISR Code Here Your ISR Code Here -- --
Code generated for closing brace ' Code generated for closing brace '} }' of ISR function: ' of ISR function:
Restore RCOUNT Restore RCOUNT
Restore W4, W5 Restore W4, W5
Restore W6, W7 Restore W6, W7
Deallocate stack frame Deallocate stack frame
Return From Interrupt Return From Interrupt
Restore W2, W3 Restore W2, W3
Restore W0, W1 Restore W0, W1
Pop from Pop from
Top of Stack Top of Stack
Restore PSVPAG Restore PSVPAG
This code is only present if no_auto_psv attribute is not specified.
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 137
Interrupts
Using Shadow Registers for Context Save/Restore
The PUSH.S and POP.S instructions will be used to
save and restore using the shadow registers:
W0 W3
C, Z, OV, N, and DC bits in the SRH:SRL (STATUS) register
Syntax
void void __attribute__((interrupt, shadow)) __attribute__((interrupt, shadow)) ISRname ISRname( (void void) )
Example
void void __attribute__((interrupt, shadow)) __attribute__((interrupt, shadow))
_INT0Interrupt _INT0Interrupt( (void void) )
{ {
/* ISR Code Here */ /* ISR Code Here */
} }
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 138
Interrupts
Using Shadow Registers for Context Save/Restore
Example: Disassembly Listing of an ISR Using Shadow
-- -- Your ISR Code Here Your ISR Code Here -- --
4: 4: void void __attribute__ __attribute__(( ((interrupt interrupt, , shadow shadow)) )) _INT0Interrupt _INT0Interrupt( (void void) )
5: 5: { {
011B2 FEA000 011B2 FEA000 push.s push.s
011B4 F80036 push.w 0x0036 011B4 F80036 push.w 0x0036
011B6 BE9F84 mov.d 0x0008,[ 011B6 BE9F84 mov.d 0x0008,[0x001e++ 0x001e++] ]
011B8 BE9F86 mov.d 0x000c,[ 011B8 BE9F86 mov.d 0x000c,[0x001e++ 0x001e++] ]
011BA F80034 011BA F80034 push.w 0x0034 push.w 0x0034
011BB B3C000 mov.b #0x0,0x0000 011BB B3C000 mov.b #0x0,0x0000
011CC 8801A0 mov.w 0x0000,0x0034 011CC 8801A0 mov.w 0x0000,0x0034
011CE FA0000 lnk #0x0 011CE FA0000 lnk #0x0
Code generated for opening brace ' Code generated for opening brace '{ {' of ISR function: ' of ISR function:
Save RCOUNT Save RCOUNT
Save W4, W5 Save W4, W5
Save W6, W7 Save W6, W7
Save W0 Save W0 W3, status bits C, Z, OV, N, DC W3, status bits C, Z, OV, N, DC
Save PSVPAG Save PSVPAG
0x001e 0x001e is W15 (Stack Pointer) is W15 (Stack Pointer)
Set PSVPAG Set PSVPAG
Allocate stack frame of 0 bytes Allocate stack frame of 0 bytes
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 139
Example: Disassembly Listing of an ISR Using Shadow
12: 12: } }
011CE FA8000 ulnk 011CE FA8000 ulnk
011D0 F90034 pop.w 0x0034 011D0 F90034 pop.w 0x0034
011D0 BE034F mov.d [ 011D0 BE034F mov.d [-- --0x001e 0x001e],0x000c ],0x000c
011D2 BE024F mov.d [ 011D2 BE024F mov.d [-- --0x001e 0x001e],0x0008 ],0x0008
011D4 F90036 pop.w 0x0036 011D4 F90036 pop.w 0x0036
011D6 FE8000 011D6 FE8000 pop.s pop.s
011D8 064000 retfie 011D8 064000 retfie
Interrupts
Using Shadow Registers for Context Save/Restore
-- -- Your ISR Code Here Your ISR Code Here -- --
Code generated for closing brace ' Code generated for closing brace '} }' of ISR function: ' of ISR function:
Restore RCOUNT Restore RCOUNT
Restore W4, W5 Restore W4, W5
Restore W6, W7 Restore W6, W7
Restore W0 Restore W0 W3, status bits W3, status bits C, Z, OV, N, DC C, Z, OV, N, DC
Deallocate stack frame Deallocate stack frame
Return From Interrupt Return From Interrupt
Restore PSVPAG Restore PSVPAG
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 140
Interrupts
Using Shadow Registers for Context Save/Restore
Shadow registers must be used with care
Shadow registers are only one level deep
Contents can be lost if two interrupts use
shadow registers and one is higher
priority than the other
W0 W0
W1 W1
W2 W2
W0 W0
W1 W1
W2 W2
W3 W3
C C Z Z OV OV N N RA RA IPL IPL DC DC
Working Registers
SRH SRL
Status Register
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 141
Interrupts
How to Save Variables Not Managed by the Compiler
Any variables listed in the save list will be pushed
onto the stack along with the compiler managed
resources
Syntax
void void __attribute__((interrupt(save( __attribute__((interrupt(save(list list))) _ ))) _ISRname ISRname( (void void) )
Example
void void __attribute__((interrupt(save(x, y)))) __attribute__((interrupt(save(x, y))))
_INT0Interrupt _INT0Interrupt( (void void) )
{ {
/* ISR Code Here */ /* ISR Code Here */
} }
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 142
Example
Built-in ISR Macro Definitions
Interrupts
Macros for Simplified ISR Syntax
The macros may be used when the interrupt being
defined doesn't require any special attributes
beyond interrupt and shadow
#define #define _ISR __attribute__((interrupt)) _ISR __attribute__((interrupt))
#define #define _ISRFAST __attribute__((interrupt, shadow)) _ISRFAST __attribute__((interrupt, shadow))
void void _ISR _INT0Interrupt _ISR _INT0Interrupt( (void void) )
{ {
/* ISR Code Here */ /* ISR Code Here */
} }
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 143
Interrupts
Firmware Engineer's Responsibilities
You must clear the interrupt flag manually
Example: IFSnbits.FlagName = 0;
You must save any registers/variables you
access in the ISR's code if they are not
handled automatically by the compiler
Add a save list to the interrupt attribute
Save them manually in your ISR code
Variables modified by an interrupt should
be tagged with the volatile keyword
Lab Exercise 4
Lab Exercise 4
Interrupts
Interrupts
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 145
Lab Exercise 4
Interrupts
Timer 1 has been configured for you to
interrupt approximately twice per second
You need to write the interrupt service
routine to toggle the LED and clear the
interrupt flag
Objective
Using the Timer 1 interrupt, blink LED D3 (RA0) at a rate
determined by the internal RC oscillator's default frequency
and Timer 1's period with a 1:8 prescaler and Fosc/2 as its
clock source.
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 146
Lab Exercise 4
Interrupts
Procedure
Follow the directions in the lab manual starting on page 4-1.
On the lab PC
Open the lab workspace by selecting from the menu:
File OpenWorkspace
and select the file:
C:\MTT\TLS2130\Lab4\Lab4.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 147
Lab Exercise 4
Interrupts
Results
D3
D3
void __attribute__((interrupt)) _T1Interrupt(void)
{
LATAbits.LATA0 ^= 1; //Toggle LED
IFS0bits.T1IF = 0; //Clear interrupt flag
}
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 148
Lab Exercise 4
Interrupts
Results
F
OSC
= F
RC
/ CLKDIV = 8 MHz / 2 = 4 MHz
T1
CLK
= Fosc / 2 = 4 MHz / 2 = 2 MHz
T1
TICK
= (1 / T1CLK) * PRESCALE = (1 / 2 MHz) * 8 = 4 s
T1
Period
= T1
TICK
* 2
16
= 4 s * 65536 = 0.26s
Blink Period = 2 * T1
Period
= 2 * 0.26 s = 0.52 s
Timing Calculations
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 149
Conclusions
Lab Exercise 4
Interrupts
Interrupt functions need to be tagged with the
interrupt attribute:
Interrupts should use the names Microchip
provides in the linker script:
You must clear the interrupt flag
C:\Program Files\Microchip\MPLAB C30\Support\PIC24F\p24FJ128GA010.gld
__attribute__((interrupt))
Working with Libraries
Working with Libraries
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 151
Working With Libraries
MPLAB

C30 includes several libraries:


libc.a = Standard C Library
libm.a = Math Library
libdsp.a = DSP Library
libq.a = Fixed Point Math Library
libq-dsp.a = FP Math Library (DSP Engine)
libDEVICENUM.a = Peripheral Libraries
libpPIC24Fxxx.a
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 152
Working With Libraries
To use the peripheral libraries:
#include the appropriate header file (timer.h)
Call the functions as documented in the
library user's guide
Only the object files you use from a library
will be compiled into the final hex file
Libraries shipped with MPLAB C will be
automatically linked into your project
when they are used
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 153
Working With Libraries
Library Header Files
adc.h A/D Converter
comparator.h Analog Comparator
crc.h Cyclic Redundancy Check
Generic.h Generally useful stuff
i2c.h I2C Interface
incap.h Input Capture
outcompare.h Output Compare
PIC24_periph_features.h Peripheral Pin Select
pmp.h Parallel Master Port
ports.h I/O Ports
PwrMgnt.h Power Management
rtcc.h Real-Time Clock Calendar
spi.h SPI Interface
timer.h Timers
uart.h UART
wdt.h Watchdog Timer
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 154
config Parameter (OR these values together for desired configuration)
Function Prototype
OpenTimer1()
Example Library Function
Timer Module On/Off
T1_ON
T1_OFF
Timer Module Idle mode On/Off
T1_IDLE_CON
T1_IDLE_STOP
Timer Gate time accumulation enable
T1_GATE_ON
T1_GATE_OFF
Timer prescaler
T1_PS_1_1 T1_PS_1_64
T1_PS_1_8 T1_PS_1_128
Timer Synchronous clock enable
T1_SYNC_EXT_ON
T1_SYNC_EXT_OFF
Timer clock source
T1_SOURCE_EXT
T1_SOURCE_INT
void OpenTimer1(unsigned int config, unsigned int period);
Example:
OpenTimer1(T1_ON & T1_IDLE_CON & T1_GATE_OFF & T1_PS_1_8 &
T1_SYNC_EXT_OFF & T1_SOURCE_INT, 0xFFFF);
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 155
period Parameter
Function Prototype
OpenTimer1()
Example Library Function
void OpenTimer1(unsigned int config, unsigned int period);
Example:
OpenTimer1(T1_ON & T1_IDLE_CON & T1_GATE_OFF & T1_PS_1_8 &
T1_SYNC_EXT_OFF & T1_SOURCE_INT, 0xFFFF);
IFS0bits.T1IF
period
RESET
Equal
TMR1
Comparator
PR1
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 156
config Parameter (OR these values together for desired configuration)
Function Prototype
ConfigIntTimer1()
Example Library Function
Interrupt Priority
T1_INT_PRIOR_7
T1_INT_PRIOR_6
T1_INT_PRIOR_5
T1_INT_PRIOR_4
T1_INT_PRIOR_3
T1_INT_PRIOR_2
T1_INT_PRIOR_1
T1_INT_PRIOR_0
Interrupt Enable
T1_INT_ON
T1_INT_OFF
void ConfigIntTimer1(unsigned int config);
Example:
ConfigIntTimer1(T1_INT_ON & T1_INT_PRIOR_7);
Lab Exercise 5
Lab Exercise 5
Working with Peripheral Libraries
Working with Peripheral Libraries
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 158
Lab Exercise 5
Working with Peripheral Libraries
The objective is the same as lab 4
This time, the Timer 1 interrupt is already
written for you
You need to initialize Timer 1 using the PIC24F
peripheral libraries using the parameters
given in the lab manual
Objective
Using the Timer 1 interrupt, blink LED D3 (RA0) at a rate
determined by the internal RC oscillator's default frequency
and Timer 1's period with a 1:8 prescaler and Fosc/2 as its
clock source.
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 159
Lab Exercise 5
Working with Peripheral Libraries
Procedure
Follow the directions in the lab manual starting on page 5-1.
On the lab PC
C:\MTT\TLS2130\Lab5\Lab5.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 160
Lab Exercise 5
Working with Peripheral Libraries
Results
OpenTimer1(T1_ON & T1_IDLE_CON & T1_GATE_OFF &
T1_PS_1_8 & T1_SYNC_EXT_OFF &
T1_SOURCE_INT, 0xFFFF);
ConfigIntTimer1(T1_INT_PRIOR_7 & T1_INT_ON);
D3
D3
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 161
Conclusions
Lab Exercise 5
Working with Peripheral Libraries
Peripheral libraries can simplify the task of
configuring on chip peripherals
To use the peripheral libraries, you must
Include the appropriate header file in your source
And together choices from all options when you
call the functions do not rely on defaults
Lab Exercise 6
Lab Exercise 6
Creating Custom Libraries
Creating Custom Libraries
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 163
Lab Exercise 6
Creating Custom Libraries
Follow along with the instructor to create a
custom library and a project to test it
The library will consist of two source files,
each containing a single function
The code is already written for you
Objective
Build a library (archive) file from a simple C source file that
contains a single function. Then, use that function in a
separate project that includes the newly created library file in
its project tree.
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 164
Lab Exercise 6
Creating Custom Libraries
Open the MPLAB Settings
From the menu bar, select:
Configure Settings
Procedure
Follow the directions in the lab manual starting on page 6-1,
or follow along with the instructor and the slides as we walk
through this project together.
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 165
Lab Exercise 6
Creating Custom Libraries
Select the Project Settings
On the tabs, select: Projects
Deselect one-to-one project-
workspace model
Uncheck the last check box:
Configure MPLAB so that multiple projects may be opened within one workspace
Click when done OK
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 166
Click on and select:
C:\MTT\TLS2130\Lab6
In the ProjectName box, enter:
MyLib
Lab Exercise 6
Creating Custom Libraries
Create the Library Source Project
Create New Project
From the menu bar, select:
Project New
Name the Project
Select Project Directory
Browse
The name of this project
will be the name of the
library file (e.g. MyLib.a)
Click when done OK
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 167
C:\MTT\TLS2130\Lab6\addition.c
Lab Exercise 6
Creating Custom Libraries
Add the library source code to the project
Add Source File to Project
In the project tree, right click on SourceFiles
and select: AddFiles
Select Library Source Files
In the add file dialog box, select the library source
files from the lab 6 directory (the library code has
already been written for you):
addition.c and subtraction.c should appear in
the project tree under SourceFiles.
C:\MTT\TLS2130\Lab6\subtraction.c
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 168
Lab Exercise 6
Creating Custom Libraries
addition.c
MyLib.h
int add(int a, int b)
{
return (a + b);
}
int add(int a, int b);
int sub(int a, int b);
The header file contains
function prototypes for all the
functions in the library file.
This will be required to use the
library in other projects.
A look at the library source code and
its associated header file
subtraction.c
int sub(int a, int b)
{
return (a - b);
}
Library source code contains
functions written in the usual
way. Nothing special needs to
be done just because this will
be included in a library.
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 169
Lab Exercise 6
Creating Custom Libraries
Configure the project build options
Open the Project Build Options Dialog Box
From the menu bar, select:
Project BuildOptions Project
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 170
Lab Exercise 6
Creating Custom Libraries
Configure the project build options
Setup Tool Suite Options
From the tabs, select:
ASM30/C30Suite
Set the Target Type
In the Target Type box, select:
Buildlibrarytarget(invokeLIB30)
and check:
Buildgenericlibrary
Click when done OK
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 171
Lab Exercise 6
Creating Custom Libraries
Build the library
Compile (Build All) Compile (Build All)
Build the Libarary
From the tool bar, click on the Build All button.
When building a library, no linker script is required
because the code being generated will not be placed in a
device's memory map until it is part of a normal project.
This step will generate a library file called MyLib.a that may
now be used in any project for a 16-bit PIC

2011 Microchip Technology Incorporated. All Rights Reserved. Slide 172


Lab Exercise 6
Creating Custom Libraries
Library Build Process
Linker
C Compiler
(and Preprocessor)
Archiver
(Librarian)
addition.c
subtraction.c
addition.s
subtraction.s
addition.o
subtraction.o
MyLib.a
Assembler
Contents of MyLib.a
addition.o subtraction.o
Including an archive (*.a) into a
project, is the same as including
all of the individual object files
(*.o) that it contains...
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 173
C:\MTT\TLS2130\Lab6\Lab6.mcp
From the open project dialog box select:
Lab Exercise 6
Creating Custom Libraries
Open (or create) a test project
Open Test Project
From the menu bar, select:
Project Open
If doing this on your own, at this
point you may create a new C30
based project following the steps
from Lab 1. Include the library file
just created into the new project.
Select the Lab6 Project
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 174
#include "TLS2130.h"
#include "MyLib.h"
int sum, difference;
int main(void)
{
lcdInit();
sum = add(5, 2);
difference = sub(7, 2);
lcdPutInt(c, DEC);
Lab Exercise 6
Creating Custom Libraries
A look at the Lab6 test project
MyLib.h
MyLib.a
Generated in Step 12
Created by you, to
provide access to
functions in library
Lab6.c
MyLib.c
L
a
b
6

T
e
s
t

P
r
o
j
e
c
t
M
y
L
i
b

P
r
o
j
e
c
t
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 175
Lab Exercise 6
Creating Custom Libraries
Enable your debug tool
Enable Proteus
If not already enabled, from the
tool bar select:
Debugger SelectTool
ProteusVSM
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 176
Lab Exercise 6
Creating Custom Libraries
Click on the Click on the Build All Build All button. button.
Compile (Build All) Compile (Build All) Start Start
Simulation Simulation
Select Select Debug Debug mode. mode.
Debug/Release Debug/Release
If no errors are reported, If no errors are reported,
Click on the Click on the Start Simulation Start Simulation button. button.
Build and run the program
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 177
Lab Exercise 6
Creating Custom Libraries
Halt Halt Reset Reset Run Run
When programming completes, When programming completes,
Click on the Click on the Reset Reset button. button.
Click on the Click on the Run Run button. button.
Click on the Click on the Halt Halt button. button.
Build and run the program
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 178
Lab Exercise 6
Creating Custom Libraries
Results
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 179
Lab Exercise 6
Creating Custom Libraries
Make Library Project Active
Right click on the MyLib project and select:
SetActive
Add to or modify library source
code (and its associated header)
Rebuild Library as in Step 12
Make Test Project Active
Right click on the Lab6 project and select:
SetActive
Rebuild and Run Lab6 as in Step 17
through 21
OPTIONAL Continue Library Development
Mixing C and Assembly
Mixing C and Assembly
Inline Assembly Solutions
Inline Assembly Solutions
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 181
Inline Assembly
Simple Form Single Line
Only a single string can be passed
Generally used for instructions that take no
operands or take immediate operands
For ANSI compliance use __asm__ instead of
asm
Syntax
asm ("instruction")
Examples
asm ("nop"); // One Cycle Delay
asm ("clrwdt"); // Clear Watchdog Timer
asm ("pwrsav #0"); // Sleep mode
asm ("pwrsav #1"); // Idle mode
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 182
Inline Assembly
Simple Form Multiple Lines
Only one "asm" keyword is required
Include each instruction within double quotes
Put each instruction on a separate line for better
readability
One set of parentheses encloses the entire list
of instructions within the asm statement
Syntax
asm ("instruction_1"
"instruction_2"

"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

C30 Compiler Optimizations


1
From the menu, select:
Project BuildOptions Project
2
Select the MPLABC30 Tab
3
From the Categories combo box,
select Optimization
4
Choose an OptimizationLevel
above 0
2
3
4
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 208
Optimization Level 0
Compiler Optimizations
-O0 (Level 0) Do Not Optimize
Fastest Compilation Time
Easiest for Debugging
Code not rearranged
Code behaves as expected when variable values
changed at break point
code size
s
p
e
e
d
1
0
2
s
3
Enabled Optimizations:
NONE
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 209
Optimization Level 1
code size
s
p
e
e
d
1
0
2
s
3
Compiler Optimizations
-O or -O1 (Level 1) Optimize
Compilation takes a bit longer
Compilation requires much more memory on PC
Compiler tries to reduce both code size and
execution time
Enabled Optimizations:
-fthread-jumps
-fdefer-pop
-fomit-frame-pointer
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 210
Optimization Level 2
code size
s
p
e
e
d
1
0
2
s
3
Compiler Optimizations
-O2 (Level 2) Optimize Even More
Performs nearly all optimizations that do not
involve a space versus speed trade-off
Enabled Optimizations:
-funroll-loops
-finline-functions
All optimizations EXCEPT:
Also enables:
-fforce-mem
-fomit-frame-pointer
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 211
Optimization Level 2
code size
s
p
e
e
d
1
0
2
s
3
Compiler Optimizations
-O3 (Level 3) Optimize Yet More
Turns on all optimizations in level 2 (-O2)
Enabled Optimizations:
-finline-functions
All optimizations plus:
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 212
Optimization Level 2
code size
s
p
e
e
d
1
0
2
s
3
Compiler Optimizations
-Os (Level S) Optimize For Size
Turns on all optimizations in level 2 (-O2) that do
not typically increase code size
Performs further optimizations to reduce code
size
Enabled Optimizations:
All Level 2 optimizations that do
not increase code size
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 213
MPLAB

C30's Built-In Functions


Functions built into the compiler itself to
implement architecture specific tasks that
cannot be implemented directly in ANSI
standard C
No libraries need to be added
Just call like an ordinary function
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 214
int __builtin_addab(void);
int __builtin_add(int value, const int shift);
void __builtin_btg(unsigned int *, unsigned int 0xn);
int __builtin_clr(void);
int __builtin_clr_prefetch(int **xptr, int *xval, int xincr,
int **yptr, int *yval, int yincr, int *AWB);
signed int __builtin_divmodsd(signed long dividend, signed int divisor,
signed int *remainder);
unsigned int __builtin_divmodud(unsigned long dividend,
unsigned int divisor,
unsigned int *remainder);
int __builtin_divsd(const long num, const int den);
unsigned int __builtin_divud(const unsigned
long num, const unsigned int den);
MPLAB

C30's Built-In Functions


Built-In Function Prototypes (See MPLAB

C30 Help File for Details) Part 1


2011 Microchip Technology Incorporated. All Rights Reserved. Slide 215
MPLAB

C30's Built-In Functions


unsigned int __builtin_dmaoffset(const void *p);
int __builtin_mac(int a, int b,
int **xptr, int *xval, int xincr,
int **yptr, int *yval, int yincr, int *AWB);
int __builtin_lac(int value, int shift);
int __builtin_fbcl(int value);
int __builtin_ed(int sqr, int **xptr, int xincr,
int **yptr, int yincr, int *distance);
int __builtin_edac(int sqr, int **xptr, int xincr,
int **yptr, int yincr, int *distance);
int __builtin_movsac(int **xptr, int *xval, int xincr,
int **yptr, int *yval, int yincr, int *AWB);
signed int __builtin_modsd(signed long dividend,
signed int divisor);
Built-In Function Prototypes (See MPLAB

C30 Help File for Details) Part 2


2011 Microchip Technology Incorporated. All Rights Reserved. Slide 216
int __builtin_mpyn(int a, int b,
int **xptr, int *xval, int xincr,
int **yptr, int *yval, int yincr);
MPLAB

C30's Built-In Functions


signed long __builtin_mulsu(const signed int p0,
const unsigned int p1);
signed long __builtin_mulus(const unsigned int p0,
const signed int p1);
unsigned long __builtin_muluu(const unsigned int p0,
const unsigned int p1);
signed long __builtin_mulss(const signed int p0, const signed int p1);
int __builtin_msc(int a, int b,
int **xptr, int *xval, int xincr,
int **yptr, int *yval, int yincr, int *AWB);
int __builtin_mpy(int a, int b,
int **xptr, int *xval, int xincr,
int **yptr, int *yval, int yincr);
void __builtin_nop(void);
Built-In Function Prototypes (See MPLAB

C30 Help File for Details) Part 3


2011 Microchip Technology Incorporated. All Rights Reserved. Slide 217
unsigned int __builtin_tblrdl(unsigned int offset);
void __builtin_tblwth(unsigned int offset unsigned int data);
unsigned int __builtin_tbloffset(const void *p);
unsigned int __builtin_tblrdh(unsigned int offset);
unsigned int __builtin_psvpage(const void *p);
unsigned int __builtin_psvoffset(const void *p);
unsigned int __builtin_readsfr(const void *p);
int __builtin_return_address (const int level);
int __builtin_sac(int value, int shift);
int __builtin_sacr(int value, int shift);
int __builtin_sftac(int shift);
int __builtin_subab(void);
unsigned int __builtin_tblpage(const void *p);
MPLAB

C30's Built-In Functions


Built-In Function Prototypes (See MPLAB

C30 Help File for Details) Part 4


2011 Microchip Technology Incorporated. All Rights Reserved. Slide 218
void __builtin_disi(unsigned int cycles);
void __builtin_tblwtl(unsigned int offset unsigned int data);
void __builtin_write_NVM(void);
void __builtin_write_OSCCONL(unsigned char value);
void __builtin_write_OSCCONH(unsigned char value);
MPLAB

C30's Built-In Functions


Built-In Function Prototypes (See MPLAB C30 Help File for Details) Part 5
Built-In Function Prototypes (Undocumented as of Revision F of MPLAB C30 User's Guide)
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 219
Assembly output when using C's multiply operator *
#include <p24fj128ga010.h>
int a = 250, b = 250;
long c;
int main(void)
{
c = a * b;
while(1);
}
Multiplication Code
Using C's Multiply Operator No Typecast
mov.w _b,W1
mov.w _a,W0
mul.ss W1,W0,W0
asr W0,#15,W1
mov.w W0,_c
mov.w W1,_c+2
6 Instructions / 6 Cycles
This code will not yield the
correct results if the value of
the result requires more than
16-bits
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 220
Multiplication Code
Using C's Multiply Operator
Assembly output when using C's multiply operator *
#include <p24fj128ga010.h>
int a = 250, b = 250;
long c;
int main(void)
{
c = (long)a * b;
while(1);
}
mov.w _a,W0
mul.su W0,#1,W8
mov.w _b,W0
mul.su W0,#1,W2
mul.uu W8,W2,W6
mul.ss W8,W3,W0
mov.w W7,W4
add.w W4,W0,W4
mul.ss W2,W9,W0
add.w W4,W0,W4
mov.w W4,W7
mov.w W6,_c
mov.w W7,_c+2
13 Instructions / 13 Cycles
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 221
Assembly output when using C30's built-in mulss function
#include <p24fj128ga010.h>
int a = 250, b = 250;
long c;
int main(void)
{
c = __builtin_mulss(a, b);
while(1);
}
Multiplication Code
Using __builtin_mulss()
mov.w _b,W1
mov.w _a,W0
mul.ss W0,W1,W0
mov.w W0,_c
mov.w W1,_c+2
5 Instructions / 5 Cycles
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 222
Multiplication Code
Why Doesn't the Compiler Do This Automatically?
Because it wouldn't be a C compiler
The ANSI C language requires that
multiplication be handled a certain way
Changing that way creates a new C-like
language that will behave in a dramatically
different way from ANSI C
C code would not behave the way an
experienced C programmer would expect
It would create non-portable code from
standard C syntax
Blame K&R not Microchip
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 223
Toggle Code
Using C's ^= Operator with Bit Field Member
Assembly output when using C's ^= operator to toggle a bit field
#include <p24fj128ga010.h>
int main(void)
{
_LATA0 ^= 1;
}
mov.b _LATA,W0
and.b W0,#1,W0
btg W0,#0
and.b W0,#1,W0
and.b W0,#1,W2
mov.w #0x2c4,W1
mov.b [W1],W1
mov.b #0xfe,W0
and.b W1,W0,W0
ior.b W0,W2,W0
mov.b W0,0x02c4
11 Instructions / 11 Cycles
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 224
Assembly output when using __builtin_btg()
#include <p24fj128ga010.h>
int main(void)
{
__builtin_btg(&LATA, 0);
}
Toggle Code
Using __builtin_btg()
mov.w #_LATA,W0
btg [W0],#0
2 Instructions / 2 Cycles
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 225
Assembly output when using inline assembly
#include <p24fj128ga010.h>
int main(void)
{
asm("btg LATA, #0");
}
Toggle Code
Using Inline Assembly
btg.b _LATA,#0
1 Instruction / 1 Cycle
This code will only work with
registers in near data space.
All SFRs are in near space.
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 226
Assembly output when using xor with a shifted 1
#include <p24fj128ga010.h>
int main(void)
{
LATA ^= (1 << 0);
}
Toggle Code
Using C's ^= Operator with int Variable
btg.b _LATA,#0
1 Instruction / 1 Cycle
Optimization must be enabled, otherwise 3
instructions will be generated.
Bit to Toggle
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 227
Optimization Techniques
Data Types
Use int for array index variables
Use int for local auto variables
If you aren't trying to save memory, use an
int because not all instructions support
byte access (.b instruction suffix in
assembly)
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 228
Optimization Techniques
Bit Fields
More readable but can be less efficient
Good:
Assigning literals to bit fields
(REGbits.bit = 1)
Testing bit fields (REGbits.bit == 1)
Bad:
Toggling bits (REGbits.bit ^= 1)
Assigning a variable value to a bit field
Arithmetic on a bit field
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 229
Optimization Techniques
Modifying SFRs
With volatile variables / registers, a sequence
of bit field modifications cannot be optimized to
a single write:
Write a full integer to the entire register instead:
T1CONbits.TCKPS = 2;
T1CONbits.TGATE = 0;
T1CONbits.TSIDL = 1;
T1CONbits.TON = 1;
mov.b T1CON,W0
bclr W0,#TCKPS0
bset W0,#TCKPS1
mov.b W0,T1CON
bclr T1CON,#TGATE
bset T1CON,#TSIDL
bset T1CON,#TON
T1CON = 0xA020;
mov.w #0xa020,W0
mov.w W0,T1CON
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 230
Optimization Techniques
Miscellaneous
Ensure that function prototypes match
arguments (especially signed-ness)
Use local/auto variables in preference to
global/static variables the compiler can
put them into W registers
Do not use char for auto variables
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 231
Optimization Techniques
Data Memory Models
Use Large Data and Small Scalar Models
Entire data memory
map is available
Puts scalar variables
in near memory
Puts non-scalars in
far memory (arrays,
structures, unions)
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 232
Syntax
Inline Functions
Integrates function's code into code for its
callers
Usually faster due to lower overhead
Code size may be smaller or larger
May only be used if function definition is visible
in file where used (not just the function's
prototype)
inline Functions may be placed in header files
inline returnType identifier(parameterList)
{
//Function code here
}
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 233
Example
Inline Functions
Best used with short functions where overhead
is an issue
Must enable optimizations or use the -finline
command line switch
Similar to macros but without the preprocessor
Aware of C syntax and constructs
May be further optimized by compiler
inline int square(int a)
{
return __builtin_mulss(a, a);
}
2011 Microchip Technology Incorporated. All Rights Reserved. Slide 234
Example
Memory Models
X and Y Data Space (dsPIC

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!

You might also like