hand on workshop

Upload: haunghia

Post on 16-Jul-2015

82 views

Category:

Documents


1 download

TRANSCRIPT

Getting Started with the dsPIC30F 16-bit DSCHands-on Workshop

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 1

You are attending a hands-on workshop to get familiar with Microchips new Digital Signal Controller namely the dsPIC30F 16-bit MCU.

dsPIC Hands-on Workshop

GoalsGain knowledge of dsPIC DSC architecture Use MPLAB IDE development environment Learn how to develop code on a dsPIC DSC MPLAB C30 compiler Use Peripherals and C Peripheral Libraries Use DSP FilterLab software Use MPLAB ICD 2 In-Circuit Debugger Debug on dsPICDEM 1.1 Development Board 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 2

After a brief introduction to Microchip and the DSC family of products, we will start our hands-on portion, by getting to know the development tools. After creating a project in MPLAB IDE, we will use the MPLAB C30 C compiler to develop code and then use the MPLAB ICD 2 to program and debug the dsPIC30F6014 chip on the dsPICDEM 1.1 board. We will then learn about DSC peripherals and finally, we will learn how to use a DSP function. During the course of the training, you will use the MLAB ICD debugger and the dsPICDEM 1.1 development board.

Corporate OverviewLeading semiconductor manufacturer:of high-performance, field-programmable, 8-bit & 16-bit RISC microcontrollers of analog & interface products of related memory products for high-volume embedded control applications

$651M in product sales in FY03 More than 3,000 employees Headquartered near Phoenix in Chandler, AZ

The Silicon Desert 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 3

Microchip is the leading 8-bit semiconductor company. It offers high performance field programmable microcontrollers (MCU). Many have built-in analog and digital peripherals. In 1993 Microchip went public. At that time the revenue was $90M, with less than 1000 people. Now Microchip is #1 in volume shipment of 8-bit MCUs. Revenue in FY2003 was $651M and Microchip has over 3000 employees worldwide.

PICmicro MCU Product Migration Path

212 Products

Flash, OTP and ROM Superior Analog functionality Outstanding Flash Endurance Industrys strongest product and family migration path28-Pin Family 40/44-Pin Family

64/68-Pin Family

80/84-Pin Family 8K - 64K Words

4K - 64K Words

8-Pin Family .5K - 2K Words

14-Pin Family

18/20-Pin Family

2K - 16K Words

.5K - 16K Words

.5K - 4K Words

1K - 2K Words

tion gra i sM les m S ea

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 4

Microchip is the leader in 8-bit MCUs. How did this transformation occur? Well the secret lies in the fact that Microchip offers customers a very flexible product line of over 194 products available in Flash, OTP and ROM. Many functions are built-in like analog and digital peripherals. Microchip offers outstanding Flash endurance. Lastly, it has the strongest product and product migration paths in the industry.

80+ Flash PICmicro MCUs!

Best in Industry Program Memory Endurance100,000 Erase/Write Cycles Program Memory 1,000,000 Erase/Write Cycles Data EEPROM

Separate data EEPROM spaceMCU can continue executing code while writing to data EEPROM Store calibration values and serial numbers

In-Circuit Debugging SupportLow cost development tools Develop with the production microcontroller

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 5

Microchip now offers over 80 Flash MCUs. Microchip was the first to introduce field programmable Flash in 1993 with the PIC16C84, which is now called the PIC16F84. So it is no surprise that Microchip is still the leader in this field. In addition, Microchip offers world class endurance for data retention (greater than 40 years) Why customers prefer Flash? Streamlines Complete Product Development: Development MPLAB ICD - Lower cost development tools Develop with the production material Fast erase with no additional hardware (compared to UV erase) Production No Mask ROM charge - Program and run Can be reprogrammed - Less scrap Improved inventory management - use the same device for different applications Flash program memory typical endurance is about 100K Erase/Write(E/W) cycles. Data EEPROM on the other hand, has 1 million E/W cycles. Data EEPROM is typically used to save calibration constants, serial numbers and variables which need to be preserved through a power down cycle. Lastly, Flash offers the developer a easy development tool. Microchip offers the most cost effective and useful development tools in the industry.

Digital Signal ControlPERFORMANCEEmbedded Control + Digital Signal Processing

What is DSC ?

e Th

P DS

ce pa S

32-bit MCU 16-bit MCU 5 - 15 MIPS 8-bit MCU 1 - 10 MIPS

The 16-bit MCU with the power of DSP

dsPIC30F

PRICE 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 6

The dsPIC 30FXXXX devices are 16-bit MCUs with a full DSP engine. As previously discussed, Microchip is widely known for its 8-bit MCU with a maximum through put of 10 MIPS. In many applications faster through put is required in which case 16-bit MCU are a logical choice. Microchip decided that a 16-bit offering would satisfy some customers however a wider application pool could utilize a 16-bit architecture with a built-in DSP engine. This would be specially useful in applications requiring control algorithm to run. The dsPIC DSC meets the high end 16-bit MCU market needs as well as the low end 32-bit market needs. The dsPIC family architecture includes the easy-to-use microcontroller programming and makes this available for more complex DSP functions. Simply put, you dont have to hold a Ph.D. in electrical engineering to use the dsPIC DSC family.

dsPIC30F Looks Like a MCUEasy to use; Built-in Peripherals

Performs Like a DSPPowerful DSP engine

Priced Like a MCUThe 16-bit MCU with the power of DSP

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 7

As mentioned before, the dsPIC device looks like a MCU, performs in the same class as 16- and 32-bit DSPs and best of all is priced like a MCU. All the easy-to-use features of an 8-bit PICmicro MCU have been moved to the dsPIC family plus a very powerful DSP engine. These features include ultra-reliable Flash technology in small 18, 28 and 40 pin packages; easy single cycle and single word instructions. built-in peripherals: ADCs, UARTs, CAN, I2C, SP, PWM etc.; and finally, system level features like programmable brown-out detects, fail safe clock monitors, watchdog timers, etc. All these features make it possible to design a single chip solution for your application at a very affordable price.

dsPIC Family: Architected from Scratch

Seamlessly integrates a DSP and an MCU MCU look and feel, easy to use Competitive DSP performance Optimized for C compiler Fast, deterministic, flexible interrupts Excellent RTOS support

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 8

The dsPIC family offers all the easy-to-use functions of our 8-bit MCU migrated to 16-bit with an integrated DSP engine. The look and feel are very much like our PICmicro architecture, which is well known for its ease of use. Yet, the DSP engine gives a user a high performance machine for the application. The dsPIC instruction set and architecture has been fine tuned and optimized for a C compiler. It has DO and REPEAT instructions as part of the built-in micro code, much like the DO-While ad FOR Loop instructions in a C compiler. Unlike most architectures, the interrupts are fast and fixed, that is, an interrupt will be responded to in 5 and only 5 instructions cycles, no exceptions. In other architectures, depending on which instruction is being executed, an interrupt may respond in 3, 4 N instructions cycles. Also, the dsPIC DSCs have a unique interrupt vector for each interrupt, so there are no extra cycles taken in the interrupt service routine to check which peripheral caused which interrupt, hence faster response to an interrupt. Lastly, the dsPIC has new features in the architecture like interrupt response, software stack etc., which makes it excellent for RTOS based applications.

dsPIC Architecture Definition

Co-Development

Assembler

Simulator

Compiler

Verilog Model

Feedback from Silicon Design Team

Applications

DSP Benchmarks

MCU Benchmarks

Compiler Benchmarks

Co-development of Architecture, Compiler, Applications & Algorithms In-house compiler team Motor control consultants 3rd party compiler vendor RTOS vendors Speech/modem consultants Encryption consultants 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 9

Many of the features talked about on the dsPIC DSC were designed in at the very start of the architectural design phase. The architects sat down with C compiler, RTOS, motor control and other 3rd party designers and consultants. The architects understood the needs and requirements of the applications. Based on those discussions, special hooks and features were added to the dsPIC architecture, thereby making the dsPIC device well suited to meet the application, RTOS and C compiler needs.

C Compiler EfficiencydsPIC30F Processor includes features to enhance C code efficiency New instruction types + More flexible addressing + Software stack = Compact C code32-bit Math intensive Code 16-bit Competition (~ 50 kB code)221% 190% 157% 138% 100%

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 10

The dsPIC30F includes features in the architecture which enhance C code efficiency. With new instruction types, more flexible addressing feature, a software stack, etc the final result is a very compact and efficient C compiler and code generation. In the benchmark analysis done for 32-bit math intensive code, dsPIC30F stood 15% better than the nearest competitor and nearly 121% better than the worst.

Furthest Competitor

115%Nearest Competitor

dsPIC30F

dsPIC30F Families

Power Conversion and Motor Control Family Sensor Processor Family General Purpose Controller Family

dsPIC30F: 16-bit MCU with the power of DSP 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 11

DSCs are offered in three basic family types: Power conversion and Motor Control Family of parts which basically has peripherals like motor control PWMs, high speed ADC, etc. Sensor family of products which has high resolution ADCs, DCI, etc. Finally, the General Purpose Family of products which has high resolution ADCs, CAN, UARTs, etc. Let us look at some of the family offerings.

dsPIC30F ProductsPower Conversion & Motor Control FamilyProduct dsPIC(R) DSC P i n s A/D Output Motor 10-bit Flash SRAM EE Timer Input Comp/ Cntrl 500 KB Bytes Bytes 16-bit Cap Std PWM KSPS PWM U Quad A Enc R T S P I I 2 C ( ( T T M M ) ) 1 1 1 1 1 2 2 1 1 1 1 1 1 1 1 1 2 1 C A N

dsPIC30F2010 dsPIC30F3010 dsPIC30F4012 dsPIC30F3011 dsPIC30F4011 dsPIC30F5015 dsPIC30F6010

28 28 28 40 40 64 80

12 24 48 24 48 66 144

512 1024 2048 1024 2048 2048 8192

1024 1024 1024 1024 1024 1024 4096

3 5 5 5 5 5 5

4 4 4 4 4 4 8

2 2 2 4 4 4 8

6 6 6 6 6 8 8

6 ch 6 ch 6 ch 9 ch 9 ch 16 ch 16 ch

Yes Yes Yes Yes Yes Yes Yes

1 1 1 2 2 1 2

Brushless DC Motor Control AC Induction Motor Control Switch Reluctance Motor Control UPS, Inverters and Power Supplies 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Appliances Power Tools Automotive IndustrialSlide 12

The Power Conversion Family has 7 products from 28 pins to 80 pins and from 12 kB to 144 kB. The key features offered are motor control PWMs and high speed 10-bit ADC. The family can be used for a host of motor control applications used in appliances, automotive and industrial controls.

dsPIC30F ProductsGeneral Purpose Controller FamilyProduct Pins dsPIC(R) DSC Flash KB SRAM Bytes Output EE Timer Input Compare Bytes 16-bit Capture Std PWM A/D 12-bit 100 KSPS U A R T S I P 2 I C ( T M ) C A ( N T M ) Codec Interface

dsPIC30F3014 dsPIC30F4013 dsPIC30F5011 dsPIC30F6011 dsPIC30F6012 dsPIC30F5013 dsPIC30F6013 dsPIC30F6014

40 40 64 64 64 80 80 80

24 48 66 132 144 66 132 144

2048 2048 4096 6144 8192 4096 6144 8192

1024 1024 1024 2048 4096 1024 2048 4096

3 5 5 5 5 5 5 5

2 4 8 8 8 8 8 8

2 4 8 8 8 8 8 8

13 ch 13 ch 16 ch 16 ch 16 ch 16 ch 16 ch 16 ch

2 2 2 2 2 2 2 2

1 1 1 1 2 1 2 1 2 1 2 1 2 1 2 1 1 2 2 2 2 2 2 AC97, I2S AC97, I2S AC97, I2S AC97, I2S AC97, I2S

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 13

The General Purpose Family has 8 products from 40 pins to 80 pins and from 12 kB to 144 kB. The key features offered are high resolution 12-bit ADC, codec Interface.

dsPIC30F ProductsSensor Processor FamilyProduct Pins dsPIC(R) DSC Flash KB SRAM Bytes Output EE Timer Input Compare Bytes 16-bit Capture Std PWM A/D U A R T S I P 2 I C ( T M ) C A ( N T M ) 1 1 1 1

dsPIC30F2011 dsPIC30F3012 dsPIC30F2012 dsPIC30F3013

18 18 28 28

12 24 12 24

1024 2048 1024 2048 1024 1024

3 3 3 3

2 2 2 2

2 2 2 2

12-bit, 8 ch 12-bit, 8 ch 12-bit, 10 ch 12-bit, 10 ch

1 1 1 2

Glass Break Detect Gas Sensor Torque Sensor Tire Pressure Sensor Steering Angle Sensor

Rain Sensor Low power, Smart Sensor Airbag Sensor Processor Pressure Sensors Vibration MeasurementSlide 14

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

The Sensor Family has 4 products from 18 pins to 28 pins and from 12 kB to 24 kB. The key features offered are high resolution 12-bit ADC and small package. The family can be used for a host of sensor applications in smart sensor applications.

Hands-on Labs Learn to use dsPIC30F tools in MPLAB IDECreate a project in MPLAB IDE Compile code with MPLAB C30 Compiler Program dsPIC30F6014 with MPLAB ICD 2 Debug code on dsPICDEM 1.1 Development Board Use dsPIC peripherals - ADC and UART Use dsPIC DSP functions - digital filter

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 15

Lets now get to the hands-on section of this workshop: We will start by getting to know the development tools. After creating a project in MPLAB IDE, we will use the MPLAB C30 compiler to develop code and then use the MPLAB ICD 2 to program and debug the dsPIC30F6014 chip on the dsPICDEM 1.1 development board.

Hands-on Labs Learn to use important features of the dsPIC Digital Signal ControllerI/O Ports Timers Interrupts UART A/D Converter DSP Features

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 16

Once you are familiar with the code development and debugging process, we will move onto code examples to use the various features of the dsPIC family. We will be using the specific features and peripherals shown here. These are important features of the processor and commonly used peripherals. Please consider these labs as a starting point for experimentation and learning. If you finish the labs early, feel free to modify the code to see what happens. Please remember the additional literature you have been given. There are instructions for the labs on the printed sheets we have provided so if you get lost, follow the instructions!

dsPIC DSC Architecture

Main FeaturesSingle Core Integrating an MCU & a DSP Modified Harvard Architecture Data is 16-bit wide Instruction is 24-bit Wide Linear Program Memory up to 12 MB Linear Data (RAM) up to 64 kB True DSP Capability Many Integrated Peripherals 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 17

The dsPIC DSC is a single core integrated MCU with a DSP engine. Just like all PIC MCUs, it is a Harvard architecture which means that there are separate paths for the data and program memory. These separate paths give Harvard architecture devices a faster throughput than conventional Von Neuman architecture devices. The data or RAM path is 16-bit wide while the program memory or Flash ROM or instruction path is 24-bit wide. Again, the different path width is a Harvard architecture advantage over Von Neuman machines (where both paths are 16-bit wide). This allows the majority of instructions in the dsPIC DSC to be single word and single cycle execution. The dsPIC DSC has a linear program memory (up to 12 MB), meaning no paging in the architecture and the data memory is also linear(up to 64 kB), meaning no banking in the RAM access. The DSP engine is fixed point and has two 40-bit multiply/accumulate accumulators along with a barrel shifter and special DSP features like Modulo addressing to maintain circular buffers and bit-reversed addressing for FFT functions, to name a few. As with all PIC microcontrollers, the dsPIC DSCs have a multitude of very useful analog and digital peripherals fully integrated with the MCU.

dsPIC DSC Architecture

Main Features (continued)16 x 16-bit Working Register Array Software Stack Fast, Deterministic Interrupt Response Three Operand Instructions: C = A + B Extensive Addressing Modes

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 18

The working register array has 16 general purpose working registers. In the PIC MCU nuance, these can be viewed as 16 Wregs or W registers. The dsPIC DSC has a software stack and working register number 15 or W15 is initialized as the Top of the stack address in RAM. As mentioned earlier, the interrupts are fast, responding in 5 cycles and each has its own interrupt vector. Three operand, single cycle/word instructions can be executed where, for example, the contents of two 16-bit registers can be added and placed in a third register. Multiple addressing modes are available with preand post-incremented pointer capability. This allows for efficient execution of C code. Finally, a unique feature is available allowing additional 32 kB of data space that can be addressed or mapped from program memory using the Program Space Visibility feature of the dsPIC device. This allows the user to retrieve constants stored in program memory, just as if they were RAM locations.

Programmers Model15 W0 W1 W2 W3 W4 W5 W6 W7 W8 W9 W10 W11 W12 W13 W14 W15 0

DSP OPERAND Registers DSP ADDRESS Registers MAC Prefetch Offset MAC Write Back

W Registers General Purpose Data Registers or Address Pointers

Frame Pointer Stack Pointer

DSP Accumulators (40-bit) Program Counter (23-bit)

ACCA ACCB390

LAC/SAC over X bus LAC/SAC over X bus 32 31

16 150

0

23 22

15 SRLN OV SZ C

0

OA OB SA SB OAB SAB DA DC IPL2 IPL1 IPL0 RA

Status Register

DSP Status

MCU StatusSlide 19

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

The programmers model consists of 16, 16-bit working registers with two 40-bit accumulators. Certain W registers are pre-assigned for DSP and MAC operations, with W15 assigned as the stack pointer and W14 as the frame pointer. These W registers can be used as general purpose working registers when not being used in special DSP or addressing modes. The program counter is 23-bits wide. The Status register contains status bits applicable to the operations of the processor. It is divided into two halves, the upper for DSP status and the lower for MCU status.

Programmers Model 16 x 16-bit Working RegistersMore Flexibility for DSP and MCU Algorithms General Purpose Pointers Stack Manipulation Stack and Frame Pointers W15 is Stack Pointer W14 is Frame Pointer

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 20

With additional working registers, the user has more flexibility in DSP and MCU algorithms. By preloading addresses in the appropriate registers a user can execute complex FFT, FIR and IIR algorithms quickly and efficiently. Stack manipulating using the PUSH and POP instructions can also be executed.

Program Memory - dsPIC30F6014Reset 0x000000

Interrupt Vector Table (0x000004 - 0x00007E)

Interrupt Vector Table Reserved Alternate Vector Table

Executable code starts at 0x100 Program Instructions (0x000100 - 0x017FFE)User Flash Program Memory (~48K Instructions) Reserved Data EEPROM (4 kB)

0x0000FE 0x000100

0x7FF000 0x800000

Configuration Memory Space

Configuration Memory Space 0xFFFFFE

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 21

The program memory is Flash based and is a linear addressed space. The reset vector is at zero; however, executable code starts at hex 100. In between we have two sets of interrupt vector tables. The alternate vector table can be assigned, for example, by the user for debugging purposes during code development. The user space is 20 MB, but the max size on parts available at this time is 144 kB. Note that the Data EEPROM is also mapped in the program memory. The data EEPROM is a high endurance section of the same PEEC Flash Technology used by Microchip. Finally, the configuration space is the second half of the program memory space, and most of that space is not implemented or used for test purposes. The sections which are implemented are the configuration fuse bytes which preconfigure the device during the programming phase.

Data Memory - dsPIC30F6014MS Byte Address 2 kB SFR Space0x0001 0x07FF 0x0801

16-bits MSB LSB

LS Byte Address0x0000 0x07FE 0x0800

SFR Space X Data RAM (X)

8 kB SRAM Space

0x17FF 0x1801 0x1FFF 0x27FF

0x17FE 0x1800

Near Data Access 8 kB

Y Data RAM (Y)

0x1FFE 0x27FE

0x8001

0x8000

Addressable Indirectly or with File Register MOV Instruction

Optionally Mapped into Program Memory Program Space Visibility0xFFFF

X Data RAM Unimplemented (X)

0xFFFE

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 22

The data memory is implemented as a 64 kB block. Please note that there are 32K words each 2 bytes wide. Some important points to note: The first 2 kB of data memory is used for special functions registers. These control the core and peripheral functions. Present dsPIC30F devices have up to 8 kB of on-chip data RAM starting just after the SFR space. The data space is broken into a X and Y section to allow easy access for DSP instructions using pointers. Example: if the user wants to access two RAM locations using indirect addressing, then two pointers can be setup: one for the X space and the other for Y space and data retrieved in one instruction word. The near data space of 8K can be accessed directly using one word instructions. Beyond 8 kB, indirect addressing or MOV instructions must be used. The upper 32 kB can be optionally mapped into program memory and accessed just like data memory. This feature is useful to retrieve constants stored in the Flash program memory. Note that in most devices, the upper 32 kB may not be physically implemented as RAM.

dsPIC DSC Instruction Set Instruction Set Features84 instructions Most are one cycle Most are one word (24 bit) Three operand instructions A = B op CFor compiler efficiency

DSP instructions DO instruction REPEAT instruction 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 23

The dsPIC DSC has 84 unique instructions (not counting the multiple addressing modes). Most are single cycle and take up one word of program memory. Three operand instructions are there to improve instruction efficiency. There are a special set of DSP instructions which optimise the DSP engine. The DO instructions repeats a set of instructions marked by an address label specified in the instruction and repeats these instructions N number of times specified as a value in a W register. REPEAT on the other hand repeats the very next instruction N time specified in a W register value or a literal value. DO and REPEAT instructions significantly improve the efficiency of repetitive code loops.

Addressing Modes Generic Addressing ModesRegister Memory Direct Register Indirect with Signed Offset Literal (Immediate) Register indexed ADD W0,W1,W2 CLR CORCON DEC [++W0],W1 MOV [W0 + #0xC3],W1 SUB #0x1D7,W0 MOV [W0 + W1],W2

Special addressing methods for DSPModulo (Circular Buffer) Bit Reversed (for FFT) 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 24

Some generic addressing modes are discussed here: ADD W0,W1, and W2 instructions add the contents of W0 to the contents of W1 and saves the result in the contents of W2. If an overflow occurred, the CARRY bit will be set. CLR CORCON instructions, loads zeros to the CORCON register. DEC[++W0],W1 instruction, pre-increments the address in W0, then retrieves the value from that pre-incremented address and loads it in W1. MOV[W0+#0xC3],W1 instruction, adds an offset of 0xC3 to the address in W0 and retrieves the contests of that offset address and loads that value in W1. SUB #0x1d7,W0 instruction, subtracts a value of 0x1d7 from the contents of W0 and saves the result back into W0. Note the max value of the immediate value is 10-bits(0x3ff) only. MOV [W0+W1],W2 instruction, creates an address by adding the value in W0 and W1 and retrieves the contents from that address and loads it in W2.

InterruptsStack Operation Prior to ISR Entry

15

0 0x0800

SRL pushed onto stack to preserve IPL and MCU ALU status (except DC)

PC PC SRIPL3

W15 (before interrupt) W15 (after interrupt)0x27FE

IPL3 saved in MS bit of stacked PC value

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 25

This slide graphically shows the stack push operation for an interrupt. Remember, the PC is 23-bits wide, the SRL is 8-bits wide and the RAM space is 16-bits wide. Note that the SRL register contains the IPL status bits so the CPU priority before the interrupt is saved. The user could potentially modify the values saved on the stack to allow the CPU to return to a higher or lower priority at the end of the ISR.

Now A Few Details About Development ToolsEditor, Projects Simulator MPLAB C30 C Compiler 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 26

Editor Text editor, integrated with MPLAB IDE Context sensitive color codingFor assembler and C compiler

Many editor featuresCut, paste, copy, find/replace, match brace, goto line/label/function, bookmarks, indent/outdent block, comment/uncomment block, format upper/lower case, auto indent, word wrap, etc 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 27

MPLAB IDE includes a basic text editor which supports custom color coding by file type. There is also context sensitive color coding for the assembler and C compiler. The editor has many powerful features including cut/paste/copy, find/replace, match brace etc. Some of these will be reviewed in the following slides.

EditorTitle bar with file changed indicator Gutter display

Vertical split-pane control

d de co or ol C

x te

n pa t

e

Horizontal split-pane control

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 28

The main areas of the editor window are the title bar with file change indicator, color-coded text pane, gutter display for line numbers and break indicators and vertical and horizontal pane controls.

Right click menu Execution point Bookmark

Editor

Breakpoint Mouse over 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 29

The green arrow indicates the point where the execution stopped and a blue vertical mark indicates a bookmark, which can be placed anywhere in the code. The user can move from bookmark to bookmark as desired. A red round mark with a B in it indicates the presence where a breakpoint has been set. If the program hits that mark, it stops right after its execution. A mouse over feature allows the user to find the address and contents of a SFR register or bit. When the right mouse button is clicked, the properties box appears. One of the advanced features of this box is to look for matching braces. So if the right mouse is clicked at one brace, the user could easily find out its matching brace. This is useful when writing code in C.

Projects Find in Project FilesFind all occurrences of a string in project source files Double click a result to jump to the line in the source file

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 30

In addition, to the standard Find function, MPLAB IDE now supports Find-inProject Files. Select Project>Find in Project Files... and enter the search text in the dialog box. All occurrences of the string will be show in the output window. Double clicking on a entry will move the focus to that occurrence in the source file.

Simulator Discrete event simulatorOperates on instruction cycle boundary

Multiple breakpoints Stopwatch for time measurement Trace memory to see past execution View and modify variables and registers External stimulus

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 31

The simulator included with MPLAB IDE operates on an instruction cycle boundary, that is resolution of simulated events is an instruction cycle. Program memory and data can be modified and external stimulus can be applied to I/O pins. Some important features of the Simulator: Stopwatch function allows user to easily calculate execution time of functions and subroutines in a program Trace memory allows user to view past variable values and help debug programs External stimulus file can be generated to simulate external signal conditions Certain peripherals are not completely simulated: for example, the A/D conversion cycle is simulated, but an analog source on the input pin is not.

MPLAB C30 C Compiler

GNU based Comes with assembler, linker and librarian ANSI C compliant with standard libraries Optimized for dsPIC architectural features16-bit native data type Uses 3-operand instructions Complex addressing modes Efficient multi-bit shift operations Efficient signed/unsigned comparisons 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 32

The C compiler is GNU based and comes with an assembler, linker and librarian. The compiler is ANSI C compliant and has standard libraries. We will explore the use of these libraries in later exercises. The code generated is optimized and uses some of the architectural features for the optimization, including 16-bit data type, complex addressing schemes, 3 operand instructions, efficient multi-bit shift operations. (Example: shift right 4 times) and signed/unsigned comparisons.

MPLAB C30 C Compiler

Compiler, Assembler, Linker and LibrarianSource Files .C .SCompiler

Object Files .O LinkerAssembler Archive (Librarian)

Output Files .HEX

.O .A .GLD

.COF

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 33

The compiler, compiles the source code written either in C or assembly. This, in turn, is converted to the appropriate object code. At this point, users can link object files or archive files using the linker and the linker header file (*.gld) to create an executable hex file which can be programmed into a Flash device and made to run or code the object file (*.cof) to run with the debugger.

MPLAB C30 C Compiler

LibrariesMath - sin(), log(), sqrt(), etc. Peripheral Driver - ADC, PWM, UART, etc. DSP Algorithm - IIR filter, Convolution, etc. TCP/IP and Soft Modem Speech recognition Noise and Echo Cancellation Encryption RTOS compatible - CMX, OSEK 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 34

As mentioned before, the C compiler comes with a bundle of very useful libraries: Math, peripherals drivers and, DSP algorithms. There are also applicationspecific libraries available which include: TCP/IP, soft modem, speech recognition, noise and echo cancellations, encryption and RTOSs.

Lab 1Learn to Use dsPIC30F Tools in MPLAB Integrated Development Environment

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 35

Lab 1 dsPIC30F Tools we will use in the lab:MPLAB IDE v6.XX MPLAB C30 C Compiler MPLAB LINK30 linker MPLAB ICD 2 In-Circuit Debugger

Literature that will help you:Quick Reference Card

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 36

In this first lab, we will use the latest MPLAB IDE version 6.XX. This XX will be constantly changing since we introduce new versions on a monthly if not more often basis. This is done to cover new parts introduced by Microchip. Please get the latest version of MPLAB free from www.microchip.com. We will also use the C30 C compiler, the LINK30 linker and the debugger called MPLAB ICD 2. To help you we have a quick reference card provided.

Lab 1 Learn to use dsPIC30F tools in MPLAB IDE Four stepsStep 1 - Create a project in MPLAB IDE Step 2 - Compile code with MPLAB C30 C Compiler Step 3 - Program dsPIC30f6014 using MPLAB ICD 2 Step 4 - Run/Debug code on dsPICDEM 1.1 Demonstration Board 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 37

In lab 1 we will create a project, with a pre-exiting project, we will then compile the code using the C30 compiler and Lastly, we will program the dsPIC30F6014 device on the dsPICDEM 1.1 Development Board using MPLAB ICD 2. We will then run the code and execute some of the debugging features of the MPLAB ICD 2.

Lab 1Start MPLAB IDE

Tool Bar Project View

Menu Bar

Output View Status Bar 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 38

You will find a MPLAB IDE icon on your computer, double click it to start MPLAB. Note the following: Two windows open 1. Project Window and 2. Output Window. The tool bar shows icons for various tools selected, the menu bar is right at the top and the status bar at the bottom tell you what devices has been selected. Please note that at the start, this window may differ from what you see on your computer.

Lab 1Click Project Menu Select Project Wizard

Project Wizard screen opens Click Next 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 39

We will now create a project in the MPLAB IDE: Select Project from the menu and select Project Wizard. On the Welcome screen, click Next.

Lab 1Select dsPIC30F6014 Click Next

Select Microchip C30 Toolsuite Click Next 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 40

From the device list select dsPIC30F6014 and then click Next. Select Microchip C30 Toolsuite and then click Next.

Lab 1Type Lab 1 for Project Name Click Browse

Navigate to C:\WIB1.1\Lab1 Click Select 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 41

Type Lab 1 in the Project Name and click Browse, navigate to the C:\WIB1.1\Lab1 directory and click Select.

Lab 1Click Next

Select Lab1 Flash LED with timer delay.c Click Add Click Next 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 42

Click Next and then from the Step Four window, select the Lab1 Flash LED with Timer delay.c file. Click Add, and then click Next.

Lab 1Summary Screen Appears Click Finish

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 43

The summary screen informs you about the device selected, the Toolsuite selected and finally, the project file where the project will be created. If all looks well then click Finish.

Lab 1Project Window Now Shows the Lab 1 Project

Right Click Linker Scripts and Select Add Files 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 44

The project window now shows the source file selected. In order for the file to be compiled and linked, the linker script file needs to be identified. This file basically is the location where all the definitions related to the linker are declared: for example, the locations of the interrupt vector, the amount of RAM, Flash and EEPROM, etc. If a right click is done on the Linker Script section, and Add Files is selected, then the user can add the linker script file.

Lab 1

Go to C:\PIC30_Tools\support\gld Select p30f6014.gld and Click Open 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 45

If during installation, the user selected the default setting (which is recommended), then the linker script file will be located in the C:\PIC30_Tools\support\gld directory. In any case, look for the *.gld files in the appropriate directory on your computer and select the p30f6014.gld file. Click Open.

Lab 1Project Window Now Shows the Linker Script File

Double Click a File to View and Edit the File 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 46

The Linker Script file now shows the right linker file for the device selected. If any file needs to be edited or viewed, then double clicking of the file name will open a window and the user can edit the file as needed.

Step 2Compile and Link the Project

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 47

Lab 1 Before We Compile and LinkTell compiler where to find header file #include Tell linker to reserve memory for the MPLAB ICD 2

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 48

Before we link and compile, you will notice that a file has been referred to in the main program, namely the header file called p30f6014.h. This header file defines the exact address and location of the SFRs, PORTs etc. The header file is useful because the user can now name the PORT and SFR definitions and syntax as seen in the data sheet and the linker will automatically compile and link the right address pertaining to the syntax used. So we need to indicate to the compiler the location of the header file. If we are using the MPLAB ICD 2 to do debugging, then we also need to reserve some memory for the debug code which resides in the part.

Lab 1Click Project Menu Select Build Options and Project

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 49

Click on the Project Menu and select the Build Options and finally, Project.

Lab 1Find Include Path Click Browse

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 50

A build option for the project window opens up, which will normally show a blank for the Include Path. Click the Browse button to search for the Include Path.

Lab 1Go to C:\PIC30_Tools\support\h Click Select

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 51

Again, if the tools were installed using the default setting (which is recommended), then the header files should be located at C:\PIC30_Tools\support\h. Go to that directory and click Select. If you have selected some other locations for your header file, please indicate that path here.

Lab 1Include Path Now Points to Header Files

Click MPLAB LINK30 Tab Select Link for ICD2 and Click OK 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 52

If the default include path was selected, the include path would be as above C:\PIC30_tools\support\h\. Next click on the MPLAB LINK30 tab and select the Link for ICD2 and click OK. This will indicate to the linker that the MPLAB ICD 2 is being used for debugging and hence space will be reserved for the debug executive code.

Lab 1Click Project Menu Select Make

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 53

Now that everything has been set so, let us build or make the project. Click the Project menu and select Make. You can also hit the F10 key to do this.

Lab 1Build Results are Shown in Output Window

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 54

A output window will open and the make process outputs will be displayed. If any errors occur during the make process those will be indicated in this window. The user can then double click on the Error line and MPLAB IDE will directly take the user to the place where the compiler or linker encountered the error. In the case of Lab 1, the project is already debugged so no errors should occur and the Build Succeeded indicator should be shown at the bottom the output window.

Step 3Use the MPLAB ICD 2 to Program and Run the Code

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 55

Lab 1 HardwareMPLAB ICD 2 dsPICDEM 1.1 Development Board

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 56

In order to program the part on the dsPICDEM 1.1 Development Board, the user needs to use the MPLAB ICD 2 programmer/debugger connected to the dsPICDEM 1.1 Development Board. Please connect the MPLAB ICD 2 to the PC using the USB cable and connect the 6-pin RJ-11 phone plug from the MPLAB ICD 2 to the phone connector on the dsPICDEM 1.1 Development Board. Power the dsPICDEM 1.1 board with the supply provided (9VDC 1.0 Amp).

dsPICDEM 1.1 Development Board 1.1RS-485 UARTs (2) +9Vdc In ICD 2 CAN dsPIC Clock dsPIC XTAL Plug-In Module Header +5V Reg. CODEC

Temp SensorLCD

CODEC MIC In/ Spkr Out Switches (4) LEDs (4) POTs (3)Slide 57

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

The dsPICDEM 1.1 Development Board is a very useful tool for applications development. The section which will be used in the labs are: The Switches SW1 to SW4 The LEDs, LED1 to LED4 The 3 potentiometer RP1 to RP3 The RJ11 ICD plug in connector to connect to the MPLAB ICD 2 debugger The LCD display which is a dot matrix LCD

Lab 1 Set up the HardwareConnect power the to dsPICDEM 1.1 Development Board. Connect USB cable from PC to MPLAB ICD 2 Connect cable from MPLAB ICD 2 to dsPICDEM 1.1 Development Board

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 58

Please connect power to the dsPICDEM 1.1 board. Please connect the MPLAB ICD 2 to the PC using the USB cable and connect the 6-pin RJ-11 phone plug from the MPLAB ICD 2 to the phone connector on the dsPICDEM 1.1 board.

Lab 1Click Debugger Menu Choose Select Tool and MPLAB ICD 2

Click Debugger menu Choose Connect 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 59

Once the hardware connections are done, click Debugger on the menu bar, click on Select Tools and click on MPLAB ICD 2. If the MPLAB ICD 2 is already selected, then click on Debugger on the menu bar and click on Connect. This will connect the MPLAB ICD 2 to the MPLAB software.

Lab 1 Operating System DownloadMPLAB ICD 2 may ask to download a new operating system Click Yes

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 60

If in case the firmware on the MPLAB ICD 2 is an older version, a warning window will tell you that a new firmware is available. If this is the case, please click Yes and download the latest firmware for the MPLAB ICD 2. This will ensure that you are using the latest and the greatest firmware algorithms for the silicon. This window will not appear if you have the latest updates to the software and firmware.

Lab 1 Output WindowMPLAB ICD 2 connected to the target device Identified it as a dsPIC30F6014

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 61

Once the hardware is connected, the output window will indicate the status of the connection and indicate that the MPLAB ICD 2 is ready for operation. If an error occurred during the connection, that will be indicated. The best way to solve any error problem is to make sure all the connections are correctly made and retry the connection following the process mentioned in the previous slides. Hardware Steps to check in case of error: Power to dsPICDEM 1.1 Development Board (power LED should light) -> USB connection from ICD 2 to PC -> RJ-11 connector from ICD 2 to the dsPICDEM 1.1 Development Board. Hardware check if problems occur: 1. Check if the device selected on MPLAB ICD is dsPIC30f6014. 2. Check if power on dsPICDEM 1.1 Development Board is on -> POWER LED should be ON 3. ICD 2 is properly connected to PC through the USB cable 4. ICD 2 is properly connected to dsPICDEM 1.1 Development Board through the RJ-11 connector.

Lab 1Click Debugger Menu Choose Program

Output window 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 62

If the connection is successful, we are ready to program the part. Click on Debugger on the menu bar, choose Program. The output window will open and the steps during the programming stage will be displayed. If all the steps are successful, the message on the bottom will indicate that the programming succeeded and the MPLAB ICD 2 is ready for the next operation.

Lab 1Click Debugger Menu Choose Run

LED1 flashes at a 1 Hz rate. 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 63

Once the part programmed successfully, click on Debugger on the menu bar and click on Run. The program should run and LED1 should blink at a constant rate of 1 Hz.

Step 4Use the MPLAB ICD 2 debugging features

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 64

We will now go through some of the debugging features of the MPLAB ICD 2.

Lab 1Click View Menu Choose Program Memory

Press F5 to Halt Press F6 to Reset Green Arrow Shows Code at Reset Vector 0x00000 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 65

In order to view the program memory, click on View on the menu bar then click on Program Memory. A program memory window will appear which shows a green arrow at the reset vector of 0x00000, where a goto_reset instruction resides. Hit the F5 key to halt the program execution, hit the F6 key to reset the program.

Lab 1Press F7 to Single Step Green Arrow Points to Code at _reset

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 66

The F7 key single steps through the program. Hit F7 once and the program goes to the _reset location. Notice that this is at address hex one hundred. The code at the beginning of the reset location is the startup code inserted by the C compiler. Notice it initializes the stack and calls other initialization routines before the first call to main is done.

Lab 1 MPLAB ICD 2 Function KeysF5 - Halt F6 - Reset F7 - Single Step F9 - Run

Right ClickSet Breakpoint Run to cursor

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 67

Keys for program execution: F5 halts program execution F6 resets the program F7 single steps through the program F9 runs the program Try these out and see if they work on your program To set a breakpoint, you have to first stop execution by pressing the F5 key, then go to the location in the program memory window to see where you would like to set a breakpoint. Click the mouse left key at that location to set the cursor and then right click at that point. A menu appears which allows the user to Set a breakpoint, Run to Cursor etc. Let us explore these possibilities.

Lab 1Right Click LATD = 0xFFFF; and Choose Run to Cursor Green Arrow Points to Next Line, TRISD = 0xFFF0;

Run to Cursor Executes Line Under Cursor 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 68

From the project window, double click on the file. A window showing the code in that file will open. Move up and down in that file until you reach the code depicted in the slide. Click on the LATD = 0xFFFF; line and using the right click of the mouse, select Run to Cursor. You will notice that the green arrow points to the next line which is TRISD = 0xFFF0;. This is because the instruction LATD = 0xFFFF executes and stops at the very next instruction after that.

Lab 1Find Line if(IFS0bits.T1IF == 1) Right Click and Choose Set Breakpoint

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 69

Next let us explore how to use a breakpoint. Search the file for the line if(IFS0bits.T1IF == 1);. Select that line and right click the mouse and choose Set Breakpoint. A red breakpoint indicator will appear in the left gutter of the line.

Lab 1Press F9 to Run Green Arrow Points to Breakpoint Line

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 70

Hit the F9 key to run the program and after a short delay (of about 1 second), the program will stop and the green arrow will overlap with the red dot. Please note that the if statement in C is a complex set of assembly instructions. The program is probably stopped at some instruction right after the first one in that statement, so it is still in the process of executing that complex C statement.

Lab 1Press F7 to Single Step Green Arrow Points to if(PORTA bits.RA12 == 0)

Note Several Steps in Output Window 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 71

Press F7 to single step and you will notice that the green arrow points to if(PORTCbits.RC13 == 0), which is the next logical statement in the code. Note several steps have occurred in the output window to indicate that this C statement had several assembly level instructions in its execution.

Lab 1Click View Menu Choose Watch

Select PORTA from the Add SFR Field Click Add SFR 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 72

Now let us explore how to View and Watch variables. Click View on the Menu bar and click Watch A window will open with Add SFR and Add Symbol scroll down screens. In order to select a desired SFR to view, use the down arrow in the Add SFR menu and select it. In this case let us view PORTA, so please scroll down and select PORTA and click the Add SFR button.

Lab 1Hold Down Switch SW1 or SW2 and Press F9 PORTA Value Changes Depending on SW1 and SW2 Being Pressed

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 73

The watch window will now show PORTC value displayed as above. To see how the PORTA value changes in the watch window, hold down SW1 or SW2 and hit F9. Remember that the breakpoint is still set in the last exercise, so the program will stop every time it hits the breakpoint, and at that time, the watch window will be updated and the value of the key hit will be displayed.

dsPIC Device Interrupt Handling

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 74

Interrupt Controller Interrupts OverviewInterrupt Vector Table (IVT) Vector location contains ISR address Unique vector for each interrupt source 8 non-maskable error trap vectors 54 interrupt vectors 7 user assigned priority levels for each source Consistent 5-cycle latency for all instructions 3-cycle return from interrupt 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 75

The dsPIC30F has a unique interrupt vector for each source of interrupt. These are true vectors -- each vector is programmed with the address of the ISR. There can be up to 8 non-maskable trap vectors for critical hardware problems, such as an oscillator failure, math errors, etc.. The dsPIC DSC presently has 5 trap sources implemented. The IVT supports up to 54 sources of interrupt. The dsPIC DSC presently has 45 vectors implemented. There are 8 user assigned levels of interrupt priority, 0 through 7. 0 is low and 7 is high. Traps have priority over all other interrupts. A trap can be viewed as a level 8 priority interrupt. There is an Alternate IVT (AIVT) that can be enabled. The AIVT can be loaded with a different set of ISR addresses than the IVT. The AIVT is useful for diagnostic modes, etc. By using a different ISR, a peripheral can be used differently for the alternate mode. For example, you might want to program the UART to upload test data to a PC when testing an application. The interrupt response time is deterministic and fixed at a 5 cycle latency for all instructions. This is a very unique feature when compared to other architectures. Users can be assured that an interrupt will be responded to in a fixed duration of time. The return latency is 3 cycles.

Interrupt Vector TableReset - GOTO Instr. Reset - GOTO Instr. Reserved Oscillator Fail Trap Address Error Trap Stack Error Trap Arithmetic Error Trap Reserved Reserved Reserved Interrupt Vector 0 Interrupt Vector 1 Interrupt Vector 2 Interrupt Vector 53 Reserved Reserved Reserved Oscillator Fail Trap Address Error Trap Interrupt Vector 53 0x000000

Interrupt Vector Table

Decreasing Natural Order Priority

0x00007E

Alternate Interrupt Vector Table

0x0000FE

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 76

This slide shows a memory map of the IVT and AIVT. Each vector location is programmed with the 24-bit address of an ISR. Interrupt and trap vectors with a higher address have lower natural priority. Note that the Reset vector consumes two locations. The Reset vector is loaded with a GOTO instruction that jumps to the startup code. The Reset vector location is not a true vector because resets are not handled by the interrupt controller.

Interrupt Controller Interrupt Priority LevelsCPU has 16 priority levels Level 0 - 7 for normal peripheral interrupts Can be assigned by user Level 8 - 15 reserved non-maskable traps Oscillator failure, stack error, etc. Fixed priority cannot be disabled

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 77

There are 8 user-assigned priority levels for each source of interrupt. The SRL has status bits that indicate the present CPU priority. If a pending interrupt is greater in priority than the current CPU priority, the interrupt will take place. During the interrupt, the SRL is pushed on the stack to save the old priority level and the IPL bits are changed to the priority of the current interrupt task. Conflicting interrupt sources with the same user programmed priority level will be resolved by their natural order priority in the IVT. The position of each interrupt source in the IVT determines its natural order priority. A low order priority in the IVT can be overcome by assigning the interrupt a high user priority via the IPC (interrupt priority control) bits for that source.

Interrupt Controller CPU has some priority level at all timesStarts at zero after Reset IPL in Status Register - SR IPL3 in Core Control Register - CORCON

Higher priority interrupt can interrupt CPUCPU then assumes new priority Saves old priority on the stack

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 78

It is important to note that the CPU has some priority level at all times. This is quite different than other PIC microcontrollers. It starts at zero at Reset. The CPU priority level is located in the Status Register bits IPL. The IPL bit is located in the CORCON register. The CPU can be interrupt by a higher level priority and then assumes that priority. The old priority is saved on the stack.

Interrupt Controller Interrupt Priority Level set by IPCx registersInterrupt sources can be levels 0 - 7 A level 0 source is effectively disabled Default interrupt priority is 4

Can change CPU priority by writing IPLIPL3 is read only - cant disable traps IPL = 111 disables all other interrupts

DISI instruction disables level 1 - 6 interrupts 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 79

There are 8 user-assigned priority levels for each source of interrupt. The SRL has status bits that indicate the present CPU priority. If a pending interrupt is greater in priority than the current CPU priority, the interrupt will take place. By default, the CPU priority is 0 and all user priorities are kept at 4. During the interrupt, the SRL is pushed on the stack to save the old priority level and the IPL bits are changed to the priority of the current interrupt task. Conflicting interrupt sources with the same user programmed priority level will be resolved by their natural order priority in the IVT. The position of each interrupt source in the IVT determines its natural order priority. A low order priority in the IVT can be overcome by assigning the interrupt a high user priority via the IPC (interrupt priority control) bits for that source. To disable all user interrupts, the CPU priority can be set to 111 that is the IPL = 111. This would not allow any user interrupts to occur. Traps and non maskable interrupts could still occur. Note that IPL3 bit is read only, so traps cannot be disabled. There is also a DISI instruction which disabled interrupts between 1 - 6. This allows the CPU to still run since by default the CPU interrupt is 0. Also priority level 7 or higher interrupt still can interrupt the DISI instruction.

Interrupt Controller Interrupt Context SavingOnly SRL and PC are saved by hardware Saved on stack Compiler saves additional context data User can specify other data to save

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 80

The SRL register and the PC are saved automatically. This preserves the MCU status bits (except DC), the old CPU priority and the Repeat Active (RA) Status bit. Any other registers can be saved using PUSH instructions to place them on the software stack. The PUSH.S and POP.S instructions can be used to save the W0 W3 into shadow registers in one cycle. They also save the PSVPAG, TBLPAG, MCU status bits and RA Status bit. The shadow registers are only one level deep, so there are restrictions. Basically, the CPU cannot be interrupted by any other process that uses the shadow registers or the contents will be destroyed.

Interrupt Controller Stack OperationIPL bits15 0

0x801 0x803

0x800 0x802

IPL3 bit

Stack Grows Towards Higher Address

PC[15:0] SR[7:0] PC[22:16]

W15 (before interrupt) W15 (after interrupt)

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 81

This slide graphically shows the stack push operation for an interrupt. Note that the SRL register contains the IPL status bits so the CPU priority before the interrupt is saved. The user could potentially modify the values saved on the stack to allow the CPU to return to a higher or lower priority at the end of the ISR.

Interrupt Controller C30 Interrupt Attributes__attribute__ allows interrupt attributes list void __attribute__((interrupt)) _INT1Interrupt(void) ...((interrupt(save(Var1,Var2)))) _INT1Interrupt(void) ...((interrupt(save(Var1),irq(15)))) MyIRQ(void) _ISR is defined in header files void _ISR _INT1Interrupt(void)

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 82

The software has to declare the interrupt vector in order for the compiler and linker to create the correct jump to the location during a ISR. The interrupt attribute can be declared for a particular function to make it an interrupt function. There are standard names for the interrupt routines which are recognized by the linker. Certain attributes can also be associated with an interrupt routine, for example in the statement: void __attribute__((interrupt(save(Var1,Var2))))_INT1Interrupt(void), the variables Var1 and Var2 will be saved on the stack during the INT1 Interrupt. Alternatively the user may choose to save Var1 and Var2 on the stack by using the PUSH and POP instructions in the ISR itself.

Interrupt Controller Interrupt NestingInterrupts nested by default Disable nesting by setting NSTDIS bit INTCON1 CPU priority forced to level 7 during all interrupts when NSTDIS = 1

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 83

ISR can be interrupted by higher interrupts so nesting of interrupts is supported by default. In order to disable nesting, set the NSTDIS bit in the INTCON1 register. When this is done, the CPU priority is forced to 7 during all interrupts.

Lab 2Using Interrupts

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 84

Lab 2 Light LED3 and LED4 using INT1 and INT2 InterruptLearn about interrupts

Use Lab 2 Workspace ProvidedAdd six lines as indicated by comments

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 85

In this lab we will learn how to set up an interrupt, in this case, a INT1 and INT2 interrupt

Lab 2 INT1 and INT2 Interrupt RegistersIFS1 - Interrupt Flag Status INT1IF bit and INT2IF bit IEC1 - Interrupt Enable Control INT1IE bit and INT2IE bit

Interrupt Vector TableUse labels defined in Linker Script file Listed in C30 Compiler Users Guide

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 86

In order to enable an interrupt, the user has to set the interrupt enable control bit: in this case the INTxIE bits. When an interrupt occurs, the interrupt status flag(IFS bit) is set and the ISR occurs. In the ISR, the user has to clear the IFS bit, in this case the INTxIF bit. The bit syntax and naming is well documented in the data sheets and the dsPIC Family Reference Manual. Another location to view the syntax is the device header file. For example p30f6014.h is the header file for the 84-pin dsPIC device used in the dsPICDEM 1.1 Development Board.

Lab 2 Linker Script file - Note label __INT1Interrupt

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 87

The linker script file defines the syntax for the Interrupt Service Routine Call. Note the double (two) underscore before the INTxInterrupt, ( __ ).

Lab 2 Operation of Lab 2LED1 flashes in background in main() Turn on/off LED3 when switch SW1 is pressed Turn on/off LED4 when switch SW2 is pressed

Tasks for Lab 2Enable INTx interrupts Create a INTx interrupt function Clear interrupt flag to allow a new interrupt

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 88

Lab 2 C:\WIB1.1\Lab2\Lab 2.mcw Workspace Code to be Added is Clearly Marked!

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 89

Please use the already created workspaces in C:\wib1.1\lab2\lab2.mcw. The easiest way is to close the existing workspace under File->close workspace. Then open a new workspace by selecting File->open workspace and choosing C:\wib1.1\lab2\lab2.mcw. Scroll down to the light blue section where clearly marked labels indicate where code needs to be added:

Lab 2 Solution:Line 46: Line 47: Line 67: Line 78: Line 69: Line 80: IEC1bits.INT1IE = 1; IEC1bits.INT2IE = 1; void _ISR _INT1Interrupt(void) void _ISR _INT2Interrupt(void) IFS1bits.INT1IF = 0; IFS1bits.INT2IF = 0;Slide 90

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Lab 3Using Interrupt Priorities

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 91

Lab 3 Set Timer Interrupts to Different Priorities Change CPU Priority in CodeLearn about interrupt priorities and interaction

Use Lab 3 Workspace ProvidedAdd five lines as indicated by comments

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 92

In this lab, we will explore the interrupt priority scheme of the dsPIC device. We will learn the interaction between high and low interrupt.

Lab 3 Operation of Lab 3Set CPU priority to level 4 (in code) Timer1 level 3 interrupts every 1/10 second Light LED1 for 1/10 second in ISR Timer2 level 5 interrupts every one second Light LED2 for one second in ISR Notice that Timer1 interrupt to light LED1 never happens Timer1 level 3 is less than CPU level 4 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 93

At first the CPU priority will be set to 4. Timer1 priority will be set to level 3, which is setup to occur every 1/10 second. Timer2 priority is set to level 5 and is setup to occur every second. What we notice from the setup is that the Timer1 ISR will never occur, since its priority of 3 is lower than the CPU priority of 4.

Lab 3 Operation of Lab 3 Continued...Detect when SW1 is pressed in main loop Set CPU priority to level 6 and LED4 on Detect when SW1 is released in main loop Set CPU priority to level 2 and LED4 off Notice that no timer interrupts occur while switch is pressed Notice that both timer interrupts occur after switch is released 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 94

Next what we will do is change the priority when SW1 is pressed. When SW1 is pressed we will set the CPU priority to 6, which is top priority in this program, so neither Timer1 nor Timer2 should interrupt it. Finally, when SW1 is released, the CPU priority is set to 2, so now it has the lowest priority and can be interrupted by Timer1 and Timer2.

Lab 3A Picture is Worth a Thousand Words!

Event 7 6 5 4 3 2 1 0 CPU Priority Level

ResetSlide 95

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

This is an interactive slide so read each slide note: On reset, the CPU priority is set to 0.

Lab 3Initialize CPU, Timer1 and Timer2 Priority Level

Event 7 6 5 4 3 2 1 0

Pending

Timer2 Initialized Timer1

LED2 LED1

ResetSlide 96

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

In the initialization, the CPU priority is set to 4, Timer1 to Timer3 and Timer2 to Timer5. So the Timer1 interrupt will never be serviced since its priority is lower than the CPU.

Lab 3Timer2 Interrupt Occurs

Event 7 6 5 4 3 2 1 0

Pending

Timer2 Initialized Timer1

LED2 LED1

ResetSlide 97

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

However when Timer2 interrupt occurs every second, the ISR will be executed and LED2 will light up. LED 1 will still be off.

Lab 3Timer2 Interrupt Returns

Event 7 6 5 4 3 2 1 0

Pending

Timer2 Initialized Timer1

LED2 LED1

ResetSlide 98

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Lab 3Timer2 Interrupt Occurs

Event 7 6 5 4 3 2 1 0

Pending

Timer2 Initialized Timer1

LED2 LED1

ResetSlide 99

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Lab 3Timer2 Interrupt Returns

Event 7 6 5 4 3 2 1 0

Pending

Timer2 Initialized Timer1

LED2 LED1

ResetSlide 100

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Lab 3Code Changes CPU Priority When S1 Pressed

Event 7 6 S1 pressed Timer2 5 4 Initialized Timer1 3 2 1 Reset 0 LED4 LED2 LED1 SW1

Pending Pending

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 101

When SW1 is pressed, CPU priority is set to 6, so neither a Timer2 or Timer1 are serviced. So if LED2 is on, it will continue to stay on or if LED2 is off then it will continue to stay off.

Lab 3Code Changes CPU Priority When S1 Released

Event 7 6 S1 pressed Timer2 5 4 Initialized Timer1 3 2 S1 released 1 Reset 0 LED4 LED2 LED1 SW1

Pending Pending

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 102

When SW1 is released, CPU priority is now set to 2, so both Timer1 and Timer2 will be serviced.

Lab 3Pending Timer2 Interrupt is Handled

Event 7 6 S1 pressed Timer2 5 4 Initialized Timer1 3 2 S1 released 1 Reset 0 LED4 LED2 LED1 SW1

Pending

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 103

Lab 3Pending Timer1 Interrupt is Handled

Event 7 6 S1 pressed Timer2 5 4 Initialized Timer1 3 2 S1 released 1 Reset 0 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

LED4 LED2 LED1 SW1

Slide 104

Lab 3Return from Timer1 Interrupt

Event 7 6 S1 pressed Timer2 5 4 Initialized Timer1 3 2 S1 released 1 Reset 0 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

LED4 LED2 LED1 SW1

Slide 105

Lab 3Timer1 Interrupt Occurs

Event 7 6 S1 pressed Timer2 5 4 Initialized Timer1 3 2 S1 released 1 Reset 0 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

LED4 LED2 LED1 SW1

Slide 106

Lab 3Return from Timer1 Interrupt

Event 7 6 S1 pressed Timer2 5 4 Initialized Timer1 3 2 S1 released 1 Reset 0 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

LED4 LED2 LED1 SW1

Slide 107

Lab 3Timer2 Interrupt Occurs

Event 7 6 S1 pressed Timer2 5 4 Initialized Timer1 3 2 S1 released 1 Reset 0 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

LED4 LED2 LED1 SW1

Slide 108

Lab 3Return from Timer2 Interrupt

Event 7 6 S1 pressed Timer2 5 4 Initialized Timer1 3 2 S1 released 1 Reset 0 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

LED4 LED2 LED1 SW1

Slide 109

Lab 3Timer1 Interrupt Occurs

Event 7 6 S1 pressed Timer2 5 4 Initialized Timer1 3 2 S1 released 1 Reset 0 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

LED4 LED2 LED1 SW1

Slide 110

Lab 3Timer2 Interrupt Occurs

Event 7 6 S1 pressed Timer2 5 4 Initialized Timer1 3 2 S1 released 1 Reset 0 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

LED4 LED2 LED1 SW1

Slide 111

Lab 3Return from Timer2 Interrupt

Event 7 6 S1 pressed Timer2 5 4 Initialized Timer1 3 2 S1 released 1 Reset 0 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

LED4 LED2 LED1 SW1

Slide 112

Lab 3Return from Timer1 Interrupt

Event 7 LED4 6 S1 pressed LED2 Timer2 5 4 Initialized LED1 Timer1 3 SW1 2 S1 released 1 Reset 0 One click too many! 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 113

Lab 3 Tasks for Lab 3Set CPU priority to level 4 Set Timer1 interrupt priority to level 3 Set Timer2 interrupt priority to level 5 Wait until switch SW1 pressed Wait in Timer1 ISR until next Timer1 interrupt

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 114

Lab 3 C:\WIB1.1\Lab3\Lab 3.mcw Workspace Code to be Added is Clearly Marked!

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 115

Use Lab 3 workspace already created in C:\wib1.1\lab3\lab3.mcw.

Lab 3 A SolutionLine 38: Line 51: Line 66: Line 73: Line 98: SRbits.IPL = 4; IPC0bits.T1IP = 3; IPC1bits.T2IP = 5; while(!SW1); while(IFS0bits.T1IF == 0);Slide 116

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Lab 4: Peripheral Overview

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 117

dsPIC30F Peripherals

MCU / DSP CORE16-bit ALU 16 x 16 MAC Dual 40-bit ACC

Real Time Clock 16 / 32 bit Timers Timer2 / Timer3 16 / 32 bit Timers Timer4 / Timer5

Timer1

Output Compare Standard PWM(8 ch / 16-bit)

Packages I/O PORTS CAN 218 SDIP 20 SSOP 28 SDIP 28 SSOP 40 DIP 44 TQFP 64 TQFP

Input Capture(8 ch / 16-bit)

Program Memory Flash144 kB

Data Memory SRAM8 kB

ADC 12-bit 100 KSPS ADC 10-bit 500 KSPS

Motor Control PWM

16-bit, 6-8 chQuadrature Encoder

(Timer6)

UART 1

UART 2

SPI 1

4 kB

AC97, I2S

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

CAN 1

I2C

Data Memory EEPROM

SPI 2

CODEC interface

80 TQFP

Slide 118

The dsPIC device has a host of built-in peripherals to make it truly a single chip solution for design applications. Some of the key new peripherals are: High speed ADC: 10-bit 500 Kilo samples per second (kps) or 12-bit 100 kps with 16 deep buffers and automatic conversion setups. Details to follow. Motor Control PWM: These PWM are available as 4 complementary pairs or 8 independent PWMs with centered or edge aligned PWMs. Quadrature Encoder: with inputs QA, QB and index. The output is a 16-bit value marking the position of the rotor in a Motor control application. CODEC interface with AC97 and I2S support. Details to follow. The other existing peripherals are enhanced to give advanced and faster performance. For example the UART has a 4 deep buffer for Rx and Tx. The I2C has full multi-master support. The SPI has a 8- and 16-bit interface. Some devices also have two instances of the same peripheral. Now we will briefly touch upon some of the peripherals and their features.

Timers/Counters OverviewFive 16-bit General Purpose Timers / CountersSimilar functionality between all 5 timers

Period Registers for EachInterrupt generation on match Reset on match

Gated Timer Operation on EachInterrupt-on-falling edge of gate

Four of These Timers can Make a 32-bit Timer/Counter

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 119

The dsPIC devices have up to five 16-bit general purpose timers. Key features: Each timer has its own 16-bit Period register, so when there is a match between the timer value and its period register, then an interrupt is generated and the timer is automatically reset to zero. No software intervention is required to reload the timer. Each timer has a gated timer operation Four of the timers can be concatenated to form two pairs of 32-bit timers

Motor Control PWM Block Diagram16-bit Time Base

Duty Cycle Generator #4 Duty Cycle Generator #3 Duty Cycle Generator #2 Duty Cycle Generator #1 Dead Time Unit PWM Override Logic Dead Time Unit Dead Time Unit

PWM4H PWM4L PWM3H PWM3L PWM2H PWM2L Dead Time Unit PWM1H PWM1L Fault A Fault BTwo fault pins w/ programmable fault states Four PWM output pairs with output polarity control

A/D Conversion Trigger

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 120

This is a general block diagram of the Motor Control PWM module. Up to 8 outputs and 2 fault inputs are available. The module has a dedicated timebase and four PWM duty cycle generators. Each duty cycle generator is connected to a dead time unit to insert dead band during rising or falling edges of the PWM. This feature is useful for driving complementary pair transistors or FETs. Finally, a control logic block, produces complementary outputs on each pair of PWM output pins. Edge aligned or center-aligned PWM wave-shapes can be produced. The commutation logic block controls output polarity, programmable fault shutdowns and allows the user to manually manipulate the PWM pins for motor commutation. The A/D conversion trigger allows a sequence of A/D conversions to be triggered at any point relative to the PWM timebase.

QEI Block DiagramClock DividerINDEX

Tcy

Digital Filter Logic

QEB/UP_ DN

Digital Filter Logic

Quadrature Decoder Logic DIRTimer Mode

Clock Reset

QEA/TQCKI GATE

Digital Filter LogicTcy

Prescaler and Sync. Logic

0 1

16-Bit Up/Down CounterTimer Mode

Comparator Max. Count Register

TQCS UP/DOWN

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 121

Quadrature Encode Interface: A typical application may utilize the direction output as an up/down input control flag and either channel, A or B, as the count input trigger for a common up/down counter. The counter in an incremental system will increment or decrement as required to maintain a relative position or count output. The x2 or 4 Measurement mode relates to whether the up/down counter will increment based upon both edges from one channel or both edges from both channels. The x4 Measurement mode will inherently provide finer resolution data on motor position. For example, with a 512 line count (N) encoder and implementing a x4 Measurement mode, the position angle resolution is: = 360 / 4 x 512 = 0.17578125 per incremental count For the x2 Measurement mode = 360 / 2 x 512 = 0.3515625 per incremental count For those applications which utilize an incremental encoder but the encoder does not have a index pulse output, the position counter can be reset by using the Max Count Compare register or letting the counter roll over. If the Max Count reset mode is used when the position counter equals the Max Count Compare register, the Position Count register will reset to zero and the revolution counter will be incremented.

DCI FeaturesSupport for PCM Audio CodecsDCI supports speech, modem and general audio applications

Automatic Synchronous Serial Data Transfer Support for I2S and AC97 Protocols TDM Features Support up to 16 Data Time Slots Module has up to 4 Word Buffer (16-bit words) Master or Slave Operation Separate Baud Generator for SCK Signal

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 122

The Data Converter Interface (DCI) module allows the dsPIC DSC to be connected to audio coder/decoders (codecs). Speech processing, soft-modems and general audio algorithms require high-quality analog input and output to the DSP device. These applications require A/D and DAC resolutions between 13 and 16 bits. The DCI is a type of synchronous serial interface with four I/O pins; SCK, SDI, SDO and FS. A data transfer is initiated by the Frame Sync (FS) signal. These transfers occur with zero CPU overhead at the data sampling rate. The FS signal can be generated by the DCI (master) or by the codec (slave). Either device may generate the SCK, which is continuous in most applications. The internal codec clocks may be derived from the SCK signal using a PLL. One or more data words may be transferred when the FS signal is generated. The DCI supports TDM transfers with up to 16 time slots per data frame. This is an important feature since many codecs transfer both audio and control data at the same time. The DCI has enable bits that determine which of the 16 time slots are transmitted/received. Thus, only the time slots of interest have to be buffered. The SDO pin is automatically tristated during unused time slots so other devices may be attached to the serial TDM bus. The TDM features of the DCI permit data to be shared in multi-channel/multi-processor DSP applications. Up to four data words may be buffered before an interrupt is generated. This feature saves interrupt processing overhead. The buffers may be used in one of two methods. First, multiple data samples for an audio channel can be buffered before processing. This technique is called block processing. Second, various time slots in a data frame can be stored in the buffer before interrupting the CPU. Therefore, all of the control and data samples are available at the time of the interrupt. The DCI has a SCK generator optimized for codec applications. Typical SCK frequencies vary between 16x and 256x the audio sampling rate. Typical audio sampling rates for targeted dsPIC audio applications include 8 kHz - 32 kHz.

DCI Block DiagramSCK GeneratorWord Size Control Frame Size Control Frame Sync Mode

CSCK

Frame Sync Generator

COFS

Receive Buffer Registers w / Shadow RegsData Bus

Buffer Control Transmit Buffer Registers w / Shadow Regs

CPU interrupt

16-bit Serial Shift Register

CSDI

CSDO

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 123

This is a block diagram of the DCI module. The module is organized as a Serial Shift register connected to a block of memory through a local AGU. The SCK signal may be generated internally or provided to the SCK pin from another device. The FS signal can be generated internally (DCI master) or provided by the codec (DCI slave). The module has control bits to select the data word size (up to 16-bits) the data frame length (up to 16 data words) and the type of FS signal that is generated/received. The buffer AGU is incremented each time data is transmitted or received during a timeslot. The DCI may be configured to buffer 1 to 4 data samples. An interrupt is generated when the buffer is full or has processed the requested quantity of samples.

UART Module

2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC

Slide 124

We will discuss and go into hands-on exercise for a few of the peripherals to give the user a taste of how to program and use them, as well as talk about some of the more advanced features of the peripherals. The first is the UART.

UART - OverviewSerial TX and RX of 8-bit or 9-bit DataFull-duplex, asynchronous communication Support for communication protocols such as RS-232, RS-422, RS-485 and LIN 4-deep transmit and receive buffers Transmit and receive interrupts Error detection Support for receiver addressing

Additional FeaturesLoopback mode Alternate TX/RX pins on some devices Wake-up from SLEEP 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 125

The UART module is used for transmission and reception of 8-bit or 9-bit data over a serial transmit line and a serial receive line. Many dsPIC30F devices contain two UART modules and therefore have two pairs of transmit and receive pins. UART communication is full-duplex, which means that a transmission and a reception can proceed simultaneously. It is also an example of Asynchronous communication, as each communicating entity is responsible for internally generating its own timing. The UART module may be used with standard protocols such as RS-232, RS-422, RS-485 and Local Interconnect Network or LIN. Besides basic transmission and reception capabilities, the UART has a number of useful features. For example, it includes independent buffering of up to 4 characters of transmitted data and up to 4 characters of received data, detection of communication errors, generation of interrupts and the ability to address individual UART nodes. Other features, which we will discuss in later slides, are Loopback, alternate communication pins and Wake-up from SLEEP.

UARTABAUD ICx 0 1 To Input Capture Baud Rate Generator UxRX 0 1 LPBACK Module Control / Error Handling LogicError Status

16 Divider

UxRSRLoad UxRSR to Buffer PF

UxRXREG

Parity UxTX Gen.

UxTSRLoad UxTSR

UTXBRK

UxTXREG

LIN Bus Support 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 126

This is a simplified Block Diagram of the UART module in a dsPIC30F device. Note that the communications interface consists of only 2 pins: UART Transmit and UART Receive. Observe also the 4-deep First In First Out (FIFO) buffering of data. The Transmit Shift register is used to shift out data through the UART Transmit pin, whereas the Receive Shift register is used to shift in data through the UART Receive pin. Data in successive locations of the transmit buffer are transferred to the Transmit shift Register and Receive Shift register contents are transferred to the Receive Buffer. Keep in mind that only the first location of the transmit buffer is memory-mapped and is therefore user-accessible as the UART Transmit register. Similarly, only the first received character of the receive buffer is user-accessible as the UART Receive register. There are some features provided mainly to support the LIN protocol. These features include autobaud features which allows the Rx pin to be directly connected to a capture input (which would have to be previously setup to accept this input). The timing of the incoming reception is detected and the new baud rate can then be appropriately set. Please note that the interrupt logic can be set to interrupt the CPU at the first, second, third or fourth serial byte reception.

UART Baud Rate GeneratorEach UART has a 16-bit baud rate generator Baud Rate controlled by UxBRG register Baud Rate = Fcy / ( 16 * (UxBRG + 1) ) UxBRG = Fcy / (16 * Baud Rate) - 1 (Fcy = Instruction Cycle Frequency) TX and RX use same baud rate 2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 127

The UART module contains a 16-bit baud rate generator, which is used to provide timing synchronization of data transfer and all other UART events. The Baud Rate Generator is memory-mapped and therefore user-accessible. Due to the communications being asynchronous, the user must configure the baud rate generators of the transmitting device, as well as the receiving device, such that both have the same baud rate. As is apparent from the equation, the maximum baud rate that can be attained is a sixteenth of the instruction cycle frequency Fcy.

UARTRegisters to Configure the UARTUxMODE, UxSTA, UxBRG

C Library for the UARTOpenUARTx(int configmode, int configsta, int setbrg) CloseUARTx() unsigned int ReadUARTx() WriteUARTx(int data)