mcu3121 16-bit standard peripherals and programming using c30

175
MCU3121 16-bit Standard Peripherals and Programming using C30

Upload: donovan-chapell

Post on 28-Mar-2015

224 views

Category:

Documents


6 download

TRANSCRIPT

Page 1: MCU3121 16-bit Standard Peripherals and Programming using C30

MCU3121

16-bit Standard Peripherals and Programming using C30

MCU3121

16-bit Standard Peripherals and Programming using C30

Page 2: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 2

Objectives

When you walk out of this class, you will understand the 16-Bit MCU: Architecture Interrupts Basic Peripherals Peripheral Configuration Programming in C using MPLAB C30

Page 3: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 3

Agenda 16-Bit Architecture Basics & MPLAB C30

MCU Data Path & Registers Program & Data Memory ALU, Register Set, Clocking Scheme

LAB 1: My First C30 Project Data Access From Program Memory

LAB 2: PSV Configuration and Usage Stack and Frame pointer Interrupt and Trap Handling

LAB 3: Interrupt Configuration and Usage

Page 4: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 4

Agenda (Continued..) 16-Bit Peripherals

I/O Ports ADC

LAB 4: ADC Configuration & usage Comparators & Voltage Reference generator Timers

LAB 5: Configuration of 32-bit Timers Capture Compare & PWM UART

LAB 6: UART Configuration and Usage of FIFO I2C™ SPI

Page 5: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 5

Agenda (Continued..)

Special features Oscillators and Power Saving modes Resets WDT

Summary References Appendix A

MPLAB C30 C-Language Extensions

Page 6: MCU3121 16-bit Standard Peripherals and Programming using C30

16-Bit Architecture Basics & MPLAB C3016-Bit Architecture Basics & MPLAB C30

Page 7: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 7

Harvard Architecture

16-bit microcontroller 24-bit Instruction width Data Transfer Mechanism between

PM and DM

Program Memory

(Up to 12MB)

1624

PIC24

RISC CPU

Data Memory

(Up to 64KB)

16 – bit window

MAC(dsPIC)

Page 8: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 8

DSPEngineDSP

Engine

Architecture Block Diagram

W Array

16 x 16

23-bit PCControlMCU

ALU

Data Memory(RAM)

32K x 16 bit

DSP: dual accessMCU: single

access

X

AG

U

Y

AG

U

InstructionPre-fetch &

Decode

TA

BLE

Access C

nt r

l

Address PathMCU/DSP Data Path Program Data/Control Path

DSP Data Path

ProgramMemory

4M x 24 bit

LinearMCU & DSC

DSC ONLY

Page 9: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 9

Maximum 12MB - 4MB x 24-bit - 23-bit PC (PCH & PCL)

PC increments in words (LSB always ‘0’)

Reset Vector at 0 Interrupt Vector Table

from 4h to FEh User Code space from

200h to 7FFFFEh (what ever is implemented)

Program Memory Organization

000000h

7FFFFEh

FFFFFEh

PC<22:1>0 0

TABPAG Source reg

023

Co

nfi

g S

pa

ceU

se

r S

pa

ce

Unimplemented

Device ID

Config Registers

On Chip User Flash Memory

Alternate Vector Table

Flash Config Words

Reset Vector

Interrupt Vector Table 000004h

000104h

000200h

Source reg PSVPAG 00

Table Ops

PSV

023

Page 10: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 10

Near Data Memory

8 KB

Unimplemented Optionally Mappedinto

Program Memory Using PSV

0x8001

0xFFFF

0x8000

0xFFFE

SRAM Space

X Data Ram

0x0801 0x0800

Y Data Ram 0x1FFE

SFR Space0x0001 0x0000

0x07FF 0x07FE

2 KBSFR Space

MS ByteAddress

LS ByteAddress

16-bits

MSB LSB

Dual Port RAM 2 KBDual-Port DMA RAM

Data Memory Organization

Page 11: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 11

PSV - Program Space Visibility From Data Space

SFR Space

32 KBProgram SpaceVisibility (PSV)

0x8000

0x0000

Data Memory

Program Memory

0x010000

0x000000

0x018000

15 023

Data Memory

0x9000

0xFFFE

0x0000

0x008000

0x1234

PAGE 1

0x001000

PAGE 2

0x009000

PAGE 3

0x011000

0x5678

0xABCD

0x1234

0x5678

0xABCD

Ability to map 16KW (32KB) program memory segments into Data Memory

015

Page 12: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 12

MCU ALU & Datapath - Overview -

16-bit Family ALU is 16-bits Wide Operates on both 8 & 16-bit operands for

better C support (char / int) Instruction set : 92 + 12 (dsPIC) Single cycle bit manipulation (RMW) Operations: Add, Subtract, Logical,

Single/Multi-bit shifts (1 cycle), 2’s complement

Page 13: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 13

Datapath Example (c = a + b;)

a (copy)

….

CPU Registers

a

b

c

temp

i

….

Data Memory (Variables)

ALU

add w0, [w1], [w2]

ALU can operate directly or indirectly on variables stored in Data Memory

w1

w2

w3

w5

w15

w0

addr(b)

addr(c)

Page 14: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 14

Datapath Example #2(c = a + b;)

a (copy)

….

CPU Registers

a

b

c

temp

i

….

Data Memory (Variables)

ALU

add w0, w1, w2

ALU can operate directly on variables stored in CPU Registers

w1

w2

w3

w5

w15

w0

b (copy)

c (copy)

Page 15: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 15

Multiply & Divide Support Single-cycle, 17x17 multiplier

Supports mixed mode multiplies (signed/unsigned)

32/16 and 16/16 signed/unsigned integer divider Implemented as an interruptible, single

instruction iterative loop, i.e.

Execution time: 19 Tcy, Latency : 1 Tcy

repeat #17 ;must be executed within repeat loop

div.sd ;signed division (16/16)

Page 16: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 16

Register Set

0

15

16 General Purpose

Data Registers or

Address Pointers

Stack Pointer

W0W1W2W3W4W5W6W7W8W9

W10W11W12W13W14W15

15 0

Frame Pointer

DSP Status

MCU Status

Stack Pointer Limit SPLIM

Status Register Low

IPL2 IPL1 IPL0 RA N ZOV C

Status Registe

r HighOA OB SA SB OAB DASAB DC

7

8

MCU & DSC

DSC ONLY

Page 17: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 17

Register Set (contd.)

ACCBLACCBHACCBUACCB

Two DSP Accumulators

ACCA ACCALACCAHACCAU

0153139

CORCON

015Core/DSP Control Register

Prg. Space Visibility Page Address

PSVPAG07

Data Table Page Address

TBLPAG

07

Page 18: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 18

Register Set (contd.)

RCOUNT

015Repeat Loop Counter

DCOUNT

015Do Loop Counter

DOSTART

022Do Loop Start Address

DOEND

022Do Loop End Address

Program Counter

022Program Counter

Do Loop Registers:

Page 19: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 19

Fetch SUB_1+1

Exec. SUB_1Fetch SUB_1

Forced NOPFetch 2+1

Update PC

Fetch 11. mov W0, PORTB Exec. 1

Fetch 22. rcall SUB_1

(Forced nop)

4. bset PORTA, #RA3

TCY0 TCY1 TCY2 TCY3 TCY4

3. SUB_1:

.

. .

.

Instruction Pipeline

Allows overlap of execution and fetch

Makes single cycle execution Program branches (e.g. goto, rcall)

take two cycles

Page 20: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 20

Clocking Scheme Instruction cycle = 2 Input Clocks PIC24F

A 32Mhz clk = 16MIPS or Tcy = 62.5 nS PIC24H/dsPIC33

A 80Mhz clk = 40 MIPS or Tcy = 25 nS dsPIC30F – Instruction cycle = 4 Input Clocks

A 120Mhz clk = 30MIPS or Tcy = 33 nS

1 Instruction cycle (TCY)

OSC1

Q2

Q1

Q3

Q4

FCY

Page 21: MCU3121 16-bit Standard Peripherals and Programming using C30

Lab 1Lab 1My First C30 ProjectMy First C30 Project

Page 22: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 22

Hands-on Exercises

All labs are in the following directory:C:\RTC\MCU3121\LabX where X is the number of the lab

Solution workspaces are supplied in the following directory:C:\RTC\MCU3121\LabX\Solution where X is the number of the lab

Directions for the labs are in the class handout which is also in the following directory:C:\RTC\MCU3121\Presentation & Handouts\MCU3121_Handout v1.0.pdf

Supplementary materials are in the following directory: C:\RTC\MCU3121\User’s Guides and Data Sheets

Page 23: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 23

Labcenter Proteus VSM Virtual prototyping

for PICMicro’s. Simulate complete

embedded systems. Develop and debug

your firmware on virtual hardware. Test and verify

before ordering your prototype.

• Schematic • Simulation of

• PICDEM2+ Board.• www.labcenter.com

Page 24: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 27

Goals: Learn the basics of C30 by working with

a template project To Do:

Follow along with the presenter Expected Result:

Successfully build the project and program the device

LED D3 should blink

Lab 1: Working with C30 and MPLAB IDE

Page 25: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 28

Lab 1: C30 Project

CSource

File

Linker Script(Optional)

C30AssemblerCompiler

AndLinker

Page 26: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 29

Lab 1: Template File

Include statements, Configuration macros, and Define statements

Global variable declarations with and

without attributes

Page 27: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 30

Lab 1: Template File Continued

• Templates for main function and interrupt service routines.

• Note the use of the various ISR attributes

Page 28: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 31

Lab 1: Code

Add this code to

main function

Create delay

function

Now Compile! (F10)

Page 29: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 32

Lab 1: Program Memory ViewReset and Interrupt

Vectors

Initialization code inserted from crt0.s

main() and delay() functions

Interrupt Service Routines

Page 30: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 33

Lab 1: Program Memory & Disassembly Listing

Program Memory Variables

Disassembly Listing

The assembly code that the

compiler generates

Page 31: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 34

Lab 1: Map File

Memory usage data

Data Memory Variable

Locations

Prog Mem Variable & Function Locations

- Locate memory sections in Map file

Page 32: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 35

Lab 1: Watch Window

Data memory on 32-byte boundary (lower 5 bits of address 0)

Program Memory Variable – note longer address

Data memory variables

- Compare addresses to expected values. Do they make sense?

Page 33: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 36

Lab 1: MPLAB SIM

Main loop execution time

Configure Oscillator Frequency

Page 34: MCU3121 16-bit Standard Peripherals and Programming using C30

Data Access From Program MemoryData Access From Program MemoryTable Read/Write & Program Space Visibility (PSV)Table Read/Write & Program Space Visibility (PSV)

Page 35: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 38

Constant Data Access from PM Using Table Instructions

24-bit Effective Address(EA) formation Configuration space is accessed by setting

TBLPAG<7> (i.e. EA<23>) Only means of accessing configuration space

Effective 24-bit PM Address

24-bit Instruction

OP CODE

TBLPAG<7:0>

Source & Dest Regs

15-bits from Source/Dest. Pointer

w w w w w w w w w w w w w w w w

Byte Select

16-bit Source/Dest. PointerTBLPAG Register

TBLPAG<7:0>8-bits fromTBLPAG Register

w w w w w w w w w w w w w w w

p

Word SelectFrom Op Code

Page 36: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 39

Actual 24-bit Program Memory

8-bits

16-bits

0 0 0 0 0 0 0 0

Constant Data Access from PM Using Table Instructions

Table Instruction View of Program Memory

TBLRDH/TBLWTH TBLRDL/TBLWTL

TBLRDL.B/TBLWTL.BTBLRDL.B/TBLWTL.BTBLRDH.B/TBLWTH.B

Phantom Byte

023

Page 37: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 40

Using Table Read/Write in C30

Must use assembly for special instructions and exact timing Add assembly file to project, or, Use C30 Built-ins:const unsigned int myVar = 0xFFFF;unsigned int varAddr;

TBLPAG = __builtin_tblpage(&myVar);varAddr = __builtin_tbloffset(&myVar);

__builtin_tblwtl(varAddr, 0xAAAA); //load data to write://0xAAAA

NVMCON = 0x4003; //NVM word write opcode__builtin_write_NVM(); //unlock & set WR bit

Page 38: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 41

Constant Data Access from PM Using Program Space Visibility

32 KB segment of PM may be mapped into the data memory address space If PSV bit (CORCON<2>) is set and if SrcPointer (DM

EA)<15> is ‘1’ then data is accessed from PM

Effective 24-bit PM Address

14-bits from Source Pointer

0 User Space only

PSVPAG<7:0> w w w w w w w w w w w w w w

0User Space Only

24-bit Instruction

OP CODE Source & Dest Regs

16-bit Source Pointer

Only even words can be accessed

1 w w w w w w w w w w w w w w w

Byte Select

Select PSV

PSVPAG Register

PSVPAG<7:0>

8-bits fromPSVPAG Register

Page 39: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 42

PSV Addressing ExampleData Space

DataEA = 0x9000 PSVPAG0

On Chip User Flash Memory

Near Data Memory

000000H

0

Data Space EA<15:0>

023

Source reg

SFRs

Far Data Memory

PSVPAG0

On Chip User Flash Memory

Alternate Vector Table

Reset Vector

Interrupt Vector Table

Flash Config Words

000000H

7FFFFEH

PC<22:1> 00

0

0

15U

se

r S

pa

ce

Source reg

0000H

0800H

2000H

2FFEH

8000H

0

01

PSVPAG = 0x20

100000H

CORCON<PSV> = 1

ProgEA = 0x101000

32KB

Page 40: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 43

Actual 24-bit Program Memory

8-bits

16-bits

0 0 0 0 0 0 0 0

Data Access from PM Using PSV

WORD access instruction

Byte access instruction with odd address

023

Byte access instruction with even address

0x00 or 0xFF

Only lower 16-bits of PM location can be accessed via mapping- Upper 8 bits should be programmed for a NOP

Page 41: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 44

Using the PSV in C30 Three usage options

Manual PSV char data[256] __attribute__((space(psv))) Must manually point to the correct PSV when

accessing the variable Auto PSV

const char data[256]; or char data[256]

__attribute__((space(auto_psv))) Maximum of 32 KB of constant data allowed Linker does not allow PSV space to cross a

PSVPAG boundary and adjusts automatically

Page 42: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 45

Using the PSV in C30 Compiler Managed PSV

Only in C30 v3.00 and later Allows use of more than 32 KB of

constants Compiler automatically sets

PSVPAG Must apply attribute space(psv) to

variable & declare variable as managed with __psv__ qualifier__psv__ char data[256] __attribute__ ((space(psv)))

Page 43: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 46

Advantages of PSV PSV allows large tables of data to be

stored and accessed quickly & easily PSV provides a bridge to a common

data/program address space (Von Neumann) but only when needed

Example: Strings for display, Sine table, lookup

tablesNote : If your application requires large

data tables, access through TBLPAG should is preferred to optimize PM memory usage

Page 44: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 47

Data Access Overhead Using PSV

PSV data fetch overhead: Outside a REPEAT loop:

Data move ops, overhead = 1 cycle ALU based ops, overhead = 2 cycles

Within a REPEAT loop: Data pipelined, so overhead for all ops = 0

cycles First & last iteration - data pipeline fill/flush

Data move ops, overhead = 1 cycle ALU based ops, overhead = 2 cycles

Page 45: MCU3121 16-bit Standard Peripherals and Programming using C30

Lab 2Lab 2PSV Configuration and UsagePSV Configuration and Usage

Page 46: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 49

Goals: To initialize PSV To store a Hello World string in PSV

space To read and transmit this string to LCD

To Do: Look into the Hand out provided

Expected Result: The text displayed on LCD should match

the array defined

Lab 2: PSV Configuration and Usage

Page 47: MCU3121 16-bit Standard Peripherals and Programming using C30

Software StackSoftware Stack

Page 48: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 51

Two levels used to save PC

Software Stack in Data RAM

SPLIM

Stack Grows

Towards Higher

AddressStack Pointer (W15 )

Top of the Stack

Pushed Data

PCHPCL

PCL

0x00

PCHSRL

0x800

0x27FE

Interruptcallpush

Over Flow Error

Under Flow Error

Page 49: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 52

Frame Pointer

SPLIM

Stack Pointer (W15) Top of the Stack

Local Variable2

Local Variable1Frame Pointer

PCL0x00 PCH

0x800

0x27FE

Call

Frame Pointer (W14)

Offset = 2

Lnk #4Indicates 4 bytes of Space required (always even no.)

Page 50: MCU3121 16-bit Standard Peripherals and Programming using C30

Traps and InterruptsTraps and Interrupts

Page 51: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 54

Interrupt Architecture

Vector Address

CPUInterrupt

Controller

CPU Interrupt

Nat

ura

lP

rio

rity

Interrupts

0

7 0

117C

PU

P

RIO

RIT

Y

0

7

15

8

TRAPS

Address

Use

r S

elec

tab

leP

rio

rity

Sta

tic

Pri

ori

ty

Page 52: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 55

IVT / AIVTHighest Priority

Lowest Priority

Math Err. Trap Vector

Interrupt 0 Vector

RESET VectorAlso used for RESET

Osc. Fail Trap VectorAdrs. Err. Trap Vector

Stack Err. Trap Vector

Reserved

Reserved

ReservedReserved

.

.

.

0x0C0x0E

0x000x020x040x060x08

0xFC0xFE

.

.

.

0x0A

0x100x120x140x16

0x10C0x10E

0x1000x1020x1040x1060x108

0x1FC0x1FE

.

.

.

0x10A

0x110

0x1120x114

0x116Interrupt 1 Vector

Interrupt 116 VectorInterrupt 117 Vector

Page 53: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 56

AIVT Advantage

IF “condition1” is true goto “application” Else goto “debug”

Application_main

Use IVT

...

…..

End

ISR1 ; add. 0x004

Process data

Debug_main

Use AIVT...

…..End

ISR1 ; add. 0x104

Glow LED; Visual Indication

Page 54: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 57

Interrupt Priority CPU has 16 priority levels

Level 0 is the default CPU level (main) Level 1 - 7 for user interrupts Level 8 -15 reserved for traps (NMI)

An interrupt source must have a user-assigned priority level greater than current CPU priority level (IPL<3:0>) to initiate an exception process. Level 4 is the default for all user interrupt sources

Natural order priority (IVT order) is used to resolve conflicts between simultaneous, pending interrupt sources within a given user-assigned priority level

Page 55: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 58

0 1 1 10 1 0 00 0 0 10 0 0 0

L4

main() L0

L1

Interrupt Nesting Example

L7

0123456789101112

Status Register131415

0123456789101112

Core Control Register131415

IPL2

IPL1

IPL0

IPL3

CPU EXECUTION TRACE

RETURN

RETURN*

RETURN

L4 INT

L7 INT

L1 INT

0123

IPL<3:0>

5 Cycle Latency

5 Cycle Latency 7 Cycle Latency

7 Cycle Latency

3 Cycle Latency

Page 56: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 60

Traps Soft Traps

Priority levels 8 through 12 Treated as an NMI with fixed priority ‘Normal’ exception process is taken Example:

Arithmetic error trap (priority level 11) Stack error trap (priority level 12)

Hard Traps Priority levels 13 through 15 CPU execution flow is immediately suspended Execution cannot resume until trap is acknowledged Example:

Address error trap (level 13) Oscillator error trap (level 14)

Page 57: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 61

Error Traps

What happens when a trap occurs? Branches to address 0 by default Better to branch to a reset instruction

Linker adds a reset instruction and vector Best to add your own

error trap handler

12

Page 58: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 62

Configuring Interrupts

IEC0: Interrupt Enable Control Register 0 : Enable Interrupt

0123456789101112131415

INT0IE

IFS0: Interrupt Flag Control Register 0 : Clear Interrupt in the ISR0123456789101112131415

INT0IF

IPC0: Interrupt Priority Control Register 0 : Assign Priority0123456789101112131415

INT0IP

000: Disabled001: Priority 1 Interrupt010: Priority 2 Interrupt011: Priority 3 Interrupt100: Priority 4 Interrupt101: Priority 5 Interrupt110: Priority 6 Interrupt111: Priority 7 Interrupt

Changes to the interrupt priority level should

not be made while an interrupt is enabled

Page 59: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 63

Interrupt Service Routines in C

Compiler saves / restores the ISR context Hardware saves return address and SR

Fast ISR saves W0-W3 in one cycle (only 1 level deep) Uses push.s and pop.s (only 1 level deep)

Globals used by the ISR must be volatile volatile unsigned global_flag;

ISR must clear the Interrupt Flag IFS0bits.T1IF = 0;

Making function calls not recommended Linker will populate the Vector Table

Must use designated interrupt names The designated interrupt names can be found in the .gld file of that

device, which can be found at c:\Program Files\Microchip\MPLAB C30\support\PIC24F\gld

Page 60: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 64

Function Attributes

Declare an interrupt functionvoid __attribute__((interrupt)) _ADCInterrupt(void)void _ISR _IC1Interrupt(void)

Make function use shadow registers

void __attribute__((interrupt,shadow)) _ADCInterrupt(void)

void _ISRFAST _IC1Interrupt(void)int __attribute__((shadow)) FastFunc(int Abc)

Saves W0-W3 and SR bits with push.s and pop.s

Page 61: MCU3121 16-bit Standard Peripherals and Programming using C30

Lab 3Lab 3Interrupt Configuration and UsageInterrupt Configuration and Usage

Page 62: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 66

Goal: Understand Interrupt configuration Understand Interrupt priority Writing Interrupt handler for a given

Interrupt vector To Do:

Look into the Hand out provided Expected Result:

Look into the Hand out provided

Lab 3: Interrupt Configuration and Usage

Page 63: MCU3121 16-bit Standard Peripherals and Programming using C30

16-Bit Peripherals16-Bit Peripherals

Page 64: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 68

PIC24F Family

4 – 16 KBData Memory

Memory Bus

8 – 256 KBFlash Memory

InterruptControl

16 MIPS 16-bit Core

16b ALU16 x 16b W

Register Array

17b x 17b Multiply

Address Generator Unit

Multi-bitShifter

JTAG Interface

Perip

heral B

us

WDT & Pwr Mgmt.

28 - 100-pin Packages

(2 to 4) UART

Real time clock+cal

CTMU

CRC

(5) 16/32 Timers

PMP

INTRC w/PLL

Inte

rrup

tC

on

trol

(2) SPI + (2) I2C

500 Ksps 10b ADC

(2) Comparators

Pe

riph

era

l Pin

Se

lec

t

Output Compare/PWM

Input Capture

New devices with PPS (Peripheral Pin Select) digital I/O pins can be freely connected to peripherals by SW !!

USB 2.0 OTGNEW

Page 65: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 69

PIC24H Family

1 – 16 KB Data Memory

Memory Bus

12 – 256 KBFlash Memory

8 Channel DMA

InterruptControl

40 MIPS 16-bit Core

16b ALU16 x 16b W

Register Array

17b x 17b Multiply

Address Generator Unit

Multi-bitShifter

JTAG Interface

Perip

heral B

us

WDT & Pwr Mgmt.

18 - 100-pin Packages

(1-2) UART w/LIN & IrDA®

(1-2) SPI

(3-9) 16/32 Timers

1.1 Msps 10b ADC

INTRC w/PLL

(0-2) ECAN™

Inte

rrup

tC

on

trol

(1-2) I2C™

500 Ksps 12b ADC

Output Compare/PWM

Input Capture

New devices with PPS (Peripheral Pin Select) digital I/O pins can be freely connected to peripherals by SW !!

Page 66: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 70

30 MIPS 16-bit Core

16b ALU16 x 16b W

Register Array

17b x 17b Multiply

Dual AGU X & Y

BarrelShifter

JTAG Interface

DSP EngineDual 40b

Accumulators

0.5 - 8 KB Data Memory

Memory Bus

12 - 144 KB Flash Memory

1 - 4 KB EEPROM

Perip

heral B

us

WDT & Pwr Mgmt.

18 - 80-pin Packages

(1-2) UART w/LIN & IrDA®

(1-2) SPI

MC QEI

Codec I/F (I2S, AC97)

(2-5) 16/32 Timers

-or- 200 Ksps 12b ADC

MC PWM

INTRC w/PLL

(0-2) CAN™

Inte

rrup

tC

on

trol

(1-2) I2C™

1 Msps 10b ADC

dsPIC30F Family

Output Compare/PWM

Input Capture

Page 67: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 71

40 MIPS 16-bit Core

16b ALU16 x 16b W

Register Array

17b x 17b Multiply

Dual AGU X & Y

BarrelShifter

JTAG Interface

DSP EngineDual 40b

Accumulators

1 – 30 KB Data Memory

Memory Bus

12 – 256 KB Flash Memory

8-channel DMA

Inte

rrup

tC

on

trol

Perip

heral B

us

WDT & Pwr Mgmt.

18 - 100-pin Packages

(1-2) UART w/LIN & IrDA®

(1-2) SPI™

(0-2) MC QEI

Codec I/F (I2S, AC97)

(3-9) 16/32 Timers

(4-8) MC PWM

INTRC w/PLL

(0-2) ECAN™

(1-2) I2C™

(1-2) 1.1Msps 10b ADC

(1-2) 500Ksps 12b ADC

dsPIC33F Family

(2) 16 bits Audio DAC

IC / OC / PWM

New devices with PPS (Peripheral Pin Select) digital I/O pins can be freely connected to peripherals by SW !!

Page 68: MCU3121 16-bit Standard Peripherals and Programming using C30

I/O PortsI/O Ports

Page 69: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 73

I/O PORT

1 1 1111111

2 1 03456715

I I IIIIIII

TRISA

PORTA Function

PINs

0

O

0 0

OO

Page 70: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 74

Digital I/O Ports

Internal Data Bus

Write PORTxWrite LATx

Read LATx Read PORTx

LATx Register(PORTx Output

Latches)

PORTx I/O Pins

Page 71: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 75

Why do we have LAT Reg?

VIL

V on PORTA,PIN0

Q1 Q2 Q3Q4

At Low Frequency or Low Capacitive LoadingBSET PORTA,PIN0 BSET PORTA,PIN1

VIL

V on PORTA,PIN0

Q1 Q2 Q3Q4

At High Frequency or High Capacitive Loading

Q4BSET PORTA,PIN0 BSET PORTA,PIN1

Port A Read in RMW Operation

Port A Read in RMW Operation

Qclks

Qclks

Voltage

Voltage

Page 72: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 76

Why do we have LAT Reg?

For Read-Modify-Write operations on port pins, use the LATch rather than PORTx: BSET LATA,#0 BSET LATA,#1

_LATA0 = 0 ; // = LATAbits.LATA0 _LATA1 = 1 ; // = LATAbits.LATA1

Page 73: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 77

I/O PORTOpen Drain Control

0 0 0000000

2 1 03456715

ODCx

PORTx Function

PINs

1

Drive Logic

OD

Page 74: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 78

Interfacing to 5V devices

PIC24FJxxxx Peripheral

+3.3V +5V

CMOS InputsVih(min) = 3.5V

CMOS Open drain

output

5V tolerant input

CMOS output

5V tolerant input and Open drain configuration simplifies 5V interface

Page 75: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 79

Interfacing to 5V devices

Interfacing to low impedence 5V load with open drain feature

PIC24FJxxxx

5V

Load onLogic low

5V

Load OffLogic high

PIC24FJxxxx

Page 76: MCU3121 16-bit Standard Peripherals and Programming using C30

ADCADCAnalog-to-Digital ConverterAnalog-to-Digital Converter

Page 77: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 81

Successive Approximation (SAR) conversion Conversion speeds of up to 500ksps Up to 16 analog input pins External Voltage reference pins Automatic Channel Scan mode Selectable conversion trigger source 16-word conversion result buffer Selectable Buffer Fill modes Four result alignment options Operation during CPU Sleep and Idle modes

10 Bit ADC Features

Page 78: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 82

PIC24F A/D

VREF+

VREF-

A/Dconverter

ConversionControl

Bu

s In

terfa

ce

DataFormat

SampleSequenceControl

Inp

ut M

uxes

AN0

AN1S/H

AN15

CH0 8/16 LevelResults Buffer

VR+

VR-

VR

S

elec

t

AVDD

AVSS

Page 79: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 83

10-bit ADC - Block Diagram

AVDD

AVSS

VREF+

VREF-

VR+

VR-V

R S

elec

t

AD1CON2<VCFG2:VCFG0>

AVSSAVDD1xx

VREF-VREF+011

VREF-AVDD010

AVSSVREF+001

AVSSAVDD000

VR-VR+VCFG2:VCFG0

AD1CON2 Register

bit15

CSSL13=0CSSL14=0CSSL15=0

BUFMbit0

ALTS

CSNAVCFG2 VCFG1 VCFG0bit8

SMPI1 SMPI 0SMPI3 SMPI2BUFSbit7

--- --- --- ---

---

Page 80: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 84

10-bit ADC - Block DiagramAN0AN1

AN15

Mux

A

VR-

AN1

AD1CHS<CH0SA3:CH0SA0>

AD1CHS<CH0NA>

VINH

VINL

(0)

(1)

AD1PCFG Registerbit15

CSSL10=0CSSL13=0CSSL14=0 CSSL8=0PCFG1bit0

PCFG0PCFG2PCFG15 PCFG14 PCFG13 …………

bit8AD1CON2 Register

bit15

CSSL13=0CSSL14=0

BUFMbit0

ALTS

CSNAVCFG2 VCFG1 VCFG0

SMPI1 SMPI 0SMPI3 SMPI2BUFSbit7

--- --- --- ---

---

bit8AD1CHS Register

bit15

CH0SA1bit0

CH0SA0CH0SA2CH0NAbit7

CH0SA3

CH0SB1 CH0SB0CH0SB2CH0NB CH0SB3--- --- ---

--- --- ---

AD1CSSL Registerbit15

CSSL13=0CSSL14=0 CSSL1bit0

CSSL0CSSL2CSSL15 CSSL14 CSSL13 …………

Page 81: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 85

Channel Scanning

ADCBUF Buffer

+

-

CH 0

AN15AN14

….

AN5AN4AN3AN2AN1AN0

+B- B

+A

- A

VREF-

AN1

AN0AN2

AN13AN14

INTADCBUF0

AD1CSSL Registerbit15

CSSL13=0CSSL14=0 CSSL1bit0

CSSL0CSSL2CSSL15 CSSL14 CSSL13

AN13

…………

bit8AD1CON2 Register

bit15

CSSL13=0CSSL14=0

BUFMbit0

ALTS

CSNAVCFG2 VCFG1 VCFG0

SMPI1 SMPI 0SMPI3 SMPI2BUFSbit7

--- --- --- ---

---

Page 82: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 86

10-bit ADC - Block Diagram

VINH

VINL

S/H

Mux

AM

ux B

AD1CON1<ASAM>

AD1CON1<SAMP>Conversion complete Signal

01

bit8

AD1CON2 Registerbit15

CSSL13=0

BUFMbit0

ALTS

CSNAVCFG2 VCFG1 VCFG0

SMPI1 SMPI 0SMPI3 SMPI2BUFSbit7

--- --- --- ---

---

Page 83: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 87

10-bit ADC - Block Diagram

VINH

VINL

S/H

AD1CON1<ASAM>

AD1CON1<SAMP>

Conversion complete Signal

ADC1BUF0 :

ADC1BUF15

RESULT

VR+VR-

AD1CON1<DONE>

AD1CON3<SAMC4:SAMC0> (7) 0 TAD to 31 TAD

AD1CON1 <SSRC2:SSRC0>

Clearing AD1CON1<SAMP> (0)Active Transition on INT0 pin (1)Timer4 Compare ends (2)

Avoid 0 TAD

A/Dconverter

VR- VR+

Page 84: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 88

10-bit ADC - Block Diagram

AD1CON3<ADCS7:ADCS0>

TCY to 256*TCY

RCAD

FCY = FOSC/2

TAD

AD1CON3<ADRC>

1

0

AD Clock Postscaler ÷ by

1 to 256

Page 85: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 89

10-bit ADC - Block Diagram

0000 00dd dddd ddddssss sssd dddd dddddddd dddd dd00 0000sddd dddd dd00 0000

RESULTFORMAT

AD1CON1<FORM1:FORM0>

AD1CON2<BUFM> = ‘0’

AD1CON2<BUFS>

AD1CON2<SMPI3:SMPI0>

ADC1BUF0::::::

ADC1BUF15

AD1CON2<BUFM> = ‘1’

ADC1BUF0::

ADC1BUF7

ADC1BUF8::

ADC1BUF15

0

1

Page 86: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 90

AcquisitionTime

ConversionTime

StartAcquisition

Time

EndConversion

AnalogInput

A/D Sampling Time

A/D Clock

TAD

Acquisition/Conversion Timing

Page 87: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 91

12-bit A/D Converter Up to 500 K Samples / Sec Sampling Rate

Up to 32 input channels ( 2 x A/D )

16 conversion results deep buffer (dsPIC30)

DMA capable (PIC24H / dsPIC33)

Analog Input Range: Vss to Vdd (or VREF- to VREF+)

Multiple Trigger sources for Start of Conversion Software Trigger

Motor Control PWM

Timer 3

External Interrupt

Automatic conversion on internal time out

Page 88: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 92

PIC24H/30/33 A/D

A/Dconverter

ConversionControl

Bu

s In

terfa

ce

DataFormat

SampleSequenceControl

Inp

ut M

uxes

AN0

AN1

S/H

S/H

S/H

S/H

AN31

Results Buffer

CH0

CH1 *

CH2 *

CH3 *

* S/H channels 1, 2 & 3 only available on 10- bit mode

VREF+

VREF-

VR+

VR-

VR

S

elec

t

AVDD

AVSS

Page 89: MCU3121 16-bit Standard Peripherals and Programming using C30

Lab 4Lab 4ADC Configuration and UsageADC Configuration and Usage

Page 90: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 94

Lab 4: ADC Configuration and Usage

Goal To configure ADC To configure I/O ports To read ADC and o/p on to LEDs

To Do: Look into the Hand out provided

Expected Result: The average pot value is displayed

on LEDs

Page 91: MCU3121 16-bit Standard Peripherals and Programming using C30

Analog Comparator ModuleAnalog Comparator Module

Page 92: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 96

Analog Comparator Block Diagram

CMCON<CxPOS>

Comp

_

+

CxIN+

CxIN-

CxIN+CVREF

CMCON<CxNEG> CMCON<CxINV> CMCON<CxOUT>

CxOUT

CMCON<CxOUTEN>

VIN -

VIN +

CMCON<CxEN>

Page 93: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 97

Analog Comparator Voltage Reference Generator

16 – to – 1 M

UX

VREF+AVDD

CVRCON<CVRSS>

CVRCON<CVREN>

CVRCON<CVRR>

8 R

8 R

RRRR

RRR CVRCON<CVROE>

CVREF

CVRCON<CVR3:CVR0>

16 Steps

0

1

VREF-AVSS

1

0CVRCON<CVRSS> (CVR<3:0>)*CVRSrc/241

((CVR<3:0>)+8)*CVRSrc/320

Step SizeCVRR

Page 94: MCU3121 16-bit Standard Peripherals and Programming using C30

TimersTimers

Page 95: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 99

Timer Features

Five 16-bit General Purpose Timers / Counters Similar functionality between all 5 timers

Asynchronous counter feature only in Timer1

Period Registers for each Interrupt generation on match Reset on match

Gated Timer operation on each Interrupt on falling edge of gate

Four of these timers (Timer 2+3 & 4+5) can make two 32-bit timers/counters

Page 96: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 100

Timer x

Tx Int Flag

TMRx

PRx

CompEq.

Rst

TCKPS<1:0>TON

Sync

Prescaler

1, 8, 64, 256

0

1

GateSync

TCS

1 X

0 1

0 0TG

ATE

TCY

TxCKI

ADC Event Trigger

Timer4/5

TIMER1 ONLY

ALL TIMERS

TGATE TCSCK

TGATEQ D

SOSC1

SOSC2

LP

OSC

SO

SC

EN

TSYNC

1

0

Page 97: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 101

32-bit Timer (T2+T3/T4+T5)

T3/T5

Interrupt Flag

CK

TGATE

Equal

Reset

TCKPS<1:0>TON

Sync

Prescaler

1, 8, 64, 256GateSync

TCS

TG

ATE

0

1

T2CKI/T4CKI

1 X

TCY

ADC Event Trigger

(Timer 5 only) Comparator x 32

TMR2/4TMR3/5

PR2/4PR3/5

0 1

0 0

Write TMR2/4Read

TMR2/4

TMR3/5HLD

LSWMSW

**T3CON/T5CON SFRs bits are ignored when in 32-bit timer mode

TxCON<T32>

TGATE TCS

DQ

Page 98: MCU3121 16-bit Standard Peripherals and Programming using C30

Lab 5Lab 5Configuration of 32-Bit TimersConfiguration of 32-Bit Timers

Page 99: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 103

Goal Understand working of Timers in 32 bit mode Configure the Timer 2/3 pair for 32 bit mode Implement a stop watch

To Do: Look into the Hand out provided

Expected Result: Press the Switch S3 to start timer Again press the Switch S3 to stop timer and

LCD displays the Time elapsed between the start and stop

Lab 5: Configuration of 32-Bit Timers

Page 100: MCU3121 16-bit Standard Peripherals and Programming using C30

Input CaptureInput Capture

Page 101: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 105

Why Do We Need IC Module Consider an Example to measure the Pulse width of the

signal The IC Module should be configured to

Capture on Every Edge Interrupt on every Second Event

Then the Pulse width of the signal can be found by using the formula:

Buffer 1 Buffer 0-Timer running

Frequency

Pulse Width =

Page 102: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 106

Input Capture

Input Capture Up to five Input Capture Channels Captures 16-bit timer value Tcy Resolution Timer 2 or Timer 3 as time base

Page 103: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 107

Input Capture

ICTMRICx Prescaler

CounterEdge Detection Logic and Sync

Module Control Logic

TMR2

1 0

FIFO

ICxBUFICxF Interrupt

Flag

TMR3

11: Interrupt on every fourth capture event10: Interrupt on every third capture event01: Interrupt on every second capture event00: Interrupt on every capture event

111: Input Capture functions just as an interrupt pin while in SLEEP or IDLE mode101: Capture on every sixteenth rising edge100: Capture on every forth rising edge 011: Capture on every rising edge 010: Capture on every falling edge 001: Capture on every edge (both rising and falling) 000: Capture module is turned off

ICxCON<ICI1:ICI0> ICxCON<ICM2:ICM0>

Page 104: MCU3121 16-bit Standard Peripherals and Programming using C30

Output Compare and PWMOutput Compare and PWM

Page 105: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 109

Up to 8 Output Compare / PWM Channels Timer 2 or Timer 3 as time base 16-bit Compare Minimum 1Tcy pulse width allowed Several Compare Modes:

Set, Reset or Toggle Pin Single Pulse, Continuous pulse PWM Single Compare Match Mode (using OCxR) Dual Compare Match Mode (using OCxR & OCxRS)

Output Compare & PWM

Page 106: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 110

Output Compare

111: PWM mode with Fault pin option110: PWM mode without Fault pin option

101: Initialize OCx-low, generate continuous signal 100: Initialize OCx-low, generate single pulse 011: Toggle OCx on every compare match 010: Initialize OCx-High, pull OCx low on compare match

001: Initialize OCx-low, pull OCx high on compare match

000: Compare module is turned off

SR

QOutput

CompareLogic

Comparator

OCxR

OCxRS

0 1 0 1OCTSEL

TMR2Timer2/3

Period Match

OCFA/B

OCFx

OCM<2:0>Mode Select

OCxIFInterrupt Flag

TMR3

OCxCON<OCM2:OCM0>

Page 107: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 111

PWM mode 16-bit glitch-less (double buffered) PWM

output Full range of 0 to 100% duty cycle Wide frequency range Selectable PWM shutdown on fault

detection This is an Asynchronous shutdown

Output Compare Module

Page 108: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 112

OC PWM Mode

On timer period match OCx set, TMR COUNT cleared OCxRS copied to OCxR

On OCxR match OCx cleared

TMR COUNT

Time

OCxR

OCx

OCxRS

OCxR

PR

Page 109: MCU3121 16-bit Standard Peripherals and Programming using C30

UARTUART

Page 110: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 114

UART Features

4-deep FIFO Transmit Data Buffer 4-deep FIFO Receive Data Buffer Parity, Framing and Buffer Overrun Error

Detection Support for 9-bit mode with Address

Detect (9th bit = 1) Transmit and Receive Interrupts Loopback mode for Diagnostic Support LIN 1.2 Protocol Support IrDA® Support

Page 111: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 115

UART Module – Transmit

UxCTS

(Start)

(Stop)

UxTX

UTXBRK

ParityGenerator

÷16Divider

Transmit Shift Register UxTSR

UxTXREGUTX8- Control UxTSR- Control Buffer- Generate Flags- Generate Interrupt

Transmit Control

UxTXIF

Load UxTSR

Transmit FIFO

Word Write Word/ByteWrite

Internal Data Bus16

UxMODE UxSTA

Page 112: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 116

UART Module – Receive

UxRX

UxTX

LPBACK

-Start bit detect- Parity check

- Stop bit detect- Wake Logic

÷16 Divider

ReceiveShift Register UxRSR

UxRXREGURX8

- Generate Flags- Generate Interrupt- Shift Data Character

Receive Control

UxRXIF

Load UxRXREG

Receive FIFO

Word ReadWord/Byte

Read

Internal Data Bus16

UxMODE UxSTA

UENSelection

BCLKx/UxRTS

UxCTS

BCLKx

UxRTS

UxCTS

16x Baud Clock

Page 113: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 117

UART with CTS and RTS

Controlled Transmission and Reception Simplex Mode Flow Control Mode

Simplex Mode

DTE

16-bitMicro

DCE

Modem

RTS RTS

CTS CTS

RS232 Transceivers

May I send something?

Ok, go ahead and send.

Flow Control Mode

DTE

16-bitMicro

DTE

PC

RTS RTS

CTS CTS

RS232 Transceivers

I am ready to receive

I am ready to receive

Page 114: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 118

UART - IrDA® Support

Built-in IrDA Encoder and Decoder The IrDA Encoder and Decoder can be

enabled by setting UxMODE<IREN> bit

16x Baud Clock is generated to support external IrDA Encoder and Decoder 16x Baud Clock is generated by setting

UxMODE<UEN1:UEN0> to ’11’ The generated Baud Clock is available

on the pin BCLKx

Page 115: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 119

Optical Communication

Two ways to connect LED

I/O

Logic High = LED OnLogic Low = LED off

I/O

Logic Low = LED OnLogic High = LED off

Vdd

Page 116: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 120

IrDA® Mode Bit Encoding

UxTXData

UxTX

UxTX

16x BaudClock

UxTXData

UxTX

‘0’ Transmit Bit

8th 11th

Page 117: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 121

UART - LIN Support

Transmission of Break Characters A Break character can be transmitted by

setting the UxSTA<UTXBRK> bit for at least 13 bit times

Autobaud Detection

Master Header

Message Frame

SyncBreak SyncField IdentField Data Checksum

Slave Response

Master or

Page 118: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 122

Master Header

Message Frame

SyncBreak SyncField IdentField Data Checksum

Slave Response

LIN - Protocol

UxSTA<UTXBRK> Enables Transmitting Break

condition on the bus (Drive low TX pin for 13-Bit

Time)

UxMODE<ABAUD> Enables to measure the baud-

rate using Input Capture unit during SYNCH Field

(0x55).

Master or

Page 119: MCU3121 16-bit Standard Peripherals and Programming using C30

Lab 6Lab 6UART Configuration and Usage of FIFOUART Configuration and Usage of FIFO

Page 120: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 124

LAB 6: Working with UART

Goal: Understand Configuration of UART module Understand Transmit and Receive interrupts Write a software to Transmit and Receive data

using UART To Do:

Look into the Hand out provided Expected Result:

LED D3 flashes at different rates to indicate lower CPU time spent handling UART data using FIFO buffer

Page 121: MCU3121 16-bit Standard Peripherals and Programming using C30

I2C™I2C™

Page 122: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 126

I2C™ Overview

Synchronous 2-wire communication

Master-Slave protocol Serial interface (Half-duplex):

SDA: Data line to & from the master SCL: Clock line, master controlled

Page 123: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 129

I2C™

SCLx

Control Logic

I2CBRG(9-bit) MASTER Mode

BRG TCY/2

I2CxCON(16-bit)

I2CxSTAT(16-bit)

SDAx

I2CxTRN(8-bit)

Shift Clock

Add. Match Detect I2CxADD(10-bit)

I2CxMSK(10-bit)RSR

I2CxRCV(8-bit)

Shift Clock

MASTERSLAVE

Page 124: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 130

Address Masking

What is it? It allows a PIC® MCU to ACK more than

one address.What is it good for? IPMI: Intelligent Platform Management

Interface Embedded system device networking: using

a PIC MCU as multiple I2C™ devices

Page 125: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 131

Embedded System Device Networking

PIC®

MCU

MSTR

EPROM

PICMCU

SLV

RTC

ADC

3V 3V

SCLSDA

PWM

Page 126: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 132

Embedded System Device Networking

PIC®

MCU

MSTRPIC

MCU

SLV

ADC

3V 3V

SCLSDA

RTC

EPROM

P

W

M

Eliminate external I2C™ devices

Page 127: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 133

Address Masking Example

All addresses that will be ACKed: A7.A6.A5.0.A3.0.0 A7.A6.A5.0.A3.0.1 A7.A6.A5.0.A3.1.0 A7.A6.A5.0.A3.1.1 A7.A6.A5.1.A3.0.0 A7.A6.A5.1.A3.0.1 A7.A6.A5.1.A3.1.0 A7.A6.A5.1.A3.1.1

S R/W=0 ACKA7 A6 A5 X A3 X X

By setting the ADMSK bits in SSPCON2, we mask the address bits.

In this case ADMSK[7:1]=0001011

Page 128: MCU3121 16-bit Standard Peripherals and Programming using C30

SPISPI

Page 129: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 135

SPI - Overview

Serial transmission and reception of 8/16-bit data Full-duplex, synchronous communication 4-wire interface Supports 4 different clock formats and serial

clock speeds up to 10 Mbps Buffered Transmission and Reception

MASTER SLAVE

SCK SCK

SDO SDI

SDI SDO

SS SS

Page 130: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 136

SPI Block Diagram

FCY

MASTERSPIxSR

SPIxBUF

SDIx

SDOx

8-Level FIFO (Enhance Mode)

SSx

SCKx

Sync Control

Clock Control

Select Edge

Pre- scaler

Clock Enable

SLAVE

PIC24F devices utilize FIFO. Other 16-bit

devices can use DMA for data

transfers

Page 131: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 137

SPI Clock

bit7 bit0

bit15 bit8DISSDO-SPIFSDFRMEN-

MSTEN=1CKP=0SSEN PPRE<1:0>

SPIxCON Register

MODE16 SMP CKE=1

SPRE<2:0>

PPRE SPRE

Fcy SCK1,4,16,64 1,2,...8

CKP: Clock Polarity Select 0: Idle State of CLK is LOW 1: Idle State of CLK is HIGH

CKE: Clock Edge Select 0: Transmit data on Idle to Active Edge 1: Transmit data on Active to Idle Edge

Page 132: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 138

SPI - Serial Clock Formats

(a) CKP = 0, CKE = 0

(a)SCK

(b) CKP = 0, CKE = 1

(b)SCK

(c) CKP = 1, CKE = 0

(c)SCK

(d) CKP = 1, CKE = 1

(d)SCK

SDO(0x69)

(b) and (d)0 1 1 0 1 0 0 1

Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0

SDO(0x69)

(a) and (c)11 1 10 0 0 0

Page 133: MCU3121 16-bit Standard Peripherals and Programming using C30

Special FeaturesSpecial Features

Page 134: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 140

Powering CPUPIC24FJ, PIC24HJ, dsPIC33FJ

Internal on-chip regulator 2.5V nominal for the CPU 3.3V nominal for the I/O and

peripheral voltage Low ESR cap required

10µf recommended VREG Control pin (PIC24F)

Enable/disable the regulator BOR

VREGControl

Vddcore/Vcap

Vdd

3.3V

Regulator

PIC24FJ128GA

10µf

CPU

Page 135: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 141

Power Management Power management options:

Lower the supply voltage Lower the clock speed

Postscaler Clock switching

Disable unused peripherals Minimal power saving

Execute pwrsav instruction SLEEP IDLE

DOZE mode

LPRC FRC

POSC SOSC

FRC + PLL

POSC + PLL

Page 136: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 142

Power Management

Exiting Power Saving mode System Reset Watch Dog Timer Any enabled interrupt

Interrupt Priority Level <= CPU IPL Execute the next instruction

Interrupt Priority Level > CPU IPL Execute the interrupt handler

How to know it is a wake up Check RCON<SLEEP> and RCON<IDLE> bits

Page 137: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 143

Clock Sources

32KHzSecondary

Crystal OSC

SOSCI

SOSCO

Low Pwr RC 32KHz

Fast RC 8.0 MHz

OSCI

OSCO

PostScaler

4x PLL

PostScaler

CPU Clock

Peripherals Clock

XT,HSCrystal

OSC

EC Clock

Primary Oscillator

Page 138: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 144

Clock Sources

XT,HSCrystal OSC

EC Clock

Primary Oscillator

XT, EC, HS 4x PLL XTPLL, ECPLL,

32KHzSecondary

Crystal OSC

SOSC

OSCI

OSCO

It is 4x PLL only in PIC24F. In other 16 bit controllers it can be configured into 4x, 8x or 16x PLL

Page 139: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 145

Clock Sources

Fast RC 8.0 MHz

FRCPostScaler, ÷ by1, 2, 4, 8, 16, 32,

64 or 256

CLKDIV<RCDIV2:RCDIV0>

FRCDIV 4x PLL FRCPLL (÷1 or ÷2)

LPRCLow Pwr. RC 32 KHz

Page 140: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 146

On-the-Fly Clock Switching

OSCCON<OSWEN> bit to enable On Fly Clock Switching and OSCCON<NOSC2:NOSC0> bits to select the new clock source

Instruction-Based Power Saving Modes Sleep Idle

Power Saving Technology

LPRC FRC

POSC SOSC

FRC + PLL

POSC + PLL

Page 141: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 147

XT, HS, EC

PostScaler ÷ By

1, 2, 4, 8, 16, 32, 64, 128

CLKDIV<DOZE2:DOZE0>

HSPLL,ECPLL

FRCDIV

FRC

LPRC

SOSC

CPU Clock

Peripherals Clock

FRCPLL

Doze Mode

CLKDIV<DOZEN>

Page 142: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 148

Fail-Safe Clock Monitor

What happens on Oscillator Failure? Device switches automatically to the FRC oscillator if

FSCM is enabled FSCM controlled by the bit FOSC<FCKSM>

Oscillator Failure Trap is generated

Code execution vectors to the Oscillator Fail trap handler, if one exists. Here the application should: Clear the Clock Fail bit, OSCCON<CF>

Clear the Osc FAIL trap flag, INTCON1<OSCFAIL>

Switch to required Clock Source form FRC

Execute a RETFIE

Page 143: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 149

Resets

PIC24 RESETS Power-on Reset (POR) Pin Reset (MCLR) RESET Instruction (SWR) Watchdog Timer Reset (WDT) Brown-out Reset (BOR) Trap Conflict Reset (TRAPR) Illegal Opcode Reset (IOPUWR) Uninitialized W Register Reset (UWR) Configuration word mismatch Reset (CM)

For all the resets PC vectors to address 0

Page 144: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 150

Watchdog Timer

Recovers from software malfunction Resets MCU if not attended on-time

Software must clear it periodically (CLRWDT) Programmable timeout period

1 ms to 131 s typical Fuse time programmable prescaler and

postscaler Both Fuse time and Run time Enable available Option to select Windowed WDT

CLRWDT should be used only in last quadrant If CLRWDT is used earlier, resets the device

Page 145: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 151

Programming Support

In Circuit Serial Programming™ (ICSP™): Device can be programmed in circuit Useful to Combine Programming and Final test

Enhanced In Circuit Serial Programming™ (Enhanced ICSP™) capability:

Uses programming executive for faster programming Run Time Self Programming (RTSP):

Device can program its own Flash memory Useful for Remote code updates

JTAG Interface Programming support through Serial Vector Format files Provides for boundary scan

Page 146: MCU3121 16-bit Standard Peripherals and Programming using C30

SummarySummary

Page 147: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 153

Summary We reviewed the 16-Bit Family Architecture

16-bit Datapath & Key CPU registers Program/Data Memory and Data Access from Program Memory Interrupt Handling and latency

We reviewed the MPLAB C30 C Language Extensions The basics of creating an embedded c-application for the

PIC24F/dsPIC We reviewed the 16-bit Family Basic Peripherals

I/O Ports ADC Comparators, Voltage Reference Timers Input Capture Output Compare & PWM USART I2C™ SPI

Special features of 16-bit microcontrollers

Page 148: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 154

Summary

Carried out the Labs on Using MPLAB and C30 PSV initialization and usage Interrupt handling and its priority setting Initialization and ADC conversion 32-bit Timer configuration and its usage UART configuration and use of FIFO

Page 149: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 155

Development Tools Used

Real ICE DV244005

Explorer 16 with PIC24FJ128GA010 PIM DM240001

Page 150: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 156

References

PIC24F, PIC24H, dsPIC33 F Datasheets PIC24F family reference manual dsPIC30F family reference Manual Explorer 16 User’s Guide C30 Compiler User’s Guide Other 16-bit RTC Courses

204 ADV: Advanced 16-bit peripherals 103 ASP: Intro. To 16-Bit Arch. & Assembly

Language Programming 104 DSP: dsPIC DSP Engine 301 MCW: BLDC Motor Control Using dsPIC 312 DPS: SMPS Design Using dsPIC

www.microchip.com/pic24

Page 151: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 157

Page 152: MCU3121 16-bit Standard Peripherals and Programming using C30

Appendix AAppendix AMPLAB C30 C-Language ExtensionsMPLAB C30 C-Language Extensions

Page 153: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 159

MPLAB C30 Compiler 3 Products,

MPLAB C Compiler for PIC24 MCUs and dsPIC DSCs (SW006012) $895US (one-time cost)

MPLAB C Compiler for dsPICs DSCs (SW006013) $495US

MPLAB C Compiler for PIC24 MCUs (SW0066014) $495US

Targets ANSI: 1989 standard Built off GCC Compiler

Standard C functions Run time libraries

Free Student Versions available (Optimizations disabled after 60 days)

www.microchip.com/c30

Page 154: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 160

.a Linker

.o

.s

Development Tools Data FlowC Compiler

(and Preprocessor).c

.s

Archiver(Librarian)

MPLAB IDEDebug Tool

C Source Files

Assembly Source Files

Assembly Source Files

Object Files

Object File Libraries (Archives)

Linker ScriptCOFFDebug File

Executable

Memory Map

Compiler Driver Program

Assembler

.hC Header Files

.incAssembly Include Files

.gld

.hex

.map

.cof

Page 155: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 161

C30 C Language Extensions- Agenda -

Program Memory Variables SFR Access Mixing C and Assembly Built-in Functions Specifying Attributes of Variables &

Functions Interrupt Support Configuration Settings Support

Page 156: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 162

Variables in Program Memory

const - data type qualifier indicates that a variable is located in program memory space, and is to be accessed as an “Auto PSV” type (i.e. compiler-managed PSV) ex. const char data[256];

Can optionally place and access constants in data memory using the constants-in-memory memory model

const data is limited to <32kB See PSV slides for more options (>32kB)

Page 157: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 163

C30 C Language Extensions

Program Memory Variables SFR Access Mixing C and Assembly Built-in Functions Specifying Attributes of Variables &

Functions Interrupt Support Configuration Settings Support

Page 158: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 164

SFR Access

Special Function Registers can be accessed directly in C code: Word access: PORTA = 0xFFEC; SFRNAMEbits.BITNAME can be used to

access bits and bit fields e.g. PORTAbits.RA1 = 1; or

IPC0bits.INT0IP = 0; _SFRNAME and _BITNAME can also be

used to reference an SFR or bit e.g. _PORTA or _RA1

Must use standard header and linker script files

Page 159: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 165

C30 C Language Extensions

Program Memory Variables SFR Access Mixing C and Assembly Built-in Functions Specifying Attributes of Variables &

Functions Interrupt Support Configuration Settings Support

Page 160: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 166

Mixing C and Assembly

Assembly files (.s ) can be used in C30 projects and called from C Details available in C30 User’s Guide

Inline assembly can be inserted into C source code Simple method: asm(“reset”) asm(“clrwdt”)

Complex method: a = b + c

asm volatile(“add %1, %2, %0” : “=r”(a) : “r”(b), “r”(c))

Page 161: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 167

C30 C Language Extensions

Program Memory Variables SFR Access Mixing C and Assembly Built-in Functions Specifying Attributes of Variables &

Functions Interrupt Support Configuration Settings Support

Page 162: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 168

Built-in Functions

Enable use of special hardware features Multiply

Divide

Table pointers

PSV – retrieve and access PSV information

__builtin_divsd(const long num, const int den)

__builtin_mulss(const signed int p0, const signed int p1)

__builtin_tblpage(const void *p)__builtin_tbloffset(const void *p)__builtin_tblwtl(unsigned int offset, unsigned int data)__builtin_tblrdl(unsigned int offset)

__builtin_psvpage(const void *p)__builtin_psvoffset(const void *p)

Page 163: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 169

Built-in Functions

More efficient code – Faster & Smaller Bit toggle

Locked register writes

All DSP Operations

Other “built-ins” Nop(), Sleep() & Idle(), ClrWdt()

__builtin_btg(unsigned int *, unsigned int 0xn)

__builtin_write_NVM(void); //sets WR bit__builtin_write_OSCCONL(unsigned char value)__builtin_write_OSCCONH(unsigned char value)

__builtin_mac(…)

Page 164: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 170

C30 C Language Extensions

Program Memory Variables SFR Access Mixing C and Assembly Built-in Functions Specifying Attributes of Variables &

Functions Interrupt Support Configuration Settings Support

Page 165: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 171

Attributes of Variables

The keyword __attribute__ allows you to specify special attributes of variables or structures including Placement of objects in certain

locations in memory Alignment of objects to memory

boundaries

Page 166: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 172

Data Attributes: Examples

Place data at a specific addressint MyVar __attribute__((address(0x860)))int __attribute__((address(0x862))) MyVar2

Be careful about overlap and auto variables

Place into near memory (below 8kB)char __attribute__((near)) MyVar3, MyVar4

Page 167: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 173

Data Attributes: Examples

Place in a specific section or spaceint foo __attribute__((section(“ThePlace”)))int bar __attribute__((space(psv)))

New section will be created, if needed Spaces: data, prog, psv, eedata

Align begin or end to a multi-byte boundary

char __attribute__((aligned(32))) MyArray[18]int __attribute__((reverse(64))) EndArray[25]

Page 168: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 174

Attributes of Functions

The keyword __attribute__ allows you to declare certain things about your function which help the compiler optimize function calls and check your code

Examples include Absolute function placement in memory Specification of ISR functions

Page 169: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 175

Function Attributes: Examples

Placement of a function at a particular address

Declaration of interrupt service routines…

void foo() __attribute__ (address(0x100))) {...}

Page 170: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 176

C30 C Language Extensions

Program Memory Variables SFR Access Mixing C and Assembly Built-in Functions Specifying Attributes of Variables &

Functions Interrupt Support Configuration Settings Support

Page 171: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 177

Interrupt Support

Declaring interrupts with the compiler has two components: Declaring a function as an interrupt

service routine (ISR) Specifying additional attributes

Page 172: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 178

Interrupt Support

Declare an interrupt function

void __attribute__((interrupt))_ADCInterrupt(void)

Make function use shadow registers

void __attribute__((interrupt,shadow))_ADCInterrupt(void)

Saves W0-W3 and SR bits with push.s and pop.s

Optionally, save other variables on context save

void

__attribute__((interrupt(save(var1,var2))))_ADCInterrupt(void)

Page 173: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 179

C30 C Language Extensions

Program Memory Variables SFR Access Mixing C and Assembly Built-in Functions Specifying Attributes of Variables &

Functions Interrupt Support Configuration Settings Support

Page 174: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 180

Configuration Settings

Device configuration can be set in MPLAB IDE using “Configuration bits” window

A better way is to use _config directives in C code _CONFIG1(<VALUE1> & <VALUE2>) ;

_CONFIG2(<VALUE>);

MCU header files contain valid config definitions and mnemonics

e.g. _CONFIG1(GCP_OFF & GWRP_OFF & FWDT_ON & ICS_PGx2)

Page 175: MCU3121 16-bit Standard Peripherals and Programming using C30

© 2008 Microchip Technology Incorporated. All Rights Reserved. MCU3121 Slide 181

Trademarks

The Microchip name and logo, the Microchip logo, Accuron, dsPIC, KeeLoq, microID, MPLAB, PIC, PICmicro, PICSTART, PRO MATE, PowerSmart, rfPIC and SmartShunt are registered trademarks of Microchip Technology Incorporated in the U.S.A. and other countries.

AmpLab, FilterLab, Migratable Memory, MXDEV, MXLAB, SEEVAL, SmartSensor and The Embedded Control Solutions Company are registered trademarks of Microchip Technology Incorporated in the U.S.A.

Analog-for-the-Digital Age, Application Maestro, dsPICDEM, dsPICDEM.net, dsPICworks, ECAN, ECONOMONITOR, FanSense, FlexROM, fuzzyLAB, In-Circuit Serial Programming, ICSP, ICEPIC, Linear Active Thermistor, Mindi, MiWi, MPASM, MPLIB, MPLINK, MPSIM, PICkit, PICDEM, PICDEM.net, PICLAB, PICtail, PowerCal, PowerInfo, PowerMate, PowerTool, REAL ICE, rfLAB, rfPICDEM, Select Mode, Smart Serial, SmartTel, Total Endurance, UNI/O, WiperLock and ZENA are trademarks of Microchip Technology Incorporated in the U.S.A. and other countries.

SQTP is a service mark of Microchip Technology Incorporated in the U.S.A.

All other trademarks mentioned herein are property of their respective companies.