You are on page 1of 174

Getting Started with the dsPIC30F 16-bit DSC

Hands-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

Goals
Gain 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 Overview
Leading 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 path
28-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 Endurance


100,000 Erase/Write Cycles Program Memory 1,000,000 Erase/Write Cycles Data EEPROM

Separate data EEPROM space


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

In-Circuit Debugging Support


Low 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 Control


PERFORMANCE
Embedded 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 MCU


Easy to use; Built-in Peripherals

Performs Like a DSP


Powerful DSP engine

Priced Like a MCU


The 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 Efficiency
dsPIC30F Processor includes features to enhance C code efficiency New instruction types + More flexible addressing + Software stack = Compact C code
32-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 Products
Power Conversion & Motor Control Family
Product 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 Industrial


Slide 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 Products
General Purpose Controller Family
Product 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 Products
Sensor Processor Family
Product 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 Measurement
Slide 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 IDE


Create 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 Controller
I/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 Features
Single 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 Model
15 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 ACCB
39
0

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

16 15
0

23 22

15 SRL
N OV SZ C

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

Status Register

DSP Status

MCU Status
Slide 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 Registers


More 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 - dsPIC30F6014


Reset 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 - dsPIC30F6014


MS Byte Address 2 kB SFR Space
0x0001 0x07FF 0x0801

16-bits MSB LSB

LS Byte Address
0x0000 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 Visibility


0xFFFF

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 Features


84 instructions Most are one cycle Most are one word (24 bit) Three operand instructions A = B op C
For 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 Modes


Register 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 DSP


Modulo (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.

Interrupts
Stack Operation Prior to ISR Entry

15

0 0x0800

SRL pushed onto stack to preserve IPL<2:0> and MCU ALU status (except DC)

PC<15:0> PC<22:16> SR<7:0>


IPL3

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 Tools


Editor, 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 coding
For assembler and C compiler

Many editor features


Cut, 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.

Editor
Title bar with file changed indicator Gutter display

Vertical split-pane control

d de co or ol C

x te

n pa t

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 Files


Find 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 simulator


Operates 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 features
16-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 Librarian


Source Files .C .S
Compiler

Object Files .O Linker


Assembler 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

Libraries
Math - 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 1
Learn 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 steps


Step 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 1
Start 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 1
Click 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 1
Select 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 1
Type 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 1
Click 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 1
Summary 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 1
Project 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 1
Project 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 2
Compile 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 Link


Tell compiler where to find header file #include <p30f6014.h> 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 1
Click 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 1
Find 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 1
Go 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 1
Include 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 1
Click 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 1
Build 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 3
Use 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 Hardware
MPLAB 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.1


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

Temp Sensor
LCD

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 Hardware


Connect 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 1
Click 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 Download


MPLAB 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 Window


MPLAB 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 1
Click 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 1
Click 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 4
Use 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 1
Click 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 1
Press 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 Keys


F5 - Halt F6 - Reset F7 - Single Step F9 - Run

Right Click
Set 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 1
Right 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 <Flash LED with Timer delay.c> 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 1
Find 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 1
Press 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 1
Press 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 1
Click 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 1
Hold 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 Overview


Interrupt 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 Table


Reset - 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 Levels


CPU 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 times


Starts at zero after Reset IPL<2:0> in Status Register - SR IPL3 in Core Control Register - CORCON

Higher priority interrupt can interrupt CPU


CPU 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<2:0>. The IPL<3> 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 registers


Interrupt sources can be levels 0 - 7 A level 0 source is effectively disabled Default interrupt priority is 4

Can change CPU priority by writing IPL<2:0>


IPL3 is read only - cant disable traps IPL<2:0> = 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<2:0> = 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 Saving


Only 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 Operation


IPL<2:0> bits
15 0

0x801 0x803

0x800 0x802

IPL3 bit

Stack Grows Towards Higher Address

PC[15:0] SR[7:0] PC[22:16] <Free Word>

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 Nesting


Interrupts nested by default Disable nesting by setting NSTDIS bit INTCON1<15> 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 2
Using 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 Interrupt
Learn about interrupts

Use Lab 2 Workspace Provided


Add 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 Registers


IFS1 - Interrupt Flag Status INT1IF bit and INT2IF bit IEC1 - Interrupt Enable Control INT1IE bit and INT2IE bit

Interrupt Vector Table


Use 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 2


LED1 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 2


Enable 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 3
Using 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 Code
Learn about interrupt priorities and interaction

Use Lab 3 Workspace Provided


Add 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 3


Set 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 3
A Picture is Worth a Thousand Words!

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

Reset
Slide 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 3
Initialize CPU, Timer1 and Timer2 Priority Level

Event 7 6 5 4 3 2 1 0

Pending

Timer2 Initialized Timer1

LED2 LED1

Reset
Slide 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 3
Timer2 Interrupt Occurs

Event 7 6 5 4 3 2 1 0

Pending

Timer2 Initialized Timer1

LED2 LED1

Reset
Slide 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 3
Timer2 Interrupt Returns

Event 7 6 5 4 3 2 1 0

Pending

Timer2 Initialized Timer1

LED2 LED1

Reset
Slide 98

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

Lab 3
Timer2 Interrupt Occurs

Event 7 6 5 4 3 2 1 0

Pending

Timer2 Initialized Timer1

LED2 LED1

Reset
Slide 99

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

Lab 3
Timer2 Interrupt Returns

Event 7 6 5 4 3 2 1 0

Pending

Timer2 Initialized Timer1

LED2 LED1

Reset
Slide 100

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

Lab 3
Code 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 3
Code 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 3
Pending 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 3
Pending 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 3
Return 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 3
Timer1 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 3
Return 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 3
Timer2 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 3
Return 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 3
Timer1 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 3
Timer2 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 3
Return 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 3
Return 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 3


Set 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 Solution
Line 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 CORE


16-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 2


18 SDIP 20 SSOP 28 SDIP 28 SSOP 40 DIP 44 TQFP 64 TQFP

Input Capture
(8 ch / 16-bit)

Program Memory Flash


144 kB

Data Memory SRAM


8 kB

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

Motor Control PWM

16-bit, 6-8 ch
Quadrature 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 Overview
Five 16-bit General Purpose Timers / Counters
Similar functionality between all 5 timers

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 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 Diagram


16-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 B
Two 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 Diagram


Clock Divider
INDEX

Tcy

Digital Filter Logic

QEB/UP_ DN

Digital Filter Logic

Quadrature Decoder Logic DIR


Timer Mode

Clock Reset

QEA/TQCKI GATE

Digital Filter Logic


Tcy

Prescaler and Sync. Logic

0 1

16-Bit Up/Down Counter


Timer 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 Features
Support for PCM Audio Codecs
DCI 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 Diagram


SCK Generator
Word Size Control Frame Size Control Frame Sync Mode

CSCK

Frame Sync Generator

COFS

Receive Buffer Registers w / Shadow Regs


Data 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 - Overview
Serial TX and RX of 8-bit or 9-bit Data
Full-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 Features
Loopback 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.

UART
ABAUD ICx 0 1 To Input Capture Baud Rate Generator UxRX 0 1 LPBACK Module Control / Error Handling Logic
Error Status

16 Divider

UxRSR
Load UxRSR to Buffer PF

UxRXREG

Parity UxTX Gen.

UxTSR
Load 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 Generator


Each 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.

UART
Registers to Configure the UART
UxMODE, UxSTA, UxBRG

C Library for the UART


OpenUARTx(int configmode, int configsta, int setbrg) CloseUARTx() unsigned int ReadUARTx() WriteUARTx(int data)

C Libraries also Support Classic C Type Routines:


getcUARTx(), putcUARTx(), putsUARTx() etc.

Other Functions Available are:


BusyUARTx(); DataRdyUARTx();
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 128

When using the UART, the user has to set the following registers: UxMODE, UxSTA and UxBRG where x = 1 or 2 If the user is using C, then C libraries are available, which can greatly help the user when configuring and using the UART. C libraries help to initialize the UART, read UART data and write to the UART. For those users programming in the PC world, there are classic C libraries like getc, putc, gets and puts functions which are also implemented. These functions are a great help when using the UART. In the next lab, we will use these UART functions in C.

Lab 4 Instructions
Use Lab4.mcw Already Defined
libp30F6014.a and UART.h are already in the project

Use C Libraries to Set UART1 Baud Rate to 9600


Use the formula U1BRG = Fcy / (16 x Baud Rate) - 1 Note that Fcy is already defined as FCY OpenUART1(U1MODEvalue, U1STAvalue, baudvalue);

Transmit a Text Message Ending with a NULL


Use WriteUARTx(int data) - Note: int, not char

Receive Buffer Receives Transmitted Data


Loopback mode is enabled When SW1 is pressed LCD should display Microchip
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 129

The workspace is already setup in Lab4.mcw. Choose the workspace in C:\wib1.1\lab4\lab4.mcw Key points to note: In order to use the C libraries, the user has to use the generic peripheral library module which is libp30f6014.a in this case. The user must also select the appropriate header file for the peripheral chosen, which in this case is UART.h. Note that these libraries have already been included in the project Lab4.mcw. Lab 4 consists of setting the UART baud rate to 9600 and transmitting a string of characters. To initialize the UART we will use the OpenUART1(U1MODEvalue,U1STAvalue,baudvalue); function, which has 3 parameters associated with it. The user has to define the baud value parameter. The string message displayed is Microchip, terminated with a NULL character. To transmit the characters, the user should use the WriteUARTx(int variable), function. Note that this function passes an int parameter not a Char. So if the actual data is char then it should be type cast as an int during the function call. Note the received buffer has already been setup to receive the transmitted characters by using the loopback feature of the dsPIC UART. The received characters are displayed on the LCD screen. Edit the program, compile and then run. Press SW1 on the board and one transmission should start. The word Microchip should be displayed on the LCD screen.

Lab 4 Instructions

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

Slide 130

Please look at the appropriate location in the main text file and make the required changes. Note that FCY and BAUDRATE are define so the user can directly use the formula for baud value provided in the slides.

Lab 4 Result

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

Slide 131

Edit, compile and run the program With the program running hit SW1 and with each hit Microchip will be displayed on the LCD screen as above.

Solution for Lab 4 Solution


Line 54: WriteUART1((int)Txdata[TxIndex++]); Line 83: baudvalue = FCY / 16/BAUDRATE - 1;

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

Slide 132

A/D Converters
10- or 12-bit High Speed, Multi-channel

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

Slide 133

The next peripheral which will be discussed is the Analog-to-Digital Converter.

A/D Converter 10-bit A/D


10-bit resolution with +/- 1-bit accuracy 500K samples/second conversion rate Up to 16 analog inputs, 4 S/H amplifiers

12-bit A/D
12-bit resolution with +/- 1-bit accuracy 100K samples/second conversion rate Up to 16 analog inputs, single S/H amplifier
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 134

There are two ADCs available on dsPIC DSCs. The motor control family of devices have the 10-bit ADC which has a 500 kps conversion rate and has 4 simultaneous sample inputs. This is important for motor control apps where simultaneous sampling of current and voltage is important. The General Purpose and Sensor Family has a 12-bit ADC with a 100 kps conversion rate and one sample and hold.

A/D Converter Common Features


External VREF+ and VREFAnalog input range: (VREF-) to (VREF+) Allows unipolar differential measurements Programmable sampling sequence 16 sample, dual-ported buffer Multiple conversion trigger sources Many conversion scheduling options

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

Slide 135

Some of the common features of the ADC are: External VREF capability with an analog range between VREF + and VREF-. The input is unipolar differential and the conversions are saved in 16 dual port buffers. It is possible to set the conversion for different trigger sources: PWM, timer timeout, INT pin input, etc. Several scheduling options are also available. Some of these will be discussed in the next few slides.

12-bit A/D Converter


VREF+ VREF AN0 AN1 CH0 S/H

Conversion Control

ADC 12 bit 100 KSPS

BUFFER 16 deep

Data Format

Bus Interface

Input MUXes

AN15

Sample Sequence Control

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

Slide 136

The basic 12-bit ADC block diagram is as shown. There can be a max of 16 inputs MUXed into one sample and hold circuit and the converter. The result is saved in the 16 deep buffer and can be loaded for different sampling sequences and conversion control options. The saved data can then be read by the CPU in four different formats: signed and unsigned integer/fractional formats.

12-bit A/D Converter Controlling Start of Sampling


ASAM = 1 - Automatically begin sampling after conversion Maximizes the sampling time ASAM = 0 - Does not automatically begin sampling User must set SAMP bit to begin sampling Clear SAMP bit to end sampling and start conversion SAMP bit is in the ADCON1 register
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 137

The are several methods for the sequence of sampling. One such method is to set the ASAM or Automatic Sample bit. In this method, the sampling automatically starts right after the conversion is done. This optimizes the sampling time. Another method is by not doing an automatic sampling but using manual sampling. Here the user would have to set the SAMP bit for sampling and clear SAMP bit to end sampling and start conversion.

12-bit A/D Converter


Controlling Start of Conversion SSRC Bits Select Method of Conversion Start
Manual trigger Clear SAMP bit to start conversion Auto sample time Internal TAD count starts conversion Motor Control PWM special event trigger 10-bit A/D only - synchronize measurement Timer3 period match trigger starts conversion INT0 pin active edge starts conversion

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

Slide 138

The conversion start can be controlled by several methods: The manual method involves the SAMP bit being set/reset by software as discussed in the previous slide. Auto sample time involves setting a internal TAD count. When this count times out, the conversion starts. Another method is from a PWM pulse trigger. This method is very useful in motor control applications where the user is interested in measuring the current consumption of the motor, thereby determining the torque or load on the motor. The current value however is only valid when the PWM is driving the circuit. Hence, the PWM trigger mechanism only reads the current when the PWM is active on that circuit. Still other methods of conversion starts are Timer3 period match or an active edge on a INT0 pin. As can be seen, the ADC is very flexible.

12-bit A/D Converter When is the Result Available? SMPI Bits Specify Samples per Interrupt Interrupt on Completion of nth Conversion
ADIF bit in IFS0
ADCON2 Register
VCFG2
bit15

VCFG1
14

VCGF0
13

OFFCAL
12

11

CSCNA
10

bit8

BUFS
bit7

SMPI3
5

SMPI2
4

SMPI1
3

SMPI0
2

BUFM
1

ALTS
bit0
Slide 139

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

Once the conversion is done, the ADC allows the user to save the digital data in a buffer. There are 16 buffers available to save the results. This allows the user to develop applications where multiple sample/conversion are done and saved in the buffer. Only when the buffer is full or nearly full, the CPU, can be interrupted and the ADC values retrieved. This allows efficient use of the CPU as well as the ADC. The SMPI bits allow for an interrupt to be generated at the 1st, 2nd, 3rd, 4th 16th load of the ADCBUF. Please note that the loading of the buffer is done very sequentially. So for example, if the user loads say 16 ADC values from a sequential scan of 16 inputs starting from AN0 to AN15 then after the interrupt, the ADCBUF5 register value will correspond to the value of the AN5 input.

12-bit A/D Converter Where is the ADC Result Stored?


16-word result buffer - ADCBUF0,1,2E,F Buffer resets to ADCBUF0 after each interrupt Overwrites ADCBUF0 after next conversion Can software unload buffer fast enough? Buffer Fill Mode - BUFM = 1 Buffer split into two 8-word buffers BUFS shows buffer used by A/D Converter BUFS = 1, ADC fills ADCBUF8 - ADCBUFF Max 8 samples per interrupt
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 140

As mentioned in the last slide, the result is stored in the ADCBUF0 ADCBUFF registers. This buffer is very versatile and can be divided into two using the BUFM bit. This Fill mode bit allows one 8-bit section to be loaded while the other is being accessed by the CPU.

12-bit A/D Converter


Alternate Input Sample Mode ALTS = 1 - Alternate Between MUX Inputs A and B AN15
MUX inputs B MUX inputs A
ADCHS Register
CHXNB<1:0>
bit15 14

. .

ADCBUFx
AN0 AN15 - AN1 AN0 AN15 - AN1

AN0 AN1 VREF-

+ CH 0 -

CHXSB
13

CH0NB=0
12 11

CH0SB<3:0>=0000
10 9 bit8

CHXNA<1:0>
bit7 6

CHXSA
5

CH0NA=1
4 3

CH0SA<3:0>=1111
2 1 bit0
Slide 141

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

Let us explore some examples on how to use the ADC. In the above setup, the ALTS or alternate sampling mode is used. In this mode, the user can setup two modes. The first mode uses the MUX A inputs are used to sample AN0. In the second mode, the MUX B inputs are used to sample AN15 minus AN1 or the difference between the AN15 input and the AN1 input. In this setup the ADC will alternate and sample AN0 ,then AN15-AN1, then AN0, then AN15-AN1 and so on until the interrupt occurs. The ADCBUFx registers will thus reflect the conversion values.

12-bit A/D Converter


Channel Scanning on MUX A - CSCNA = 1
AN15 AN14
. .

ADCBUFx
AN0 AN3 AN4 AN6

AN7 AN6 AN5 AN4 AN3 AN2 AN1 AN0

+ CH 0 VREF-

ADCSSL Register
bit15 14 13 12

CSSL15=0 CSSL14=0 CSSL13=0 CSSL12=0 CSSL11=0 CSSL10=0 CSSL9=0


11 10 9

CSSL8=0
bit8

CSSL7=0
bit7

CSSL6=1
6

CSSL5=0
5

CSSL4=1
4

CSSL3=1
3

CSSL2=0
2

CSSL1=0
1

CSSL0=1
bit0
Slide 142

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

Another example is to scan a series of inputs sequentially. To use this mode the CSCNA bit is set and the ADCSSL register is used to indicate which channels are to be scanned by setting the appropriate channel bits. So in this case shown in the slide, the bits which are set are for channel AN0, AN3, AN4 and AN6, the rest are zero. So after the first scan, the first value in the ADCBUF will be AN0 followed by AN3 and so on. These examples are used to show the flexibility of the ADC on dsPIC device. It can be truly said that the ADC can be setup for independent operations on the dsPIC MCU with minimal intervention needed from the CPU except to retrieve the results once the most efficient ADC conversion scheme is completed.

Lab 5 Setup
Channel Scanning on MUX A - CSCNA = 1
RP1

ADCBUFx
AN4 AN5 AN6 AN4 AN5 AN6 AN4 AN5 AN6 AN4 AN5 AN6
0 1 2 3 4 5 6 7 8 9 A B

AN15 AN14
. .

RP3

AN7 AN6 AN5 AN4 AN3 AN2 AN1 AN0

+ CH 0 VREF- = GND

RP2

ADC Interrupt ADCSSL Register


CSSL15=0 CSSL14=0 CSSL13=0 CSSL12=0 CSSL11=0 CSSL10=0 CSSL9=0
bit15 14 13 12 11 10 9

CSSL8=0
bit8

CSSL7=0
bit7

CSSL6=1
6

CSSL5=1
5

CSSL4=1
4

CSSL3=0
3

CSSL2=0
2

CSSL1=0
1

CSSL0=0
bit0

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

Slide 143

In Lab 5, we will use the scan feature on the dsPIC family. The pot marked RP1 is connected to AN6, RP2 is connected to AN4 and RP3 is connected to AN5. The 3 pots are scanned four times to give us a total of 12 ADC values. At that point, an ADC interrupt is generated. The sample time is automatically generated by using the TMR3 match. The match occurs every 10 ms. Each pot is sampled for 10 ms and then converted in about 15 us. This is repeated automatically 12 times. When the ADC interrupt is generated, the program averages four readings of each of the ADC inputs and displays the average value in hex on the LCD screen. The pot values are transmitted over the serial port which is placed in a Loopback mode. So the received data is displayed on the LCD screen.

Instructions for Lab 5


Use Lab5.mcw Workspace Setup Auto Sample Using 10mS TMR3 Trigger to Stop Sampling and Start Conversion Setup ADC to Scan AN4, AN5 and AN6 Connected to RP2, RP3 and RP1 Respectively Repeat Scan 4 Times by Setting Interrupts to Occur after 12 Sample/Convert Sequences Average the Pot Values and Display the Hex Value on the LCD Display.

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

Slide 144

In Lab5.mcw workspace is located in C:\wib1.1\lab5\lab5.mcw. On the dsPICDEM 1.1 board, there are 3 potentiometers RP1, RP2 and RP3 connected to AN6, AN4 and AN5 respectively. Steps for the user are highlighted in Yellow: 1. Set the ADC for Auto Sample mode using TMR3 match. The TMR3 is already setup to match every 10 ms so there is no need to set TMR3 registers. 2. Set the ADC to scan AN4, AN5 and AN6 3. Set the ADC to interrupt after 12 sample/convert sequences. The rest of the setup is already done. The user only needs to write lines of code needed to implement the above scheme.

Instructions for Lab 5

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

Slide 145

The 3 lines of code marked above are 3 registers in the ADC module, which need to be set for the scan routine mentioned earlier. The comments tell you what needs to be done in each instance.

Lab 5 Result

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

Slide 146

The result is displayed on the LCD screen as above. Move the 3 pot wipers and see the values change in the 3 locations.

Solution for Lab 5 Solution


Line 121: ADCON1 = 0x0044; Line 123: ADCON2 = 0x042C; Line 124: ADCSSL = 0x0070;

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

Slide 147

Lab 6: Digital Filtering Overview

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

Slide 148

Up until this point we have talked about the dsPIC30F architecture, its powerful instruction set, interrupt handling and wealth of peripherals. Now we will dwell on the main feature of the dsPIC DSC namely the DSP engine and its use in real application. In order to keep it simple let us talk today about one very commonly used DSP function namely digital filtering. Before we do that, lets review what digital filtering is all about.

Digital Filters
What is Digital Filtering?
The digital processing of an input signal to produce a desired output signal with a certain frequency response or characteristic

Advantages of Digital Filtering (Over Analog):


Less affected by noise Lower power consumption Programmable systems (easy to modify) Minimal characteristic drift with age Minimal characteristic drift with temperature

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

Slide 149

Digital filtering is the digital processing of an input signal to produce an output signal which meets certain desired characteristics. A good real life example would be if you dont want to hear the scratches on a vinyl album in an audio application then you would design a filter which gets rid of the high frequency tick sound of the scratch without losing any of the high frequency fidelity of the sound or music. Most commonly, this would be know as notch filter. Like all electronics, such problems were dealt earlier on using analog circuits however with the advent of high speed DSPs, the analog circuit has been circumvented by the digital world. Let us look at some of the reasons: Digital filters are MUCH easier to tune since there are no component (capacitor, inductor or resistor) tolerances to consideration when designing the filter. Since they use digital processing, they dont have additional active or passive components which would typically draw more power, so they are low power. The are programmable since all the reprogramming is done in the algorithm or firmware. They are also less immune to temperature and age drift since again the digital filter is an algorithm.

Digital Filter Types Digital Filters are Classified into Two Types
Finite Impulse Response (FIR) Infinite Impulse Response (IIR)

FIR and IIR Filters can be Designed to Provide Some Desired Response
Low Pass Filter (passes low frequencies) High Pass Filter (passes high frequencies) Band Pass Filter (passes a frequency band) Band Stop Filter (stops a frequency band)
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 150

There are two types of digital filters: Finite Impulse Response (FIR) and Infinite Impulse Response (IIR). Using these two types, the user can design a Low/High/Bandpass filter and Finally, a Bandstop filter. What are these types of filters? Lets see the next slide ...

DSP Features
All DSP Operations Execute in a Single Cycle Single Clock Cycle MAC Instruction:
Dual Address Generator Units (AGU) support parallel operand (data and coefficient) fetches Accumulator write-back

Fractional/Integer Multiplier for 16 x16-bit Operation Two 40-bit Accumulators


Supports algorithms using complex values (e.g. FFTs) or algorithms requiring multiple filter loops Less need for data input scaling to prevent overflow Separate overflow detect, flags and branches for each accumulator Optional saturation mode

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

Slide 151

The dsPIC DSC provides the best in class embedded control features of a 16-bit MCU, many applications can also benefit by employing DSP techniques to filter input signals or to analyze incoming data streams. Speed is essential to digital signal processing. You must complete the computations on the current data before the next data set arrives. This dictates that certain hardware functions exist on chip. The dsPIC family provides a performance solution that addresses the majority of embedded signal processing applications without the high cost of competing DSPs. The dsPIC30Fs Harvard Architecture is complemented with dual Address Generation Units, or AGUs, that support dual data fetches. A rich set of DSP instructions are provided and all operate in a single cycle. The Multiply and Accumulate Instruction (MAC), for example, can multiply and add or accumulate two operands, update two address pointers, fetch the next two operands, and transfer out the accumulator value, all in a single cycle. For DSP algorithms that only require multiplying without the accumulation, such as for FFTs, the dsPIC30F also supports 16-bit signed or unsigned fractional or integer math. Some applications such as space vector or PID loop motor control require two or more concurrent filters. Other algorithms, such as FFTs, require support for real and complex values. To support these and other applications which require multiple concurrent filters, the dsPIC30F provides two separate DSP accumulators. Each accumulator is 40-bits wide, reducing the need to scale input data. Optionally, overflow can be avoided entirely by enabling Saturation Mode. Each accumulator has its own overflow flags in the DSP status register, and separate branch instructions for each accumulator on overflow or data saturation.

DSP Features
40 Stage Barrel Shifter (up to 16-bits Left or Right)
Shift accumulators, W registers or memory

Accumulator Rounding During Store Operation


Conventional rounding Convergent (unbiased) rounding

Modulo Addressing (for Filters): Both AGUs Bit Reversed Addressing (for FFTs): One AGU Zero Overhead Instruction Loop Support
REPEAT: Repeat next instruction N times DO: Repeat loop N times Constant or variable loop count
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 152

But thats not all! The dsPIC30F provides more features to ensure optimal algorithm efficiency. Data transferred from the 40-bit accumulators passes through a 40-bit barrel shifter. This hardware can shift the data up to 16-bits left or right before storing the results, all in the same instruction cycle. For added flexibility, the barrel shifter can also operate directly on the 16 general purpose registers or on data memory. Data transferred from the accumulators may be rounded before being stored. Two different ways of rounding, conventional and convergent, are provided. To support digital filtering, special support for circular buffers is provided by a modulo addressing mode. For FFT support, a bit reversed addressing mode is provided that automatically calculates the next matrix element address. Finally, special hardware is provided to support zero overhead looping. This equates to better optimized DO and REPEAT loops commonly used in DSP algorithms as well as other common MCU tasks.

DSP Engine Block Diagram


Round Logic

40-bit Accumulator A 40-bit Accumulator B Saturate Adder


Negate

Saturate

16

40 40
Barrel Shifter

Enable 16

40 40

Sign Extend
Zero-backfill

32 33 17-bit Multiplier/Scaler Operand Pre-Processing From W Array To W Array 16 16

16

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

Slide 153

This slide shows a top level block diagram of the dsPIC30F DSP engine and how each of the block are interconnected. The basic components are Multiplier and data Scaler Sign-Extend and Zero-Backfill Logic Barrel Shifter Adder and Accumulators Round and Saturation Logic blocks

The DSP engines obtains it source operands from the W array for MACclass instructions, and from the X-bus for all other instructions requiring operand data. MAC-class instruction operands are pre-fetched concurrently from the X and Y data buses into specified W registers while the current instruction is executing using previously fetched data. All writes from the DSP engine are executed across the X-bus. We will look at each of the major components in more detail in module 8.

X Data Bus

Single Cycle MAC Instruction


FIR Filter Tap = 1 cycle Sample Instruction Syntax
MAC W4*W5, A, [W8]+=2, W4, [W10]-=6, W5, W13

Source operand registers

Destination accumulator X prefetch source

Y prefetch source

Y prefetch destination

X prefetch destination

Other Acc. Write-back destination

Basic Syntax

Optional Arguments
Slide 154

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

This slide shows the syntax of a MAC instruction. Note that only the source operand registers and the destination accumulator are mandatory arguments, whereas the other arguments are optional. The following operations may be performed in a single instruction cycle: 2 data fetches - one each from X and Y data space 2 updates to the X and Y effective addresses used for the data fetch operations 1 operation on Accumulator A or B with the data in two W-registers 1 write back of the other accumulator, Accumulator B in this example

Using dsPIC Digital Filter Design Simple as 1,2,3. Create a High Pass Filter with a Cutoff Frequency of 700 Hz
Design -> FIR Window Design -> Highpass

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

Slide 155

So lets design a filter using dsPIC Digital Filter Design or dsPIC FilterLite design. Open the program by double clicking on the icon. Then click on Design -> FIR Window Design -> Highpass. The window above will appear, select Highpass then Next. Note: The instructor can choose to give the dsPIC Digital Filter Design tool to the audience and ask them to step through this procedure in synch with these slides.

Specify the Filter Characteristics


Sample Frequency = 10,000 Hz Passband = 700 Hz Stopband = 500 Hz Passband Ripple = 3 dB Stopband Ripple = 4 dB

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

Slide 156

Use the above values and fill in the highpass filter parameters. After these are filled in, hit Next. Please remember, you as a user will most likely know the parameters for your filter. The parameters here are for our filter and well explain the reasons for the value shortly.

Choose the Windowing Function Applied to the Filter

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

Slide 157

The design tool now offers you a whole lot of filter types which you can design to. Obviously there are some which have high tap value. The tool designer has marked that filter which is optimized for dsPIC designs. In this case, it is the Kaiser filter with 49 taps. Hit Next ...

The Filter Characteristics are Displayed.

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

Slide 158

Now we see the frequency, phase, impulse and step responses of this filter. You can go back and modify the input criteria before generating the filter taps. Point to note is the impulse response. You can see that a impulse basically stabilized after a period of time, which proves once again the stable nature of FIR filters.

Generate the Filter Coefficients and Source Code


Codegen -> Microchip -> dsPIC30

Save the File as fir_test1 in C:\wib1.1\lab6\


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

So the filter parameters are complete. To generate code for the dsPIC devices, simply select: Codegen, then Microchip then dsPIC30. Select the header file and save the coeff in as x data space. Hit okay and viola - the code is generated. This generates a dsPIC30F assembly source file which contains the filter tap coefficients in a constant table. The format matches the FIR/IIR filter library needs.

Filter Design Output File: Filter Taps Definition

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

Slide 160

You can see the filter taps here as .hword definitions. The number of taps are also defined for the filter library. The actual code for the FIR filter calculations is located in the filter object module which is linked into this project. Please do a rough count and you will notice 49 coeff values for the 49 taps in the Kaiser filter we chose.

DSP Performance Benchmark


Cycle Count Comparison (Normalized) Using BDTI Benchmarks
BDTI Benchmark Results Microchip 1 dsPIC 30Fxxx TI 3 C24x/C24xx
3

Motorola 2 56F83xx (56800E)

ADI 2199x (219x)

Vector Dot Product Real Block FIR Two-Biquad IIR Control

1.00 1.00 1.00 1.00

1.16 1.32 2.12 2.05

1.07 1.11 1.29 2.06

1.32 1.02 1.47 1.76

Notes: 1. Projected Results 2. Buyers Guide to DSP Processors, 2001 Edition 3. Buyers Guide to DSP Processors, 1999 Edition
Results (c) 1999-2004 Berkeley Design Technology, Inc. Contact info@BDTI.com for info.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 161

Addressing high-end audio and communications tasks requires performance that most cost sensitive embedded control applications neither need nor can afford. The goal of the dsPIC30F is to provide a performance solution that addresses the majority of embedded signal processing applications without the high cost of competing DSPs. We think we hit the mark, but you dont have to take our word for it. This data is from BDTI, an independent DSP industry benchmarking firm. It compares the number of instruction clock cycles each device takes to execute a certain DSP algorithm, with the dsPIC30F results normalized to one. As you can see, the performance compares very well with other embedded control DSP devices. Take a close look at the control benchmark. This specific benchmark speaks to the efficiency of the dsPIC30F device in support of a wealth of embedded control based applications.

DSP Performance Benchmark


Execution Time Comparison (Normalized) Using BDTI Benchmarks
BDTI Benchmark Results dsPIC 1 30Fxxx (30 MIPS)
1

TI 3 C2xx/C24xx (40 MIPS)

Motorola 2 56F83xx (60 MIPS)

ADI 2 2199x (219x) (160 MIPS)

Vector Dot Product Real Block FIR Two-Biquad IIR Control

1.00 1.00 1.00 1.00

0.87 0.99 1.59 1.54

0.53 0.55 0.65 1.03

0.25 0.19 0.28 0.33

Notes: 1. Projected Results 2. Buyers Guide to DSP Processors, 2001 Edition 3. Buyers Guide to DSP Processors, 1999 Edition
Results (c) 1999-2004 Berkeley Design Technology, Inc. Contact info@BDTI.com for info.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 162

Heres the same DSP algorithms compared by execution time. Even though the dsPIC30F is more efficient, other devices running faster than the dsPIC30F can produce quicker results on some DSP routines. However, the dsPIC30F was designed to optimize both MCU and DSP performance. Notice the circled MCU control algorithm row in the middle. The dsPIC30F excels on performing control tasks compared to typical DSP devices in the same operating MIPS region.

Additional Benchmarks
Benchmark FIR Filter Tap Biquad IIR (4 coeff) (single sample) PID (core only) Cycle Count 1 8 Execution @ 30MIPs 33 ns 267 ns

233 ns

PID 31 (core, error calculation, limit check, wind-up control) Division 18

1.02 us

600 ns

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

Slide 163

Here is code to base full benchmark for PID with error calculation, limit check, and anti-windup. This is realistic code, because it is a generic callable fxn. User passes pointer to structure that contains setpoint, feedback measurement, gains, integral, output limits, and output. See PI.inc for details of structure.
;;------------------ ASM30 API for PI routines --------------------; PIParm stucture: .equ PI_qdSumL,0 .equ PI_qdSumH,2 .equ PI_qKp,4 .equ PI_qKi,6 .equ PI_qKc,8 .equ PI_qOutMax,10 .equ PI_qOutMin,12 .equ PI_qInRef,14 .equ PI_qInMeas,16 .equ PI_qOut,18 .equ NKo,4

Interfacing to the DSP Library DSP Library is Both C Callable and Assembly Callable C Interface Requires Just 2 files:
LIBDSP.A and DSP.H Provided in C30Tools directory

Library Typedefs
typedef int fractional;

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

Slide 164

If you want to use this library, you have to include the library object module LIBDSP.A into our project so that it is linked with your code. You also have to include the DSP.H header file into any source files that will call these functions. Lastly, the libraries operate in fractional datatypes, which this typdef defines as integers. Please note that we have already included these files in the project for Lab 6.

Digital Filters and the DSP Library Library Filters Operate on Blocks of Data One Filter Initialization Call is Required FIR
FIRDelayInit (&fir_test1Filter); FIR (BLOCK_LENGTH, &filter_output_array[0], &array[0], &fir_test1Filter);

IIR (Transposed and Canonic Realizations)


IIRTransposedInit (&fir_test1Filter); IIRTransposed (BLOCK_LENGTH, &filter_output_array[0], &array[0], &fir_test1Filter); For Canonic, use IIRCanonicInit(), IIRCanonic()
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 165

In order to use the FIR filter code generated, the user has to first call the FIRDelayInit routine to initialize the filter taps to prevent startup noise/instability. This only needs to be called during power-up to prevent random tap data. Then every time you want to use the filter, you call the FIR library, providing a pointer to your input and output data, size and tap coefficient table pointer.

Lab 6: Digital Filtering and the dsPIC Digital Signal Controller

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

Slide 166

Lab 6 Overview Objectives


Use filter coefficients created by dsPIC Filter Design tool Learn how to integrate the designed filters into your project Learn how to use the DSP Library

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

Slide 167

Lab 6 Overview Tasks


The input signal contains the sum of three sine waves at 847, 367 and 123 Hz. The dsPIC Filter Design tool was used to design a high pass filter at 700 Hz to remove the 367 and 123 Hz noise components. The coefficients are stored in the file fir_test1.s Call the C FIR library function which uses the filter coefficients to remove the identified noise components Extra Credit: Benchmark the filter routines using TMR1
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 168

The dsPICDEM 1.1 Demonstration Board has hardware which can generate sine waves. We have used these to generate 3 sine waves and have mixed them up to give a rather distorted waveform of 847, 367 and 123 Hz. We will design a digital filter at a high pass of 700 Hz and remove the lower 367 and 123 Hz signals leaving only the 847 Hz and a nice clean waveform. All routines are in C. Extra credit will be given to those who use TMR1 and determine the time taken for the filter to run.

Input Signal
Pressing the SW1 Button Displays the Filter Input on the LCD Display:

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

Slide 169

A charting function has been implemented to display the waveforms on the LCD screen. If you hit the SW1 switch, you will be able to see a replica of the waveform above. The FIR is not implemented so hitting SW2 will only show a straight line. Once the filter is implemented and called, the waveform will look much better.

Output Signal
Pressing the SW2 Button Displays the Filter Output on the LCD Display:

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

Slide 170

Once the filter has been used and implemented, the filtered wave form will look as above.

Conclusion
The dsPIC30FXXXX Architecture and Peripheral Set is Ideal for DSP Applications Development Tools are Versatile, Inexpensive and Easy to Use When Developing Applications DSP Tools Reduce Mathematical Complexity With Easy Code Generation DSP Application Notes and Reference Designs: Motor Control, Filters, Speech and Connectivity

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

Slide 171

The DSP architecture and peripheral set is ideal for many DSP as well as MCU applications. Microchip development tools are also very easy to use and are inexpensive. This help the customer during the development process. DSP tools shorten the time taken to configure and handle complex mathematical equations during DSP-related processes. They also make the DSP process simple by generating code automatic. Finally, DSP application notes and reference designs are available from Microchip, to help customers in their own motor control or filter or speech recognition applications.

Survey
Please dsPIC30F Workshop in a Box Survey at:
http://techtrain.microchip.com/surveys/dspic/dspic_wsiab.aspx

Those Who Complete the Survey Will be Entered in a Drawing for Several Valuable Prizes

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

Slide 172

Thanks for Attending! Good Luck in Your Development

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

Slide 173

The Microchip name and logo, the Microchip logo, Accuron, dsPIC, KeeLoq, MPLAB, PIC, PICmicro, PICSTART, PRO MATE, PowerSmart and rfPIC are registered trademarks of Microchip Technology Incorporated in the U.S.A. and other countries. AmpLab, FilterLab, microID, MXDEV, MXLAB, PICMASTER, SEEVAL, SmartShunt and The Embedded Control Solutions Company are registered trademarks of Microchip Technology Incorporated in the U.S.A. Application Maestro, dsPICDEM, dsPICDEM.net, dsPICworks, ECAN, ECONOMONITOR, FanSense, FlexROM, fuzzyLAB, In-Circuit Serial Programming, ICSP, ICEPIC, Migratable Memory, MPASM, MPLIB, MPLINK, MPSIM, PICkit, PICDEM, PICDEM.net, PICtail, PowerCal, PowerInfo, PowerMate, PowerTool, rfLAB, Select Mode, SmartSensor, SmartTel and Total Endurance are trademarks of Microchip Technology Incorporated in the U.S.A. and other countries. Serialized Quick Turn Programming (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.

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

Slide 174

You might also like