Anda di halaman 1dari 79

Getting Started

with the

DS
Digital Signal Controller

1
Table of Contents

1 WELCOME............................................................................................................................... 4

2 THE DS DIGITAL SIGNAL CONTROLLER.................................................................... 5


2.1 ARCHITECTURE ................................................................................................................... 5
2.2 DEVICE VARIANTS ............................................................................................................... 9
2.3 APPLICATIONS ................................................................................................................... 10
3 THE MICROCHIP DEVELOPMENT TOOLS......................................................................... 11
3.1 MPLAB IDE ..................................................................................................................... 11
3.2 LANGUAGE TOOLS ............................................................................................................. 12
3.3 DEBUGGERS/EMULATORS .................................................................................................. 13
3.4 PROGRAMMERS................................................................................................................. 15
3.5 DEMO BOARDS .................................................................................................................. 16
4 THE MPLAB INTEGRATED DEVELOPMENT ENVIRONMENT.......................................... 18
4.1 MPLAB IDE OVERVIEW .................................................................................................... 18
4.2 CREATING A PROJECT ....................................................................................................... 18
4.3 BUILDING THE CODE .......................................................................................................... 22
5 THE MPLAB SIMULATOR .................................................................................................... 25
5.1 OPENING THE PROJECT ..................................................................................................... 25
5.2 SELECTING THE SIMULATOR ............................................................................................... 25
5.3 DEBUGGER SETTINGS........................................................................................................ 26
5.4 SFR, FILE REGISTER, AND WATCH WINDOWS .................................................................... 26
5.5 WALKING THROUGH CODE ................................................................................................. 27
5.6 BREAKPOINTS ................................................................................................................... 28
5.7 WATCH WINDOW ............................................................................................................... 29
5.8 STOPWATCH ..................................................................................................................... 30
5.9 TRACE .............................................................................................................................. 30
5.10 APPLYING STIMULUS ...................................................................................................... 30
6 THE MPLAB ICD 2 IN-CIRCUIT DEBUGGER...................................................................... 32
6.1 INSTALLING THE USB DRIVER ............................................................................................ 32
6.2 SETTING UP THE SERIAL PORT ........................................................................................... 33
6.3 OPENING THE PROJECT ..................................................................................................... 36
6.4 SELECTING THE ICD2........................................................................................................ 36
6.5 DEBUGGER SETTINGS........................................................................................................ 36
6.6 SFR, FILE REGISTER, AND WATCH WINDOWS .................................................................... 38
6.7 WALKING THROUGH CODE ................................................................................................. 39
6.8 BREAKPOINTS ................................................................................................................... 39
6.9 ADVANCED BREAKPOINTS .................................................................................................. 40
6.10 WATCH WINDOW ........................................................................................................... 41
7 THE MPLAB ICE 4000 IN-CIRCUIT EMULATOR ................................................................ 42
7.1 INSTALLING THE USB DRIVER ............................................................................................ 42
7.2 OPENING THE PROJECT ..................................................................................................... 44
7.3 SELECTING THE ICE4000 .................................................................................................. 44
7.4 DEBUGGER SETTINGS........................................................................................................ 44
7.5 SFR, FILE REGISTER, AND WATCH WINDOWS .................................................................... 46
7.6 WALKING THROUGH CODE ................................................................................................. 47
7.7 BREAKPOINTS ................................................................................................................... 48
7.8 COMPLEX TRIGGERS ......................................................................................................... 48

2
7.9 WATCH WINDOW ............................................................................................................... 49
7.10 STOPWATCH .................................................................................................................. 50
7.11 TRACE........................................................................................................................... 51
8 THE ASM30 ASSEMBLER.................................................................................................... 52
8.1 MPLAB ASM30 ............................................................................................................... 52
8.2 GENERAL FORMAT OF INSTRUCTIONS AND DIRECTIVES ....................................................... 52
8.3 COMMONLY USED DIRECTIVES ........................................................................................... 53
8.4 EXAMPLE CODE ................................................................................................................. 56
9 THE C30 COMPILER............................................................................................................. 60
9.1 INTRODUCTION .................................................................................................................. 60
9.2 MPLAB C30 PROJECTS .................................................................................................... 60
9.3 CREATING A PROJECT WITH THE PROJECT WIZARD ............................................................. 61
9.4 BUILDING THE PROJECT ..................................................................................................... 64
9.5 LANGUAGE FEATURES ....................................................................................................... 65
9.6 EXAMPLE CODE................................................................................................................. 65
10 THE LINK30 LINKER......................................................................................................... 67
10.1 LINKER SCRIPT FILES ..................................................................................................... 67
11 THE DSPICDEM STARTER DEMO BOARD .................................................................... 73
11.1 FEATURES ..................................................................................................................... 73
11.2 SCHEMATIC ................................................................................................................... 74
12 APPENDIX A – TUTORIAL CODE FOR DSPICDEM STARTER DEMO BOARD ........... 75
12.1 FLASH LED WITH TIMING LOOP AND SWITCH PRESS.S ...................................................... 75
12.2 SOFTWARE DELAY LOOP.S .............................................................................................. 77
12.3 FLASH LED WITH TIMING LOOP AND SWITCH PRESS.C ...................................................... 78

3
1 Welcome To learn more about MPLAB and the many
other development tools we make, go to
Welcome to the world of Microchip, your top Chapter 3.
source for comprehensive microcontroller
solutions. Already the world leader in 8-bit Once you have chosen the right dsPIC for
microcontroller shipments, we now introduce your application and obtained the
the new 16-bit DS digital signal controller. development tools of your choice, it is time
to start using the tools to develop code. To
Targeted at a wide variety of applications, get started with MPLAB and your first dsPIC
the dsPIC offers the flexibility and project, go to Chapter 4.
control of a microcontroller with the
computation and throughput Choosing The simulator in MPLAB allows you
to debug your code without any
capabilities of a digital signal DS Parts
processor. The architecture hardware. The simulator is
and peripherals are Development completely integrated into
the MPLAB software and
covered extensively in Tools Overview
this guide and there you can learn how to
are tips on Starting an MPLAB Project use it in Chapter 5.
selecting the right
dsPIC for your Simulator The MPLAB ICD
design. 2 In-Circuit De-
ICD2 In-Circuit Debugger bugger gives you
The dsPIC is the flexibility to debug
Assembler, Compiler, Linker directly in the dsPIC chip
supported by a wide
on your own circuit board.
variety of development dsPICDEM Starter
tools centered around the The ICD 2 is exceptional value
Demo Board for money and you can find out
industry leading MPLAB
Integrated Development how to use it in Chapter 6. The ICD
Environment. In this guide, you will 2 will be used extensively with the
learn how to use MPLAB and related dsPICDEM Starter Demo Board in many
tools such as the assembler, compiler, of the hands-on tutorials later in this guide.
linker, simulator, debugger and emulator. All
the tools will be covered so you will find this The ICE4000 emulator is the most
guide useful even if you have no hardware sophisticated debugging tool for the dsPIC
yet. For maximum benefit and ease of devices. To get started with the ICE4000, go
learning, the hands on tutorials are based on to Chapter 7
the dsPICDEM Starter Demo Board and the
ICD 2 In-Circuit Debugger. The core tools for writing code for the dsPIC
are the assembler, compiler and linker. The
ASM30 assembler (Chapter 8) and LINK30
To choose the right dsPIC for your design or linker (Chapter 10) are provided free with
learn more about the features of this the MPLAB development environment and
capable digital signal controller, go to are sufficient for may applications. For those
Chapter 2.
2 needing the added power of a C compiler,
the C30 Compiler (Chapter 9) is available.
These tools are based on the industry
If you are completely new to Microchip, standard GNU toolsuite.
please start at Chapter 2 to learn about
the dsPIC digital signal controller and One of the most cost effective ways to get
then proceed through the other started with the dsPIC is to purchase the
chapters. dsPICDEM Starter Demo Board described in
Chapter 11 and try out the example code.
We use the board extensively in this guide
Microchip provides a powerful development and it will usually pay for itself very quickly.
environment called MPLAB, absolutely free!

4
2 The DS Digital Signal Controller
The 16-bit dsPIC digital signal controller (DSC) is Microchip’s newest and most advanced
processor. In this chapter you will learn about the features of this processor (2.1 Architecture), the
different dsPIC devices available (2.2 Device Variants) and how to choose the most suitable
dsPIC for your application (2.3 Applications).

The dsPIC is an advanced 16-bit processor with true DSP capability which retains the
fundamental real time control capabilities of a microcontroller. The outstanding prioritized
interrupts, extensive built-in peripherals and power management features are combined with a full
featured DSP engine. Dual 40-bit accumulators, single cycle 16x16 MAC, 40-bit barrel shifter,
dual operand fetches, and zero overhead looping are among the features making this a very
capable DSP.

If you do not understand any of these terms, don’t worry, they will be covered in more detail in
this chapter.

2.1 Architecture
Harvard Architecture

The dsPIC processor has a Harvard architecture with


separate program and data memory buses. DS CPU

Program Bus Data Bus


The Harvard architecture allows different size data (16
bits) and instruction (24 bits) words. This improves the
efficiency of the instruction set. It also allows faster
processing because the dsPIC can pre-fetch the next 24 16
instruction from program memory at the same time as it
executes the current instruction that access data RAM. Program Data
Flash RAM
Program Memory and Program Counter

The program counter (PC) is 24-bits wide and addresses


up to 4M x 24 bits of user program memory space. The
program counter increments by two for each three-byte
instruction. Relax, this will be explained later!The
program memory space contains the reset location, the
interrupt vector tables, the user program memory, the
data EEPROM, and the configuration memory.

The processor begins program execution at the reset location 0x000000. This location is
programmed with a GOTO instruction which branches to the start of the code The GOTO
instruction at the reset location is followed by the interrupt vector tables. The program memory for
code starts after the vector tables.

Program looping can be done with minimal overhead with the DO and REPEAT instructions, both
of which are interruptible at any time. These features help make repetitive DSP algorithms very
efficient while maintaining the ability to handle real time events.

5
Data Memory

The data space is 64 Kbytes and is treated as one


linear address space by most instructions. When
using certain DSP instructions (Instruction Set) the
memory is split into two blocks, called X and Y
data memory. This allows these DSP instructions
to support dual operand reads, so that data can be
fetched from X memory and from Y memory at the
same time for a single instruction. The X and Y
data space boundary is fixed for any given device.
When not doing DSP instructions, the memory is
all treated as a single block of X memory.

The first 2kB of data memory is allocated to the


Special Function Registers (SFRs). The SFRs are
control and status registers for core and peripheral
functions in the dsPIC.

Up to 8kB of data RAM is implemented after the


SFRs. This is general purpose RAM that can be
used for data storage. This RAM is split into X and
Y memory for DSP instructions.

The first 8kB of data space (i.e. all 2kB of SFRs


and the first 6kB of RAM) is called “near” RAM and
can be accessed directly by any instruction that
accesses RAM. Some instructions cannot directly

access RAM that is not “near” and must use


indirect addressing.

The last 32kB of data RAM space is not


implemented but can be mapped into program
space for Program Space Visibility. This allows
tables in program memory to be read as though it
were in data RAM.

Working Register Array

The dsPIC devices have sixteen 16-bit working


registers. Each of the working registers can act as
a data register, data address pointer, or address
offset register. The 16th working register (W15)
always operates as a software stack pointer for
interrupts and calls.

6
Data Addressing Modes

The CPU supports Inherent (no operand), Relative, Literal, Memory Direct, Register Direct and
Register Indirect Addressing modes. Relax, these are not as complicated as they sound! Each
instruction that addresses data memory can use some of the available addressing modes. As
many as six addressing modes are supported for each instruction. The working registers are used
extensively as address pointers for the indirect addressing modes. They can be modified (e.g.
incremented) and used as pointers in the same instruction.

Modulo and Bit Reversed Addressing

Modulo addressing allows circular buffers to be implemented with no processor overhead to


check the boundaries of the buffer. The pointer for the buffer can be set up to automatically wrap
around to the beginning of the buffer after it reaches the end, and vice versa. This can be done in
both X and Y memory, significantly reducing the overhead for DSP algorithms.

The X memory also supports bit-reversed addressing to greatly simplify input or output data
reordering for radix-2 FFT algorithms.

Program Space Visibility

The upper 32KB of the data space memory map can


optionally be mapped into program space at any 16K
program word (32KB) boundary defined by the 8-bit CPU
Program Space Visibility Page (PSVPAG) register.
Program Bus Data Bus

The program to data space mapping feature lets any


instruction access program space as if it were data
24 16
space. This is useful for look-up tables, especially
tables of filter coefficients in DSP algorithms.
Program Data
Instruction Set Flash RAM

The dsPIC30F instruction set has two classes of


instructions: MCU instructions and DSP instructions.
These two instruction classes are seamlessly
integrated into the architecture and execute from a
single execution unit. The instruction set includes many
addressing modes and was designed for optimum C
compiler efficiency.

All instructions execute in a single cycle, with the exception of instructions that change the
program flow, the double-word move (MOV.D) instruction and the program memory read/write
(table) instructions.

For most instructions, the dsPIC30F is capable of executing a data memory read, a working
register data read, a data memory write and a program memory (instruction) read per instruction
cycle. As a result, 3 operand instructions can be supported, allowing A+B=C type operations to
be executed in a single cycle.

DSP Engine

The DSP engine features a high speed, 17-bit by 17-bit multiplier, a 40-bit ALU (Arithmetic Logic
Unit), two 40-bit saturating accumulators and a 40-bit bi-directional barrel shifter. The barrel
shifter is capable of shifting a 40-bit value up to 15 bits right, or up to 16 bits left, in a single cycle.

7
The DSP instructions operate seamlessly with all
other instructions and have been designed for
optimal real-time performance. The MAC
instruction and other associated instructions can
concurrently fetch two data operands from
memory while multiplying two W registers. This is
possible because the data memory is split into X
FIND A and Y memory spaces for DSP instructions.
BETTER
PICTURE Interrupts

The dsPIC30F has a vectored interrupt scheme.


Each interrupt source has its own vector and can
be dynamically assigned one of seven priority
levels. The interrupt entry and return latencies are
fixed, providing deterministic timing for real time
application.

The interrupt vector table (IVT) resides in


program memory, immediately following the
instruction at the reset location. The IVT contains
62 vectors consisting of up to eight non-
maskable trap vectors and up to 54 sources of
interrupt. In general, each interrupt source has
its own vector. Each interrupt vector contains the FIND A
24-bit wide starting address of the associated
interrupt service routine (ISR). BETTER
PICTURE
The Alternate Interrupt Vector Table (AIVT) is
located after the IVT in program memory. If the
ALTIVT bit is set, all interrupt and exception
processes will use the alternate vectors instead
of the default vectors. The alternate vectors are
organized in the same manner as the default
vectors and helps debugging and testing by
providing a means to switch between an
application and a test environment without
requiring the interrupt vectors to be
reprogrammed.

System and power management

Modern applications often require flexible operating modes to conserve battery power, reduce
EMI and handle fault conditions. The dsPIC has many system and power management features.
It has several oscillator modes, clock switching and oscillator failure detection. There are many
power saving modes that can selectively shut down and wake up parts of the processor and
peripherals. There are other safety features such as low voltage detection, brown-out reset,
watchdog timer reset and several error traps.

8
Peripherals

The dsPIC devices are available with a wide range of peripherals to suit a diverse assortment of
applications. The main peripherals are listed below and will be discussed in more detail later in
this guide.

• I/O ports • 10-bit or 12-bit ADC


• Timers • UART
• Input capture • SPI
• Output compare / PWM • I2C
• Motor Control PWM • Data Converter (CODEC) Interface
• Quadrature encoder • Controller Area Network (CAN)

Each device variant has a subset of these peripherals.

2.2 Device Variants

The dsPIC devices fall into three broad families. They are
characterized this way to help you pick the most suitable
part for your application: General
Purpose
General Purpose
Motor Control / Power Conversion
Sensor
Motor Control /
Power Conversion
General Purpose family
Sensor
The general purpose devices are 40 to 80 pin parts ideal for
a variety of 16-bit embedded applications. The parts with
CODEC interfaces can support many audio applications.

• All have a 12-bit, 100ksps ADC


• Most have a CODEC interface
• Most have a CAN interface
• All have dual UARTs
• Timers, Input capture, Output compare
• UART, SPI, I2C serial interfaces

Motor Control and Power Conversion family

The motor control devices are 28 to 80 pin parts designed to support motor control applications.
They are also suited for uninterruptable power supplies, inverters, switched mode power supplies
and related equipment.

• All have a 10-bit, 500ksps ADC


• All have a Motor control PWM
• All have a Quadrature encoder
• Timers, Input capture, Output compare
• UART, SPI, I2C serial interfaces

Sensor family

9
The sensor devices are small 18 to 28 pin parts designed to support low cost embedded control
applications. They have most of the features of the general purpose family but fewer of each
peripheral.

• All have a 12-bit, 100ksps ADC


• Timers, Input capture, Output compare
• UART, SPI, I2C serial interfaces

2.3 Applications

Now that you have a basic understanding of the dsPIC architecture, you can consider the
suitability of the dsPIC for your particular application. There are endless possibilities but here are
the most common applications for the dsPIC:

Motor control

The dsPIC is ideal for motor control that needs more than a basic 8-bit microcontroller. Brushless
DC, AC Induction and Switch Reluctance motors can all be controlled with a dsPIC. The
applications might require sensorless control, torque management, variable speed, position or
servo control. Noise reduction and energy efficiency applications can also be handled.

Internet connectivity

Ethernet and modem applications for Internet connectivity are supported with
Microchip’s ready to use TCP/IP, Ethernet driver and soft modem application
libraries

Speech and audio

The dsPIC can support many audio applications such as noise and echo cancellation, speech
recognition and speech playback. It can also be used as a companion chip to a main DSP in
high-end audio application to handle other tasks such as digital tuning, equalizers, etc.

Power conversion and monitoring

The many PWM modules and fast ADC in the dsPIC open up many power conversion
and power management applications. Uninterruptable power supplies, inverters, and
power management units for complex equipment can all be handled.

Sensor control

The smaller dsPIC devices are ideal for advanced sensor control. The ADC and serial
communication peripherals combined with the power management features make it possible to
create smart sensor interface modules.

Automotive

Microchip is QS-9000 and ISO/TS-16949 certified and has automotive


temperature grades parts. Traditionally our products have had long life
cycles to support product life cycles typical of automotive applications.

10
3 The Microchip Development Tools
Now that you’ve decided which dsPIC device suits your application, you will need development
tools. The development process can be broken down into three distinct steps:

• Writing your code


• Debugging the code
• Programming devices

You’ll need a tool to serve each of these functions. The key is MPLAB IDE

Note: To get started, the most cost-effective debugging and programming solution is the
MPLAB ICD 2 (DV164005). The ICD 2 can be used with the dsPIC Starter Demo
Board (DM300016) for an ideal learning platform.

3.1 MPLAB IDE


The MPLAB Integrated Development Environment (MPLAB IDE) allows you to develop a project
from beginning to end, all within the same environment. You do not need to use a separate editor,
assembler/compiler, and programming utility to create, debug, and program your applications.
The MPLAB IDE can control all aspects of this process.

MPLAB® IDE

Writing Code Debugging Programming

E E
FR
MPLAB® ASM30 MPLAB® ICD2 MPLAB® ICD2
MPLAB® C30 MPLAB® ICE4000 MPLAB® PRO MATE II
MPLAB® LINK30 EE MPLAB® SIM30 EE MPLAB® PM3
FR FR

EE ASM30, LINK30, and SIM30


FR included in MPLAB® IDE

MPLAB IDE is provided free (on CD and on www.microchip.com) and includes the project
manager, editor, ASM30 assembler, LINK30 linker,
simulator and also interfaces to various programmers,
debuggers and emulators.

Projects

The MPLAB IDE includes tools to create and use


projects and workspaces. A workspace stores all the
settings for a project so that you can swap between
projects with the minimum of effort. The Project Wizard
allows projects to be easily created with a few mouse
clicks. You can conveniently add and remove files in a

11
project using the Project Window view.

Editor

The editor is an integral part of the MPLAB IDE and provides many features that makes writing
your code easy: syntax highlighting, automatic indentation, brace matching, block commenting,
bookmarks, and many others.

In addition the editor window directly supports the debugging tools showing the current execution
position, break and trace points, mouseover viewing of variables, etc.

3.2 Language Tools


Assembler/Linker

MPLAB IDE includes the MPLAB ASM30 assembler and the MPLAB LINK30 linker based on the
industry standard GNU toolsuite. This allows you to develop code without the need to purchase
any additional software. ASM30 assembles source files into object files that the linker converts to
an output hex file along with any library (archive) files that may be included in the project.

Compilers

For those who need a C compiler, Microchip offers the MPLAB C30 compiler. Available for
purchase separately, C30 allows your code to be more portable, readable, and maintainable. And
C30 can be used from within MPLAB to give the user seamlesly integrated code development,
debugging and programming.

Aside from MPLAB C30, compilers that support dsPIC are also available from third-party
manufacturers. Hi-Tech Software, www.htsoft.com, a popular maker of PIC compilers, has a
compiler that supports the dsPIC family of Digital Signal Controllers.

For those who have programmed using Hi-Tech’s PICC or PICC-18 compilers, PICC-30 would be
a logical choice. Instead of having to learn a whole new compiler, Hi-Tech’s C compiler would
offer the most flexibility in migrating your code to the dsPIC.

Template, Include and Linker Script files

Want to start writing some code, but don’t know how to begin? Then take a look at the template
files in the dsPIC_Tools subdirectory of MPLAB IDE. These templates can be copied and used to
form the basis of your own code. You’ll also find processor include files; they define all the
register and bit names and their locations, consistent with the data sheet definitions. Linker scipt
files provide the linker with a memory map of the dsPIC devices for proper automatic code and
data placement.

12
Application Notes

Not sure how to implement your design? Just want to brush up on your design skills? Got some
time to kill? Then check our website (www.microchip.com) for the latest Application Notes. We
are always adding more application notes to provide you with examples on how to use the dsPIC
devices in an ever-expanding array of applications.

3.3 Debuggers/Emulators
Three different debugging tools can be used with MPLAB IDE: THE SIMULATOR, the ICD2, and
the ICE4000. All of these debuggers give you the ability to step through code, run till you halt or
hit a breakpoint, watch registers update, and view memory contents. Each has its own particular
advantages and disadvantages.

MPLAB SIM

The MPLAB SIM simulator is a powerful


debugging tool included with MPLAB
IDE. The simulator runs on the PC and
simulates code execution in the dsPIC.
Not only can the simulator be used to
mimic code execution, but it can also be
used to respond to simulated external
inputs, peripheral operations, and
measure code execution time.

It is a very quick and easy way to debug


code without needing external hardware.
It is particularly useful for testing
mathematical operations and DSP
functions where it can be provided
repeatable data from a file. It can be a
challenge to test code on an analog
signal in real hardware because of the
difficulty in duplicating the data. By
supplying sampled or synthesized data
as stimulus, testing is made easier.

The simulator has all the basic


debugging features and some more advanced features:

• Stopwatch – for timing code execution.


• Stimulus – for simulating external inputs and data reception.
• Trace – for viewing recorded execution.

MPLAB ICE4000

The MPLAB ICE4000 In-Circuit Emulator is a full featured


emulator capable of emulating all of the dsPIC30F devices at full
speed. It is the most powerful debugging tool we offer and gives
excellent visibility into the processor. It is fully integrated into
MPLAB and has a USB interface for fast data transfer. This
allows MPLAB to update memory and data views very quickly.

13
It is a modular system that supports a variety of processors and package options. Please use the
Product Selector Guide (available on our website www.microchip.com) to select the correct
Processor Module, Device Adapter and Transition Socket to emulate the particular device that
you wish to use.

The ICE4000 has all the basic debugging features and many more advanced features:

• Complex trigger settings – to detect sequences of events such as writes to registers.


• Stopwatch – for timing code execution.
• Trace – for viewing recorded execution.
• Logic probes - to trigger on external signals and generate triggers for test equipment.

MPLAB ICD2

The MPLAB ICD 2 In-Circuit Debugger (DV164005) is a very cost


effective debugging tool that allows code to be tested on the
target circuit board. For those who don’t want the added costs
associated with an ICE4000 and can do without its sophisticated
features, the ICD 2 is a viable alternative.

The ICD2 allows you to debug dsPIC devices directly in your


target board. You can also use it to program devices in circuit. It
lacks some of the features of the emulator such as trace memory
and complex triggers but has the basic debugging functions.

However, you give up many of the features the ICE4000 has. This can be clearly seen in the
comparison chart on the following page.

Debugger Comparison Chart

ICE 4000
ICD2 Pros:
y Real-Time Emulation
y Real-Time Watch Windows
Pros: y Complex Triggers
y Low Cost y Logic Analyzer Trigger
y Debug on Target Processor Pros:
y Also a Development Programmer y Debug on Target Cons:
Board y Different modules required to
Cons: emulate different processors
y Lose Chip Resources for Debug (sold separately)
y Cost
y Watch Windows
y Registers update
w/ a click
y Breakpoints
y Single Stepping Pros:
y Halt midst y No Target
execution Board Needed
y View Memory y Programmable
Contents Clock Speed
y Unlimited
Breakpoints
y Measure code
execution time
(Stopwatch
feature)

Pros:
y FREE (Built Into MPLAB IDE)
y Stimulus Files allow simulation of peripherals and inputs

Cons:
y Cannot respond to actual board-level signals

SIM30

14
3.4 Programmers
Three different programmers can be used with MPLAB IDE to program dsPIC devices: PM3,
PICSTART Plus and ICD2. Each has its own particular advantages and disadvantages.

The PM3, can program all packages types and has more programming options and memory.
They can also program parts in-circuit. The PICSTART Plus is a development programmer that
only programs parts in DIP packages. The ICD 2 is an in-circuit debugger that can also program
parts in circuit.

Note: As a general rule, the PM3 is best for production programming. The ICD2 is best for
testing code during development, if the boards support in-circuit programming.

The older PROMATE II programmer also supports the dsPIC devices but has been superceded
by the newer PM3.

MPLAB PM3

The MPLAB PM3 (DV007004) is the preferred choice for


those wanting to purchase a production programmer. It
consists of a basic programmer unit and various socket
modules to support various packages.

• Can be controlled from MPLAB, a command line utility


or operate stand-alone.
• Built in support for in-circuit serial programming.
• Serialized programming for unique ID numbers.
• Safe mode for code security.
• High speed programming and download through USB.
• Secure Digital and Multimedia card slot – for convenient program storage.

MPLAB ICD2

In addition to being an in-circuit debugger, the MPLAB ICD2 (DV164005) can also be used as a
low-cost development programmer. You can use it to program DIP packages out of circuit with
our Universal Programming Module (AC162049), as well as in-circuit, directly on your target
board.

PICSTART Plus

The PICStart Plus (DV003001) can program parts in DIP packages of up to


40 pins in a Zero Insertion Force (ZIF) socket on the programmer. It did not
support dsPIC devices at the time of writing but support will be added. It
interfaces to MPLAB via a serial port.

Note: The PICSTART Plus programmer should not be used to


program parts in-circuit. The power supply and pin drivers
are not designed to drive more than a chip in the socket.
3.5 Demo Boards
Several demonstration boards are available to simplify code development and testing. The
boards are very useful for new users to get started with the dsPIC processors because they have
example code and tutorials.

Note: Nearly all the example code in this Getting Started Guide will run on the lowest cost
demo board, the dsPICDEM Starter Demonstration Board (DM300016).

dsPICDEM Starter Demonstration Board

The dsPICDEM Starter Demonstration Board


(DM300016) is the lowest cost demo board for the
dsPIC devices. It uses a dsPIC30F6012 processor
and has a connector for programming and
debugging with the ICD 2. It also has the following
features:

• RS232 interface for use with the UART


• Switches and LEDs for I/O
• Analog output controlled via a digital pot
• Analog input from potentiometer
• Buffered external analog input
• Wirewrap area for prototyping

dsPICDEM 1.1 General Purpose Development Board

The dsPICDEM 1.1 General Purpose D evelopment Board (DM300014) is a more sophisticated
general purpose demo board. It uses a dsPIC30F6014 processor and has the following features
in addition to most of the features of dsPICDEM Starter Demonstration Board:

• Graphic and text LCD display module


• Header pins for ICE4000 device adapter
• Controller Area Network (CAN) interface
• RS-422 and RS-485 UART interface
• CODEC analog input and output for use with the DCI interface

dsPICDEM MC1 Motor Control Development Board

The Motor Control Development System provides the application developer with three main
components for quick prototyping and validation of BLDC, PMAC and ACIM applications. The
three main components are:

• dsPICDEM MC1 Motor Control Development Board (DM300020)


• dsPICDEM MC1L 3-Phase Low Voltage Power Module (DM300022)
• dsPICDEM MC1H 3-Phase High Voltage Power Module (DM300021)

The dsPICDEM MC1 Motor Control Development Board contains a


dsPIC30F6010 and supports a custom interface header which allows different motor power
modules to be connected to the PCB. The control board also has connectors for mechanical

16
position sensors, such as incremental rotary encoders and hall effect sensors, and a breadboard
area for custom circuits.

The dsPICDEM MC1L 3-Phase Low Voltage Power Module is optimized for 3-phase motor
applications that require a DC bus voltage less than 50 volts and can deliver up to 400W power
output. The 3-phase low voltage power module is intended to power BLDC and PMAC motors.

The dsPICDEM MC1H 3-Phase High Voltage Power Module is optimized for 3-phase motor
applications that require DC bus voltages up to 400 volts and can deliver up to 1 kW power
output. The high voltage module has an active power factor correction circuit that is controlled by
the dsPIC30F device. This power module is intended for AC induction motor and power inverter
applications that operate directly from the AC line voltage.

dsPICDEM.net™ 1 and dsPICDEM.net 2

The dsPICDEM.net 1 Development Board (DM300004-1) and


dsPICDEM.net 2 Development Board (DM300004-2) provide the
application developer a basic connectivity platform for developing
and evaluating various connectivity solutions, implementing TCP/IP
protocol layers, combined with V.22bis/V.22 ITU specifications
across PSTN or Ethernet communication channels.The board
comes with an ITU-T compliant V.22bis/V.22 modem
demonstration program loaded on the installed dsPIC30F6014
device. This program enables the user to connect and transfer data
between the dsPIC®Soft Modem (dsPIC SM) and an ITU-T compliant reference modem.Control
of the dsPIC SM is supported via AT commands communicated using the on-chip UART
channel.Also included are CMX-Micronet WEB and FTP Server demonstration files which when
downloaded into the dsPIC30F6014 device demonstrate two TCP/IP stack-based applications
over the Ethernet Datalink layer. Finally, a simple tutorial written in C code is provided which can
be run with both MPLAB®ICD 2 and MPLAB ICE 4000 development tools.

Both dsPICDEM.net 1 & 2 support the dsPIC30F5013 and dsPIC30F6014 devices and have Ethernet and
PSTN interfaces. The dsPICDEM.net 1 supports FCC/JATE PSTN and the dsPICDEM.net 2 supports CTR-
21 PSTN.

17
4 The MPLAB Integrated Development Environment
4.1 MPLAB IDE Overview
Now that you’ve been introduced to the dsPIC and it’s development tools, you’re probably itching
to write some code. As discussed in the last chapter, the MPLAB IDE software is used throughout
the whole code development process – for writing, compiling, debugging, and programming. It
has the following main features:

• Project Manager – for organizing code files


• Editor – for typing code
• Assembler and Linker – for assembling and building code
• Compiler Interface – for compiling code with separate compilers
• Simulator – for testing code operation
• Debugger/Emulator Interface – for testing code with separate debugger or emulator
• Programmer Interface – for programming parts with separate programmer

Instead of wasting time with a dry, boring discussion of these features, let’s do a quick tutorial.
Learning by doing is always better!

First install and run the latest MPLAB IDE software. No kidding – this step is important. The latest
version of MPLAB can be obtained from the Microchip Technology website (www.microchip.com).

4.2 Creating a Project


Projects and Workspaces

Generally, everything in MPLAB IDE is done within a project.

A project contains the files needed to build an application (source code, linker script files, etc.)
along with their associations to various build tools (language tools, linker) and build options (the
settings for those tools).

A workspace contains one or more projects and information on the selected device, debug tool
and/or programmer, open windows and their location, and other IDE configuration settings.
Usually, you will have one project in one workspace.

MPLAB IDE’s Project Wizard is a great way to create new projects, making it a very simple
process.

Before starting, please create a folder for the project files for this tutorial. The folder “C:\Tutorial”
is being used in the instructions that follow. Copy the “Flash LED with timing loop and switch
press.s” file and the “Software delay loop.s” file into the “C:\Tutorial” folder. These files are
supplied with this “dsPIC Getting Started Guide” document. If the files are copied from a CD, they
have read only attributes; remember to change the attributes if the file needs to be edited.

Now, start MPLAB IDE and close any open workspace with the File>Close Workspace menu.
Then, use the Project>Project Wizard menu to start the Project Wizard. A Welcome screen
should appear; click the Next button to continue.

18
Step 1 - Select a Device

The next screen allows the part to be chosen. Select dsPIC30F6012 from the pull-down.

Click the Next button to continue.

Step 2 - Select a Language Toolsuite

The next screen allows you to select the toolsuite. Select the Microchip ASM30 Toolsuite from
the pull-down. Check that that the location of the assembler and linker are:

• C:\Program Files\MPLAB IDE\dsPIC_Tools\Bin\pic30-as.exe


• C:\Program Files\MPLAB IDE\dsPIC_Tools\Bin\pic30-ld.exe

These tool locations assume that MPLAB was installed with the default settings.

Click the Next button to continue.

19
Step 3 - Name the Project

The next screen allows you to name the project. Type in MyProject for the project name and
browse to or type C:\Tutorial for the project directory.

Click the Next button to continue.

Step 4 - Add Files to the Project

The next screen allows you to add files to the project. Select the “Flash LED with timing loop
and switch press.s” file and the “Software delay loop.s” file and click the Add>> button to
include the files in the project.

Navigate to the “C:\Program Files\MPLAB IDE\dsPIC_Tools\support\gld” folder. Select the


p30f6012.gld file and click the Add>> button to include the file in the project.

20
There should now be three files in the project. Click the Next button to continue and then click the
Finish button when the summary screen appears.

After the project wizard completes, MPLAB IDE


will have a project window showing the “Flash
LED with timing loop and switch press.s”
file and the “Software delay loop.s” file in the
Source Files category and the p30f6012.gld
file in the Linker Scripts category.

If you realize that you have forgotten to add


files to your project, you don’t have to restart
the Project Wizard. Simply right-click on a
category in the project tree, select Add Files
from the drop down menu and browse till you
find the file you want to add. You can remove
files by right-clicking on the file name and selecting Remove.

A project MyProject.mcp and workspace MyProject.mcw have now been created in MPLAB
IDE. Double-click the “Flash LED with timing loop and switch press.s” file in the Project
window to open the file. MPLAB IDE should now look similar this:

Editor

There are several features provided in the editor in MPLAB IDE that makes writing code a much
smoother experience. These features include:

• Syntax highlighting

21
• View and print line numbers
• Search through all project files or within a single file
• Bookmark and jump to specific lines
• Double-click on error message to go to the line of code
• Block commenting
• Brace matching
• Variable font and font size

Syntax highlighting is an especially useful feature of MPLAB IDE. Instead of reading through a
dull, black and white file, code elements such as instructions, directives, registers, etc., appear in
different colors and fonts. This allows you to easily interpret your code, and notice mistakes more
quickly.

4.3 Building the Code


Assembling and Linking

Building a project consists of two steps. The first is the Assemby or Compile process, where each
source file is taken and converted into an object file (with a .o extension) containing opcodes, or
dsPIC instructions. These object files can be used to form libraries, added to other projects as
code modules, or used to generate the final hex file, which is used to program the dsPIC.

The second step in the building process is the Link stage. During the link stage, all of the dsPIC
instructions and variables from the various object and library files are placed in memory according
to the memory map provided by the the linker script file.

The linker will create two files:

1. The .hex file, which is a listing of the data to be placed in the dsPIC’s program, EEPROM and
configuration memory memory.
2. The .cof, or COFF file, which stands for Coded Object File Format, contains additional
information that is necessary to debug your source code.

Include Files

Before building, you must tell MPLAB IDE


where to find the include files. Near the
top of the “Flash LED with timing loop
and switch press.s” file you’ll see the
line:

.include "p30f6012.inc"

The “p30f6012.inc” file contains symbolic


information that is needed to refer to
special function register bits by name
rather than fairly meaningless numbers.
To let MPLAB know where to find this file,
use the Project>Build Options>Project
menu and click the Browse button next to
the Assembler Include Path, $(AINDIR):
field.

Browse to the “C:\Program Files\MPLAB


IDE\dsPIC_Tools\support\inc” folder

22
and click select. This is the directory where MPLAB keeps the include files for all the dsPIC
devices that it supports. Then click the OK button to save the information.

Building the Project

The project is now ready to be built and this can be done using the Project>Make menu. The
results of the build will appear in the Output window and this should indicate
that the build succeeded

Configuration Bits

The code can contain configuration bit settings, specified with config directives. In this simple
example, we must set up the configuration bits ourselves before we can program or debug the
code properly. Use the Configure>Configuration Bits menu to open the Configuration Bits
window. You can edit the settings by clicking on the text in the Setting column. The following
configuration bit settings will work on the dsPICDEM Starter Demo Board.

23
Now that you have built the project successfully, it is time to debug the code. There are several
tools that can be used for debugging. If you want to debug using the Simulator, then please go
straight to Chapter 5 for a tutorial on the simulator. If you wish to use the In-Circuit Debugger
(MPLAB ICD 2) then skip ahead to Chapter 6. To use the ICE4000 In-Circuit Emulator, go to
Chapter 7.

24
5 The MPLAB Simulator
So, you want to test your code but don’t want to bother setting up any hardware? Then SIM30 is
for you! MPLAB SIM30 is fully integrated into the MPLAB IDE environment. It is capable of
mimicking your code execution on hardware without the need for expensive overhead. You can
test external inputs, peripheral transactions and see internal signals on your processor without
having to spend any money.

There are limitations to SIM30. The simulator is not capable of reacting to or producing any real
world signals. It can’t beep buzzers, blink LEDs or interact with other processors. Still, it gives
your much flexibility in developing your code and working out all of its kinks.

The MPLAB SIM30 simulator allows you to:


• modify code and immediately re-execute it
• inject external stimuli to the simulated processor
• set register values at pre-specified intervals

The dsPIC devices have I/O pins multiplexed with other peripherals (and therefore referred by
more than one name). The simulator recognizes only the pin names specified in the standard
device headers as valid I/O pins. Therefore, you should refer to the header file for your device
(e.g. p30F6012.inc or p30F6012.h) to determine the correct pin names.

This chapter will discuss how to use the simulator. First we will open the project that we created
in the Making a Project section of the tutorial. If you have not yet completed this step, please refer
to that section now. We will use the simulator to step through our code, create breakpoints, use
the stopwatch feature, and apply stimulus.

5.1 Opening the Project


If it is not already open, open the workspace we created in Chapter 4, by selecting File>Open
Workspace. The workspace name should be visible in the title bar of the Project window. The
name of the project should be visible inside the Project window at the top of the display. A tree
structure listing file types will appear as shown below.

MPLAB IDE window after opening the Workspace.

5.2 Selecting the Simulator


Select the Debugger>Select Tool>MPLAB SIM30 menu to enable the MPLAB SIM30 simulator.
When you do this, simulator operations will be added to menus and tool bars. The standard
debugging operations plus Stopwatch, Stimulus Controller and SCL Generator will be added to
the Debugger window in the MPLAB IDE.

25
Selecting the Simulator.

5.3 Debugger Settings


In the MPLAB IDE environment, go to Debugger>Settings. On the “Osc/Trace” tab, set the
Processor Frequency for 4 MHz (since there is a 4 MHz crystal on our the Starter Demo Board)
and click on the “Trace Enable” checkbox (we will be using the Trace feature later on).

SIM30 Settings

Now click on the “Debugger Animation” tab. Here we can set the Animate speed. We will
discuss the Animate feature a little later, but for now, let’s set the Animate Step Time to 0ms, so
it’s stepping at its fastest.

5.4 SFR, File Register, and Watch Windows


Three windows are available to display Data Memory values: Special Function Register (SFR),
File Register and Watch. These windows are found under the View menu.

Select View>Watch to open a new Watch window.

26
Watch Window

2. Enter PORTD in the SFR (Special Function Register) selection box at the top of the window.
Click Add SFR to add it to the Watch window list. You can also type the register name directly
into the Watch window.

3. Repeat Step #2 for PORTC, TRISD, and TRISC.

Watch window with all ports.

You should now have four special function register (SFR) symbols in the Watch window. The first
column is the symbol’s Address, followed by the Symbol Name, and finally the Value of the
symbol.

5.5 Walking Through Code


You will now run your program. Once you selected SIM30, the Program Counter should be at the
reset vector. If it isn’t, you can force a reset by selecting Debugger>Reset>Processor Reset.

There are 4 types of Reset, selectable by the Debugger menu:


- MCLR (MCLR Reset)
- BOR (Brown-Out Reset)
- WDT (WatchDog Timer Reset)
- Processor Reset (POR or Power On Reset)

Select Debugger>Run to run your applications. “Running…” should appear in the status bar.

27
It may appear as if your program is doing nothing. Select Debugger>Halt to stop the program
execution. Notice that MPLAB IDE will not update any of its windows until it is Halted. (The
exception to this is the Animate feature, discussed a little later.)

Open the main assembly source file, “Flash LED with Timer1 and Switch Press.s”,
in the project, if it is not already open. Bring this file into focus by clicking on the file name in your
project tree.

There are four distinct methods of stepping through your code, all found under the Debugger
menu: Step Into, Step Over, Step Out, and Animate.
- The Step Into feature will single step through your code, executing the current instruction and
then halt. If the current instruction is a subroutine or function call, the Program Counter
should appear at the top of the called function.
- The Step Over feature will execute up to the next program counter location. It is just like the
Step Into feature for many instructions. However, if the instruction is a call, it will execute the
called subroutine (or function) in its entirety, and then return.
- The Step Out feature allows you to exit a subroutine or function.
- The Animate feature quickly steps through your code, executing instructions until you Halt.
Animate is the only stepping mode that updates MPLAB IDE’s windows.

The Special Function Register, File Register and Watch windows are not updated while the
dsPIC is running; they are only updated when the processor is halted.

5.6 Breakpoints
SIM30 gives the user the ability to set breakpoints: places in the code where execution is halted.
You can set breakpoints directly in your source, in the Program Memory window, or in the
Disassembly window.

In this example, let’s put a software breakpoint where PORTD is written (this will show where the
PORTD pin is toggling). If it is not already open, double-click “Flash LED with timing loop and
switch press.s” from your Project Window. Scroll down to line 43, “btg LATD, #4 ;Toggle LED
RD4” instruction. To the left of this piece of code, place your cursor, then right mouse click, and
then Select Breakpoint. (You can also set a breakpoint by double-clicking on the line.)

Now press Debugger>Run. The program will execute up to (and including) this line, toggling
LED RD4.

28
Setting a breakpoint.

5.7 Watch Window


Now click Debugger>Run to execute your program until the breakpoint. Observe the Watch
window to see your symbol values change. You will notice that changed values appear in red,
whereas unchanged values are black. Observe the changes in the Watch Window and on your
target board as you use one of the stepping methods to walk through your program. You should
see a green arrow in the gutter of the file window, indicating the current point of execution.
Continue to Run to this breakpoint.
We can see that the PORTD pin 4 is toggling in the Watch window as expected.

Watch window with PORTD changing.

Now run your program to line 42 of the code (the CALL instruction). You can do this by setting a
breakpoint, or by stepping through your code. Experiment with the Step Into, Step Out, and Step
Over commands. In this instance, using the Step Into feature alone would not be desirable, since
it would take quite a long time to complete the subroutine.

29
Note that in this example, there is no external hardware for the ICE4000, therefore we can not
push the button on S2 or see the LEDs flash.

5.8 Stopwatch
We can also measure the execution time between two events by using the Stopwatch feature.

Open the Stopwatch feature by clicking Debugger>Stopwatch.


Click Debugger>Run. The green arrow will stop at the breakpoint in the code.

The Zero button clears out the “Stopwatch” column of values.


The Synch button updates the “Stopwatch” column to match the “Total Simulated” column.
The “Stopwatch” column displays the amount of time since the stopwatch was last zeroed out,
while the “Total Simulated” column indicates time since last reset.

Stopwatch

5.9 Trace
The simulator has a handy feature called a Trace buffer, found under the View>Trace.
It holds a list of the instructions that have executed, and can hold over 65,000 instructions!

Trace

5.10 Applying Stimulus

30
SIM30 is capable of simulating external events such as the toggling of I/O pins. It can also
simulate peripheral functions such as A/D conversions or serial communication (UART/I2C/SPI).
This external stimulation is managed using the Stimulus Controller.

The Simulation Control Language, or SCL, allows you much flexibility in the application and
timing of these stimulus events. To ease with the creation of these stimulus files, MPLAB IDE
provides an SCL Generator. This Generator makes it possible to create stimulii, without the need
to understand the SCL language. The created SCL files can then be "attached" to your
simulation, using the Stimulus Controller.

For simpler stimulus, there is the Asynchronous Stimulus dialog, found on the Stimulus
Controller. This is what we will use to simulate pushing the S2 pushbutton switch on the dsPIC
Starter Demo Board.

Switch S2 is connected to the RC13 pin of the dsPIC. The switch is Active Low, meaning the pin
is low when the button is pressed, or on, and high when it is off. Add two Asynchronous stimulii,
as shown in the Figure below.

Now reset your code, by going to the Debugger>Reset>Processor Reset menu. Now press the
"Fire" button, next to the first stimulus. This sets the inactive state of the pin as high. Now
experiment firing the second stimulus at various points in your program. One good place is the
first instruction in the MainLoop:. You should see that when S2 is pressed, RD7 is high,
indicating the LED is on, and RD7 is low when not pressed.

Stimulus Controller

31
6 The MPLAB ICD 2 In-Circuit Debugger
The ICD2 is a development level programmer and In-Circuit Debugger. Although not as powerful
as an ICE (In-Circuit Emulator), it offers quite powerful debugging features.

The ICD2 allows you to execute your code on the actual target chip. You can run at full speed or
step one instruction at a time. You can view and modify register contents on the fly, as well as
set breakpoints in your source code. For the price, it can’t be beat.

This chapter discusses how to use the ICD2.


First we will open the project that we created in the Making a Project section of the tutorial.
If you have not yet completed this step, please refer to that section now.

6.1 Installing the USB Driver


If you do not have a USB port, skip to Section 4.2, for information on configuring the serial port.

When you installed MPLAB IDE, the instructions for installing the USB drivers were presented. If
you closed these instructions, they may be found in your MPLAB IDE installation
directory\Driversnn where nn represents the version of Windows.

There is also a pre-installer utility available that makes installing the USB drivers a snap. These
instructions can be found in the Utilities\MPUsbIRU directory of the MPLAB IDE installation.

Once you’ve installed the USB drivers, you should be able to see it listed under “Universal Serial
Bus controllers” in the Device Manager. Device Manager can be found by going to the Start
button, then choosing Settings>Control Panel>System. On the Hardware tab, you will see a
button for “Device Manager”.

32
The Hardware tab

Device Manager

6.2 Setting up the Serial Port


To use the serial port with the ICD2, we must check the COM port settings.

These settings are controlled on your PC through the Device Manager. Device Manager can be
found by going to the Start button, then choosing Settings>Control Panel>System. On the
Hardware tab, you will see a button for “Device Manager”.

33
The Hardware Tab

Device Manager

34
Go to Ports (COM & LPT). Select the serial port you are using, and clicking on Port Settings.
Make sure “Flow Control” is set to Hardware. Then click on “Advanced” and disable the FIFO
buffers (uncheck the box).

Flow Control

FIFOs

If any changes are made, you must restart your computer.


When using the serial port, a 9VDC power supply must be connected to the ICD2.

35
6.3 Opening the Project
If it is not already open, open the workspace we created in Chapter 4, by selecting File>Open
Workspace. The workspace name should be visible in the title bar of the Project window. The
name of the project should be visible inside the Project window at the top of the display. A tree
structure listing file types will appear as shown below.

MPLAB IDE window after opening the Workspace.

6.4 Selecting the ICD2


Connect your PC to the ICD2, via either USB or serial. Next, apply power to either your target
board or the ICD2. Finally, connect the ICD2 to your target board using the RJ-11 (phone) cable.

Enable the ICD2 as a debugger, by clicking the Debugger>Select Tool>MPLAB ICD2 menu.
When you do this, standard operations, as well as ICD2-specific ones, will be added to the menus
and toolbars.

When first enabling the ICD2, a wizard will appear that walks you through the ICD2 settings. The
wizard makes setting up the ICD2 painless, asking you…..

Connect to your target board, by selecting Debugger>Connect. The Output window should now
indicate that the ICD2 is connecting to your target board. Now, you will now need to program the
dsPIC with your code. Select Debugger>Program to program the device.

Note: It is important that you program the device from the Debugger menu.
Failure to do so may arise in debugging errors.

6.5 Debugger Settings


In the MPLAB IDE environment, go to Debugger>Settings and click on the Communication Tab.
Select the COM port you are using.

36
Communications tab

While you are still under the Debugger>Settings window, click on the Power tab.
You will see a checkbox which states, “Power Target Circuit from ICD2”.

The USB port supplies enough power for the ICD2 only.
If you wish to power the target circuit from the ICD2, a 9VDC power supply must be connected to
the ICD2. If you power the target board separately, a power supply is not necessary.

Note: The USB cable should be connected to the ICD2 before connecting it to power.
Connecting in reverse order can prevent the ICD2 from being seen.

When using the serial port, a 9VDC power supply must be connected to the ICD2.

You must ensure that you have the appropriate power setting selected

Power tab

37
6.6 SFR, File Register, and Watch Windows
Three windows are available to display Data Memory values: Special Function Register (SFR),
File Register and Watch. These windows are found under the View menu. Using the SFR and
File Register windows can slow down ICD2 communications. Therefore, it is recommended that
registers and variables of interest be added to the Watch window.

Select View>Watch to open a new Watch window.

Watch Window

2. Enter PORTD in the SFR (Special Function Register) selection box at the top of the window.
Click Add SFR to add it to the Watch window list. You can also type the register name directly
into the Watch window.

3. Repeat Step #2 for PORTC, TRISD, and TRISC.

Watch window with all ports.

You should now have four special function register (SFR) symbols in the Watch window. The first
column is the symbol’s Address, followed by the Symbol Name, and finally the Value of the
symbol.

38
6.7 Walking Through Code
You will now run your program. Once you selected the ICD2, the Program Counter should be at
the reset vector. If it isn’t, you can force a reset by selecting Debugger>Reset.

Select Debugger>Run to run your applications. “Running…” should appear in the status bar.

You should now see the RD4 LED on your dsPIC Starter Demo Board blinking. If you press S1,
the RD7 LED should light up. Switch S3 is the reset button; holding it down will cause the LEDs
to stop blinking and will hold the chip in a reset state.

Select Debugger>Halt to stop the program execution. Notice that MPLAB IDE will not update
any of its windows until it is Halted. (The exception to this is the Animate feature, discussed a
little later.)

Open the main assembly source file, “Flash LED with Timer1 and Switch Press.s”,
in the project, if it is not already open. Bring this file into focus by clicking on the file name in your
project tree.

There are four distinct methods of stepping through your code, all found under the Debugger
menu: Step Into, Step Over, Step Out, and Animate.
- The Step Into feature will single step through your code, executing the current instruction and
then halt. If the current instruction is a subroutine or function call, the Program Counter
should appear at the top of the called function.
- The Step Over feature will execute up to the next program counter location. It is just like the
Step Into feature for many instructions. However, if the instruction is a call, it will execute the
called subroutine (or function) in its entirety, and then return.
- The Step Out feature allows you to exit a subroutine or function.
- The Animate feature quickly steps through your code, executing instructions until you Halt.
Animate is the only stepping mode that updates MPLAB IDE’s windows.

The Special Function Register, File Register and Watch windows are not updated while the
dsPIC is running; they are only updated when the processor is halted.

6.8 Breakpoints
The ICD2 gives the user the ability to set breakpoints: places in the code where execution is
halted. You can set breakpoints directly in your source, in the Program Memory window, or in the
Disassembly window.

In this example, let’s put a software breakpoint where PORTD is written (this will show where the
PORTD pin is toggling). If it is not already open, double-click “Flash LED with timing loop and
switch press.s” from your Project Window. Scroll down to line 43, “btg LATD, #4 ;Toggle LED
RD4” instruction. To the left of this piece of code, place your cursor, then right mouse click, and
then Select Breakpoint. (You can also set a breakpoint by double-clicking on the line.)

Now press Debugger>Run. The program will execute up to (and including) this line, toggling
LED RD4.

39
Setting a breakpoint.

6.9 Advanced Breakpoints


The ICD2 also has the ability to perform more complex breakpoints. This dialog can be found by
clicking on the Debugger>Advanced Breakpoints menu. Press the Help button on this dialog
for more information on this feature.

Advanced Breakpoints

40
6.10 Watch Window
Now click Debugger>Run to execute your program until the breakpoint. Observe the Watch
window to see your symbol values change. You will notice that changed values appear in red,
whereas unchanged values are black. Observe the changes in the Watch Window and on your
target board as you use one of the stepping methods to walk through your program. You should
see a green arrow in the gutter of the file window, indicating the current point of execution.
Continue to Run to this breakpoint.
We can see that the PORTD pin 4 is toggling in the Watch window as expected.

Watch window with PORTD changing.

Now run your program to line 42 of the code (the CALL instruction). You can do this by setting a
breakpoint, or by stepping through your code. Experiment with the Step Into, Step Out, and Step
Over commands. In this instance, using the Step Into feature alone would not be desirable, since
it would take quite a long time to complete the subroutine.

You should now have a good idea of how the ICD2 works and some of its commonly used
features. More information is available in the ICD2 User’s Guide and the MPLAB IDE online help.

41
7 The MPLAB ICE 4000 In-Circuit Emulator
MPLAB ICE 4000 is an In-Circuit Emulator (ICE) designed to emulate PIC18 and dsPIC devices.
It provides full-speed emulation and visibility, into both the instruction and the data paths during
execution.

MPLAB ICE 4000 performs basic functions such as run, halt, single step, and software
breakpoints, plus advanced features such as instruction/address data monitoring, instruction data
trace, complex triggering and code coverage. The ICE4000 can be used either as a pure
emulator, allowing you to debug the internal functions of the processor, or in-circuit to act as the
processor in your target board.

The pod is the interface between the PC and the processor module. It has the hardware in it to
read data from the processor module and send it back to the PC, as well as taking commands
and various other data from the PC and send it to the processor module.

Processor modules are the component which actually emulate the specific device.

Device adapters are interchangeable assemblies that allow the emulator to interface to a target
application system.

Transition sockets are available in various styles to allow a common device adapter to be
connected to one of the supported surface mount package styles

This chapter will discuss how to use the ICE4000. First we will open the project that we created in
the Making a Project section of the tutorial. If you have not yet completed this step, please refer to
that section now. We will use the simulator to step through our code, create breakpoints, and use
the stopwatch feature.

7.1 Installing the USB Driver


When you installed MPLAB IDE, the instructions for installing the USB driver were presented. If
you closed these instructions, they may be found in your MPLAB IDE installation
directory\Driversnn where nn represents the version of Windows.

Note: The ICE4000 must be powered on for the USB port to be recognized.
If it is not turned on, you will not be able to install the USB drivers.

There is also a pre-installer utility available that makes installing the USB drivers a snap. These
instructions can be found in the Utilities\MPUsbIRU directory of the MPLAB IDE installation.

Once you’ve installed the USB drivers, you should be able to see them listed under “Universal
Serial Bus controllers” in the Device Manager. Device Manager is located by going to the Start
button, then choosing Settings>Control Panel>System. On the Hardware tab, select the “Device
Manager”.

42
The Hardware tab

Device Manager

43
7.2 Opening the Project
If it is not already open, open the workspace we created in Chapter 4, by selecting File>Open
Workspace. The workspace name should be visible in the title bar of the Project window. The
name of the project should be visible inside the Project window at the top of the display. A tree
structure listing file types will appear as shown below.

MPLAB IDE window after opening the Workspace.

7.3 Selecting the ICE4000


Insert the processor module firmly onto the top of the MPLAB ICE 4000 pod.
Turn on the ICE4000 power.

Note: Before connecting the emulator system to the target application system, power on
the emulator system (with processor module already inserted), and select Processor
Power from Emulator to allow MPLAB IDE to perform the initialization.

Then, select the Power from Target Board, connect the target board to the emulator
system and apply power to the target board. This will minimize the target system
exposure to reverse current.

Select the Debugger>Select Tool>MPLAB ICE4000 menu to enable the ICE4000 as a


debugger. The standard debugging operations will be added to the Debugger window and
toolbars in the MPLAB IDE.

7.4 Debugger Settings


Open the Debugger>Settings dialog.
Click on the “Power” tab, and set all of the options are set to “From Emulator”.

44
Power Settings

Now click on the “Clock” tab. Change the “Desired Frequency” to 4 MHz and press Apply.
Press OK to accept these settings.

Notice that the “Use Target Clock” checkbox is grayed out. If you wish to use the 4 MHz
oscillator present on the dsPIC Starter Demo board, you must set “Processor Power” to “From
Target Board”.

45
Clock Settings

7.5 SFR, File Register, and Watch Windows


Three windows are available to display Data Memory values: Special Function Register (SFR),
File Register and Watch. These windows are found under the View menu. Using the SFR and
File Register windows can slow down ICE4000 communications. Therefore, it is recommended
that registers and variables of interest be added to the Watch window.

Select View>Watch to open a new Watch window.

Watch Window

46
2. Enter PORTD in the SFR (Special Function Register) selection box at the top of the window.
Click Add SFR to add it to the Watch window list. You can also type the register name directly
into the Watch window.

3. Repeat Step #2 for PORTC, TRISD, and TRISC.

Watch window with all ports.

You should now have four special function register (SFR) symbols in the Watch window. The first
column is the symbol’s Address, followed by the Symbol Name, and finally the Value of the
symbol.

7.6 Walking Through Code


You will now run your program. Once you selected the ICE4000, the Program Counter should be
at the reset vector. If it isn’t, you can force a reset by selecting Debugger>Reset.

Select Debugger>Run to run your applications. “Running…” should appear in the status bar.

You should now see the RD4 LED on your dsPIC Starter Demo Board blinking. If you press S1,
the RD7 LED should light up. Switch S3 is the reset button; holding it down will cause the LEDs
to stop blinking and will hold the chip in a reset state.

Select Debugger>Halt to stop the program execution. Notice that MPLAB IDE will not update
any of its windows until it is Halted. (The exception to this is the Animate feature, discussed a
little later.)

Open the main assembly source file, “Flash LED with Timer1 and Switch Press.s”,
in the project, if it is not already open. Bring this file into focus by clicking on the file name in your
project tree.

There are four distinct methods of stepping through your code, all found under the Debugger
menu: Step Into, Step Over, Step Out, and Animate.
- The Step Into feature will single step through your code, executing the current instruction and
then halt. If the current instruction is a subroutine or function call, the Program Counter
should appear at the top of the called function.
- The Step Over feature will execute up to the next program counter location. It is just like the
Step Into feature for many instructions. However, if the instruction is a call, it will execute the
called subroutine (or function) in its entirety, and then return.
- The Step Out feature allows you to exit a subroutine or function.
- The Animate feature quickly steps through your code, executing instructions until you Halt.
Animate is the only stepping mode that updates MPLAB IDE’s windows.

47
The Special Function Register, File Register and Watch windows are not updated while the
dsPIC is running; they are only updated when the processor is halted.

7.7 Breakpoints
The ICE4000 gives the user the ability to set breakpoints: places in the code where execution is
halted. You can set breakpoints directly in your source, in the Program Memory window, or in the
Disassembly window.

In this example, let’s put a software breakpoint where PORTD is written (this will show where the
PORTD pin is toggling). If it is not already open, double-click “Flash LED with timing loop and
switch press.s” from your Project Window. Scroll down to line 43, “btg LATD, #4 ;Toggle LED
RD4” instruction. To the left of this piece of code, place your cursor, then right mouse click, and
then Select Breakpoint. (You can also set a breakpoint by double-clicking on the line.)

Now press Debugger>Run. The program will execute up to (and including) this line, toggling
LED RD4.

Setting a breakpoint.

7.8 Complex Triggers


The ICE4000 also has the ability to trigger a breakpoint on a complex set of events. This dialog
can be found by going to Debugger>Complex Triggers and Code Coverage. Notice how the
diagram and options change as you select different a “Trigger Type”. This feature gives you a lot
of power in tracking down elusive problems. Press the Help button on this dialog for more
information on this feature.

48
Complex Triggers

Notice also that you have the ability to trigger on complex set of internal dsPIC events, as well as
recording a map of the instructions that have executed, using the Code Coverage feature.

7.9 Watch Window


Now click Debugger>Run to execute your program until the breakpoint. Observe the Watch
window to see your symbol values change. You will notice that changed values appear in red,
whereas unchanged values are black. Observe the changes in the Watch Window and on your
target board as you use one of the stepping methods to walk through your program. You should
see a green arrow in the gutter of the file window, indicating the current point of execution.
Continue to Run to this breakpoint.
We can see that the PORTD pin 4 is toggling in the Watch window as expected.

49
Watch window with PORTD changing.

Now run your program to line 42 of the code (the CALL instruction). You can do this by setting a
breakpoint, or by stepping through your code. Experiment with the Step Into, Step Out, and Step
Over commands. In this instance, using the Step Into feature alone would not be desirable, since
it would take quite a long time to complete the subroutine.

7.10 Stopwatch
We can measure the execution time between two events by using the Stopwatch feature.

Open the Stopwatch feature by clicking Debugger>Stopwatch.


Click Debugger>Run. The green arrow will stop at the breakpoint in the code.

The first column indicates the number of instruction cycles and amount of time since the
processor was last halted. This value can be cleared by pushing the Zero button in the Stopwatch
window.

The second column shows the number of instruction cycles and amount of time since the last
reset of the device. Pressing the Synch button updates the First Column, as if the Zero button
were never pressed.

To reset the second column, the “Clear Simulation Time on Reset” checkbox must be checked
and you must reset the device.
You can do this by clicking on the Debugger>Reset menu, the Reset Button on the toolbar, or by
hitting F6 on your keyboard.

50
Stopwatch

7.11 Trace
The ICE4000 has a handy feature called a Trace buffer, found under the View>Trace.
It holds a list of the instructions that have executed, and can hold over 65,000 instructions!

Trace

51
8 The ASM30 Assembler
Now that you know how to create and build a project, and use the tools to simulate or debug, let’s
spend a little time to learn how to write code. Since the ASM30 assembler is included with
MPLAB IDE, we’ll discuss some of the essentials to using this language tool.

8.1 MPLAB ASM30


The ASM30 assembler is based on open source GNU software and may seem familiar to some
users. The assembler interprets instructions and directives in source code files to generate object
code. A linker (Chapter 10) is used to convert the object code to a final output (Hex) file for
programming a part.

Instructions are code that is executed at run-time in the dsPIC. They are the native language of
the dsPIC processor. Several chapters would need to be devoted to the Instruction Set to cover it
in adequate detail. However, that goes beyond the scope of a simple “Getting Started” document.
For further information about the dsPIC Instruction Set, refer to the “dsPIC30F Programmer’s
Reference Manual”.

Directives are interpreted at build-time by the assembler and are used to define sections of
memory, initialize constants, declare and define symbols, substitute text, etc. A list of directives
and their usage is documented in the "MPLAB ASM30 User's Guide". All directives must be
preceded by a period (.).

We’ll discuss a few of the most commonly used directives, so that you’ll have an idea of what is
required when writing your own code. Many of these directives were used in the example code
from Chapters 4 – 7.

8.2 General Format of Instructions and Directives


Instructions and directives take the following general forms:

[label:] instruction [operands] [; comment]

[label:] directive [arguments] [; comment]

Labels are used to mark locations in code. At link time, labels are evaluated to a memory
address; all label definitions must end with a colon (:) and may begin with a period(.).

Operands are used by instructions to provide source and destination information. They consist of:

• Literals
Literals are hexadecimal, octal, binary or decimal values; all literal values must be
preceded by a number sign (#).
• Registers/Memory Addresses
File Registers (GPRs and SFRs), Working Registers, Accumulators
• Condition Codes
Conditional branch instruction use status bits such as Z (zero) or C (carry) as operands

Arguments are similar to operands, used by directives for source and destination information.

52
Syntax Rules

Character Description Usage


. period begins a directive or label
: colon ends a label
# pound begins a literal value
; semicolon begins a single-line comment
/* begins multi-line comment
*/ ends multi-line comment

8.3 Commonly Used Directives


Listed below are some very commonly used directives. You’ll find the first five directives in our
tutorial from Chapter 4, where we learned how to create and build a project. Although the other
five directives were not present in our tutorial, you may find yourself in need of one of them. That
is why they are listed as examples in the dsPIC template files, provided in the
..\dsPIC_Tools\support\templates\assembly subdirectory of MPLAB IDE.

.equ equates a value to a symbol


.include includes another file into the current file
.global makes a symbol globally visible
.text starts a section of executable code
.end ends assembly within a file
.section starts a section (of code or data, in program or data memory)
.space allocate space within a section
.bss add variables to the uninitialized data section
.data add variables to the initialized data section
.hword declare words of data within a section
.palign align code within a section
.align align data within a section

.EQU

One of the common directives in any assembly source file is .equ. The .equ directive is used to
define a symbol and assign it a value.

If we look at our tutorial project, we can see that we use the .equ directive to assign the symbol
Fcy the literal value of one million. In this context, Fcy is a constant that can be used throughout
your code to represent the instruction cycle frequency.

The processor must be selected before including the standard .inc file in an assembly source file.
Using the .equ directive as shown below allows you to do this. (The processor can also be
selected two other ways, which are described in the standard include file’s comments.)

53
.INCLUDE

The .include directive adds the contents of the specified file into the assembly source, at the
point it’s used. One common use of the .include directive is to add in definitions from the
standard include file.

.GLOBAL

The .global directive is used to allow labels defined within the file to be used by other files. In our
example, the __reset symbol is made global so that the linker can use it as the address to jump
to from the reset vector. The __reset: label is required to signify the start of code and needs to
be present in one of the project’s object files (from assembler, compiler, or library files).

.TEXT

This is a special instance of the .section directive. .text is used to inform the assembler that the
code following it is to be placed in an executable section of program memory.

.END

The .end directive is used to signify the end of an assembly source file.

.SECTION

The .section directive declares a section of memory. This section can be in RAM or in program
memory and this is determined by the parameters that follow the directive. In the example below,
the secdtion is named .xbss and the “b” parameter indicates that the section is in X data memory

54
and is uninitialized. A complete list of section types is in the MPLAB ASM30, MPLAB LINK30
and Utilities User’s Guide and in the dsPIC30F Language Tools Quick Reference Card.

.SPACE

The .space directive instructs the assembler to reserve space in the current section. In the
example below, one byte of memory is reserved for the variable named Var1.

.BSS

The .bss directive is a special instance of the section directive. It causes uninitialized data
variables to be appended to the the an uninitialized data section.

.DATA

The .data directive is a special instance of the section directive. It causes initialized data
variables to be appended to the the an initialized data section.

.HWORD

The .hword directive declares words of initialized data within a section. It can also declare data
within program memory.

.PALIGN

55
The .palign directive aligns data within a program memory section. In the example below, the
variable MyData will start at an even address (exactly divisible by 2).

.ALIGN

The .align directive aligns data within a section. In the example below, the variable Array2 will
start at an address that is exactly divisible by 8. The .align directive is especially useful when
using the modulo addressing feature or the dsPIC30F processor.

8.4 Example code


Having learned about the directives and the format of the instructions, we can now look at an
example to see how it all works. Here is an explanation of the example code used in the previous
chapters. There are two files Flash LED with timing loop and switch press.s and Software
delay loop.s. We will take a detailed look at each of them.

Flash LED with timing loop and switch press.s file

First let’s look at the code in the Flash LED with timing loop and switch press.s file.

The file starts with comments preceded by semicolons (;) This is followed by a definition of the
__30F6012 label to allow the include file to check that the correct processor is being used. The
standard include file is included to define all the bits in the various SFRs.

The Fcy label is equated to a value so that that frequency changes can easily be made. A single
line can now be changed to adapt the code to different oscillator options. This label is not used in
this code, it just serves as an example.

The __reset and Delay100ms labels are made global so that the linker can use these labels to
access functions across different object files.

56
The start of executable code is preceded by a .text directive. This tells the assembler that
executable code follows and should be placed in the default code section. The linker recognizes
the __reset: label as a standard label to branch to after a reset. It must be global for the linker
to use it.

After allocating all the RAM variables, the linker finds the largest available space for the stack and
assigns the start address to the __SP_init label. The code loads this label into the stack pointer
register W15. This sets up the software stack.

The linker also provides the end address of the available stack space and the code loads this
value from the __SPLIM_init label into the SPLIM register. This sets up error checking for
stack overflows. An address error will occur if the stack pointer W15 equals the address in
SPLIM. Notice that this operation is done in two instructions. The W0 register is loaded with the
__SPLIM_init value and this is then moved into the SPLIM register. It is not possible to code a
16-bit literal value and a 13-bit near memory address into one 24-bit instruction.

After setting up the stack, the code initializes an I/O port to drive the LEDs on PORTD. The LEDs
are on bits 4 to 7 of PORTD. The code clears these bits in the port latch register LATD so that
when the I/O pins are turned into outputs the LEDs will be off. The code then clears these same
bits in the port tristate register TRISD so that the I/O pins are turned into outputs. Finally, the
code sets bit 4 of LATD to turn one LED on.

The main code loop starts with a label MainLoop:. It ends with a branch back to MainLoop so it
loops repeatedly. Inside the loop, the code tests the bit 13 of PORTC, the input connected to
switch S1. If S1 is pressed then bit 7 of LATD is set to turn on a LED attached to this pin. If S1 is
not pressed then the LED is turned off. Notice that when an I/O port is used as an input, the
PORTx register is used and when a port is used as an input, the LATx register is used.

57
The code then calls a routine Delay100ms that is declared as global at the beginning of the file.
The linker will assign an address to Delay100ms so that it is called properly. After calling the
delay routine, the code toggles bit 4 of LATD to flash a LED repeatedly.

After the software licence agreement text, there is an .end directive that indicates that there is no
more code to be assembled in this file.

Software delay loop.s file

The second file in the project is Software delay loop.s and it contains the Delay100ms routine. It
is similar to the previous file and starts in the same way by equating a processor label and
including the standard include file.

The code declares that the label for the Delay100ms routine has global visibility so that code in
other files can call the function.

A .text directive indicates that that follows will be executable code.

The Delay100ms routine starts with a label in front of the first instruction. The delay is
implemented by a repeat loop within a do loop. The repeat instruction is followed by a nop that
causes the nop to be executed 9,999 times. The repeat instruction and the nop take 10,000
instruction cycles to execute. Fosc is 1MHz so the repeat loop causes a 10ms delay.

The do instruction causes the code up to the nop at the label Dly100msEnd to be executed ten
times. This includes the 10ms repeat loop so the total delay is 100ms. There are some

58
restrictions on the last instruction in a do loop, so the code uses an extra nop to avoid terminating
the do loop with an instruction within a repeat loop.

Finally, the routine ends with a return instruction so that it returns back to the code from which it
was called.

The file ends with a .end directive after the licence agreement text to indicate that there is no
more code to be assembled.

The assembler always generates object files that need to be linked. To learn about the LINK30
linker and how it takes the code and data from the object files and creates the final output files,
please jump ahead to Chapter 10. If you are going to use the MPLAB C30 compiler, then
proceed to the next chapter, Chapter 9.

59
9 The C30 Compiler
9.1 Introduction
Many of you programming for the dsPIC will do so in C. MPLAB C30 is an ANSI-compliant C
compiler that allows you to write uniform, modular code for the dsPIC that should make it more
portable and easier to understand than writing in assembly. In addition to the advantage of the C
language itself, the libraries offered by C30 make it a powerful compiler. For example,
implementing floating point, trigonometric functions, filters and FFT algorithms can be quite
cumbersome in the assembly language. But with the DSP, peripheral, and standard math libraries
these routines can be called easily. The modularity of the C language reduces the likelihood of
functions interacting.

The intent of this chapter is not to describe the ins and outs of the C language, but rather what
you’ll need to know to be able to get up and running quickly. For detailed information on the
operation of MPLAB C30, examine the “MPLAB® C30 C Compiler User’s Guide”.

9.2 MPLAB C30 projects


We learned about MPLAB projects in Chapter 4 but only used assembly (.s) source files. We will
now see that MPLAB C30 projects are very similar but also use C language (.c) source files and
archive (.a) library files as well.

Recall that building an assembly project is a two step process. The assembly source (.s) files are
each assembled to create object (.o) files and then the object files are linked to create output
(.hex and .cof) files.

Building a C30 project is also a two step process in which C source (.c) files are compiled to
object files and the object files are linked to create output files.

Assembly C Source Files


Source Files (*.c)
(*.s)

MPLAB® MPLAB®
ASM30 C30

COFF List Files COFF List Files


Object Files (*.lst) Object Files (*.lst)
(*.o) (*.o)

In addition to C files, the project may include library files that are linked together with the object
files. The libraries are created from precompiled object files and are essentially functions that can
be used in the project without the need to be compiled.

60
When linking, the LINK30 linker uses the linker script file from the project to know what memory is
available in the chip. It then places all the code and variables from the object files and archive
files into the available memory. It generates output file for programming and debugging.

COFF COFF
Object Files Object Files
(*.o) (*.o)

MPLAB®
LIB30

Library Files
(*.a)

Linker MPLAB®
Script LINK30

Executable COFF Map File


File Debug File (*.map)
(*.hex) (*.cof)

9.3 Creating a Project with the Project Wizard


If you have not already done so, please read Chapter 4 to find out about projects and workspaces
in MPLAB IDE. We will forgo any repetition and jump right into creating a MPLAB C30 project.

First install the MPLAB C30 compiler. The tutorial that follows assumes that it has been installed
to the default location “C:\PIC30_Tools”. If you install it elsewhere, please adjust the paths in the
tutorial accordingly.

Note The tool locations for your environment may be different from those shown here.

Before starting, please create a folder for the project files for this tutorial. The folder “C:\Tutorial”
is being used in the instructions that follow. If you have already created this folder for a previous
tutorial, you can simply add the new file into the folder. Copy the “Flash LED with timing loop
and switch press.c” file into the “C:\Tutorial” folder. These files are supplied with this “dsPIC
Getting Started Guide” document. If the files are copied from a CD, they have read only
attributes; remember to change the attributes if the file needs to be edited.

Now, start MPLAB IDE and close any open workspace with the File>Close Workspace menu.
MPLAB IDE’s Project Wizard is an easy way to create new projects. Use the Project>Project
Wizard menu to start the Project Wizard. A Welcome screen should appear; click the Next button
to continue.

Step 1 - Select a Device

61
The next screen allows the part to be chosen. Select dsPIC30F6012 from the pull-down list and
click the Next button to continue.

Step 2 - Select a Language Toolsuite

Select the Microchip C30 Toolsuite from the pull-down as shown below and click the Next
button to continue.

Step 3 - Name your Project

Type in MyC30Project for the project name and browse to or type C:\Tutorial for the
project directory. Click the Next button to continue.

62
Step 4 - Adding Files to Project

Select the “Flash LED with timing loop and switch press.c” file in the “C:\Tutorial” folder and
click the Add>> button to include the file in the project as shown below.

Navigate to the “C:\PIC30_Tools\support\gld” folder. Select the “p30f6012.gld” file and click
the Add>> button to include the file in the project.

There should now be two files in the project. Click the Next button to continue and then click the
Finish button when the summary screen appears.

After the project wizard completes, MPLAB IDE will have a project window showing the
“Flash LED with timing loop and switch press.c” file in the Source Files category and the
“p30f6012.gld” file in the Linker Scripts category

If, at this point, you realize that you have


forgotten to add files to your project, you
don’t have to restart the Project Wizard.

Simply right-click on the appropriate category in the


Project Tree, click on Add Files, and browse till you
find the file you’re looking to add. You can remove
files by right-clicking on the file name and selecting
Remove.

63
For our project, let’s add the include file mentioned at the top of the “Flash LED with timing
loop and switch press.c” file, “p30f6012.h” as a Header File. You should be able to find it
located in “C:\PIC30_Tools\support\h”.

The labels for the Special Function Registers (SFRs) and bit names are defined in these standard
header files. Microchip provides these files for your convenience, as part of the MPLAB IDE
installation.

A project, MyC30Project.mcp, and workspace, MyC30Project.mcw, have now been created


using MPLAB IDE. Double-click the “Flash LED with timing loop and switch press.c” file in
the project window to open the file.

9.4 Building the Project


Before we can build our project, we need to
set the build options. Some of these
settings are used by MPLAB IDE to:

• locate files (header, library files)


• generate debugging information
• control optimization
• create diagnostics files (map, list files)

Use the Project>Build Options>Project


menu to tell MPLAB IDE where to find the
header files as shown below. Add an
Include Path by browsing to
“C:\PIC30_Tools\support\h” and click the
OK button.

The project is now ready to be built and this


can be done using the Project>Make
menu. The results of the build will appear in
the Output window and this should indicate
that the build succeeded as shown below

64
9.5 Language Features
The C30 compiler is an ANSI C compiler with various extensions to support specific features and
capabilities of the dsPIC devices.

__attribute__ keyword

The C30 compiler uses the __attribute__ keyword (note the double underscore prefix and suffix)
to specify compiler specific actions for functions and variables that cannot be done with standard
C syntax. It can be used to define sections, control how program memory is filled, optimize
functions, specify interrupt functions, etc. It is similar to the #pragma directive used in other
compilers such as MPLAB C18.

Standard Header File

A standard header file such as p30f6012.h used in our example code should always be included
in each C file with a #include statement. The header file contains the declarations for all the
special function registers (SFRs) and their bits so that they can be used in the code. The linker
obtains the addresses of the SFRs from the linker script file, p30f6012.gld in our example.

Pointers

All MPLAB C30 pointers are 16-bits wide. This gives you the ability to access the entire Data
Memory (64 KB) and the near Program Memory (32 Kwords). When pointing to addresses in far
Program Memory (>32 Kwords), pointers may resolve to “handles”. That is, the pointer will point
to a GOTO instruction, which is located in the first 32 Kwords of program space.

X and Y Data Spaces

When doing DSP operations with the dsPIC, it can be useful to retrieve data from the X and Y
data memory spaces. The __attribute__ keyword can be used in this case to define a section in Y
memory where data variables may be stored.

9.6 Example Code


Having learned more about the compiler, we can now look at an example to see how it all works.
Here is an explanation of the example code in the Flash LED with timing loop and switch
press.c file used in the tutorial.

The file starts with comments (preceded by //). The standard header file is then included to define
all the special function registers (SFRs). There is a header file for each dsPIC controller
supported by the MPLAB C30 compiler.

The processor frequency is defined in order to set up the timer later in the code. The symbol Fcy
is given a value in a #define statement.

65
The main() routine starts the executable code and has an integer return value in accordance with
the ANSI C standard. It is imprtant to note that the linker will add startup code that calls the main
routine. The first part of the main routines sets up the an I/O port for the LEDs by initializing the
output latch and turning the LED pins into outputs.

The code then initializes Timer 1 for a ½ second period and turns the timer on.

Inside the main() routine, there is a while(1) loop to ensure that code execution never leaves main
and stops. Inside the infinite loop, the code tests the RC13 input pin to see if Switch S2 is
pressed. If it is pressed, the LED on the RD7 output pin is lit by setting the pin high, otherwise the
LED is turned off.

Also in the main loop, the Timer 1 interrupt flag is tested to see if the timer matched the period
register. Note that the interrupt flag is set by the hardware, even though interrupts are not
enabled. The code clears the interrupt flag and toggles the LED on output pin RD4 whenever the
timer match occurs.

This simple code example and the tutorial should explain the basics of using the MPLAB C30
compiler.

Remember that the compiler generates object files and the LINK30 linker uses the object files to
place the code and variables intoi memory and generate the output files. To learn more about the
linker, please proceed to Chapter 10.

66
10 The LINK30 Linker
The MPLAB LINK30 linker translates object files from the ASM30 assembler, C30 compiler and
archive files from the LIB30 archiver/librarian into an executable COFF file.

C Source Files Assembly Source Precompiled Object


(*.c) Files (*.s) Files (*.o)

C30 Compiler ASM30 Assembler Archiver

Object Files Object Files Library/Archive Files


(*.o) (*.o) (*.a)

Linker Script File LINK30 Linker


(*.gld)

Executable COFF
File (*.cof)

The linker essentially links all compiled and assembled files in the project together to form one
executable file that can be programmed into a part, simulated or emulated. The hex file and map
file are created from the COFF file.

10.1 Linker Script Files


The linker uses a linker script file to know where to locate sections of memory and to know the
memory ranges for a specific part. It supports the construction of interrupt vector tables and the
allocation of the software stack. It also assigns the addresses of the special function registers
(SFRs).

The linker script file has the following categories of information that we will briefly discuss in the
rest of this chapter by looking at the p30f6012.gld file as an example:

• Output File Format and Entry Point


• Memory Region Information
• Base Memory Address
• Input/Output Section Map
• Range Checking for Near and X Data Memory
• Interrupt Vector Tables
• SFR Addresses

Output File Format and Entry Point

67
The first several lines of a linker script define the output format, processor family and entry point:

/*
** Linker Script for p30f6012
*/

OUTPUT_FORMAT("coff-pic30")
OUTPUT_ARCH("pic30")
EXTERN(__resetPRI)
EXTERN(__resetALT)
ENTRY(__reset)

Notice that the entry label is __reset. If you have a global label called __reset in your code,
that will be where the code starts executing.

Memory Region Information

The next section of the linker script file defines the various memory regions for the device. This
tells the linker how much memory is available on the device. Each memory region is range-
checked as sections are added during the link process. If any region overflows, a link error is
reported.

/*
** Memory Regions
*/
MEMORY
{
data (a!xr) : ORIGIN = 0x800, LENGTH = 8096
program (xr) : ORIGIN = 0x100, LENGTH = ((48K * 2) - 0x100)
reset : ORIGIN = 0, LENGTH = (4)
ivt : ORIGIN = 0x04, LENGTH = (62 * 2)
aivt : ORIGIN = 0x84, LENGTH = (62 * 2)
__FOSC : ORIGIN = 0xF80000, LENGTH = (2)
__FWDT : ORIGIN = 0xF80002, LENGTH = (2)
__FBORPOR : ORIGIN = 0xF80004, LENGTH = (2)
__CONFIG4 : ORIGIN = 0xF80006, LENGTH = (2)
__CONFIG5 : ORIGIN = 0xF80008, LENGTH = (2)
__FGS : ORIGIN = 0xF8000A, LENGTH = (2)
eedata : ORIGIN = 0x7FF000, LENGTH = (4096)
}

Base Memory Address

This portion of the linker script defines the starting addresses of several sections into which the
linker will place code or data. Each base address is defined as a symbol and the symbols are
used to specify load addresses in the section map that follows.

68
/*
** Base Memory Addresses - Program Memory
*/
__RESET_BASE = 0; /* Reset Instruction */
__IVT_BASE = 0x04; /* Interrupt Vector Table */
__AIVT_BASE = 0x84; /* Alternate Interrupt Vector Table */
__CODE_BASE = 0x100; /* Handles, User Code, Library Code */

/*
** Base Memory Addresses - Data Memory
*/
__SFR_BASE = 0; /* Memory-mapped SFRs */
__DATA_BASE = 0x800; /* X and General Purpose Data Memory */
__YDATA_BASE = 0x1800; /* Y Data Memory for DSP Instructions */

Input/Output Section Map

The section map is the heart of the linker script file. It defines how input sections are mapped to
output sections. Note that input sections are portions of an application that are defined in source
code, while output sections are created by the linker. Generally, several input sections may be
combined into a single output section.

For example, suppose that an application is comprised of five different functions, and each
function is defined in a separate source file. Together, these source files will produce five input
sections. The linker will combine these input sections into a single output section. Only the output
section has an absolute address. Input sections are always relocatable.

If any input or output sections are empty, there is no penalty or storage cost for the linked
application. Most applications will use only a few of the many sections that appear in the section
map.

This is how the section map starts.

/*
==================== Section Map ======================
*/

SECTIONS
{

Consider the first section of program memory, below. The program memory starts at address
zero (__RESET_BASE is defined as a base memory address above) and there is space for a two
word instruction before the interrupt vector table starts. The section is loaded with data to form a
two word GOTO __reset instruction. You can look at the encoding for a GOTO instruction in the
dsPIC30F Programmers Reference Manual () to see how the instruction has been constructed.

69
/*
================== Program Memory =====================
*/

/*
** Reset Instruction
*/
.reset __RESET_BASE :
{
SHORT(ABSOLUTE(__reset));
SHORT(0x04);
SHORT((ABSOLUTE(__reset) >> 16) & 0x7F);
SHORT(0);
} >reset

The .text section collects executable code input sections from all of the application’s input files
and puts them into one output section. The order of some input sections is defined to ensure
proper operation of the MPLAB C30 compiler. For example the .handle section is used for
function pointers and is loaded first. This is followed by the library sections .libc, .libm and .libdsp.
The math library is in the middle so that it can be called efficiently from the standard C library as
well as the DSP library. Other libraries are then followed by the rest of the code.

/*
** User Code and Library Code
*/
.text __CODE_BASE :
{
*(.handle);
*(.libc) *(.libm) *(.libdsp); /* keep together in this order */
*(.lib*);
*(.text);
} >program

The rest of the section maps follow, to define all the different type of progam memory, RAM,
EEPROM and configuration memory sections.

Note It is possible to create your own user-defined output sections in program and data
memory. There are examples showing how to do this in the linker script files.

Range Checking for Near and X Data Memory

Range check expressions are included for the X data memory space and the Near data memory
space. Range checking for all other sections is provided as the memory regions are filled. A link
error will be reported if any section extends beyond its assigned memory region.

Note that the X data space limit varies by device, while the Near data space limit is fixed at 8K
bytes, or address 0x2000.

70
/*
** Calculate overflow of X and Near data space
*/
__X_OVERFLOW = (((__exdata != __bxdata) &&
(__exdata > __YDATA_BASE)) ?
(__exdata - __YDATA_BASE) : 0);
__NEAR_OVERFLOW = (((__endata != __bndata) &&
(__endata > 0x2000)) ?
(__endata - 0x2000) : 0);

Interrupt Vector Tables

The primary and alternate interrupt vector tables are defined in a second section map, near the
end of the linker script file. Here is a simple explanation of the table, using the oscillator fail error
trap as an example:

If the symbol __OscillatorFail is defined, the address of that symbol is used, otherwise the
address of symbol __DefaultInterrupt is used instead. This means that if you have not provided
an interrupt routine, then a default routine will be called. If you have not provided a default
interrupt handler (a function with the name __DefaultInterrupt) then the linker will generate one
automatically. The simplest default interrupt handler is a RESET instruction.

/*
** Section Map for Interrupt Vector Tables
*/
SECTIONS
{

/*
** Primary Interrupt Vector Table
*/
.ivt __IVT_BASE :
{
LONG(DEFINED(__ReservedTrap0) ? ABSOLUTE(__ReservedTrap0) :
ABSOLUTE(__DefaultInterrupt));
LONG(DEFINED(__OscillatorFail) ? ABSOLUTE(__OscillatorFail) :
ABSOLUTE(__DefaultInterrupt));
LONG(DEFINED(__AddressError) ? ABSOLUTE(__AddressError) :
ABSOLUTE(__DefaultInterrupt));
LONG(DEFINED(__StackError) ? ABSOLUTE(__StackError) :
ABSOLUTE(__DefaultInterrupt));
LONG(DEFINED(__MathError) ? ABSOLUTE(__MathError) :
ABSOLUTE(__DefaultInterrupt));
.
.
.

SFR Addresses

Absolute addresses for the Special Function Registers (SFRs) are defined as a series of symbol
definitions. Two versions of each SFR address are included, with and without a leading

71
underscore. This is to enable both C and assembly language programmers to refer to the SFR
using the same name. By convention, the C compiler adds a leading underscore to every label.

/*==================================================================
** Register Definitions
** (Core and Peripheral Registers in Data Space)
**==================================================================
**
**==================================================================
**
** dsPIC Core Register Definitions
**
**================================================================*/
WREG0 = 0x0000;
_WREG0 = 0x0000;
WREG1 = 0x0002;
_WREG1 = 0x0002;
.
.
.
CAN1 = 0x0300;
_CAN1 = 0x0300;
CAN2 = 0x03C0;
_CAN2 = 0x03C0;

/*==================================================================
**end of SFR definitions required in Data Space
*=================================================================*/

That may be more data than you thought you needed, but it is important not to be intimidated by
the linker and its linker script file. The linker simply follows instructions to place your code abd
variables in the available memory.

72
11 The dsPICDEM Starter Demo Board
All of the tutorials have used the dsPICDEM Starter Demo Board. Here is a summary of the main
features of the board and a schematic that will help you use the board effectively.

11.1 Features
The dsPICDEM Starter Demo Board has the following main features:

ICD 2 debugger connection on EMUD and EMUC pins

Four LEDs on LATD pins 4 through 7 – drive high to turn on

Two switches on PORTC pins 13 and 14 – reads low when pressed

One switch on MCLR – resets when pressed

A 4 MHz crystal on the oscillator pins – use one of the XT oscillator modes

An RS232 interface on the UART1 serial port

A MCP41010 digital pot on the SPI2 port – filtered output is on the line-out header

Filtered analog input from the line-in header on analog input pin AN3

Analog input from potentiometer R13 on analog input pin AN2

73
11.2 Schematic

74
12 Appendix A – Tutorial Code for dsPICDEM Starter Demo Board
12.1 Flash LED with timing loop and switch press.s
;------------------------------------------------------------------------------
; Flash LED with Timer1 and switch press
;------------------------------------------------------------------------------

.equ __30F6012, 1
.include "p30f6012.inc"

;------------------------------------------------------------------------------
;Program Specific Constants (literals used in code)

.equ Fcy, #1000000 ;Instruction rate (Fosc/4)

;------------------------------------------------------------------------------
;Global Declarations:

.global __reset ;Declare the label for the start of code


.global Delay100ms

;------------------------------------------------------------------------------
;Start of code

.text ;Start of Code section


__reset: mov #__SP_init, W15 ;Initalize the Stack Pointer
mov #__SPLIM_init,W0
mov W0,SPLIM ;Initialize Stack Pointer Limit Register

;------------------------------------------------------------------------------
;Initialize LED outputs on PORTD bits 4-7

mov #0xff0f,W0 ;Initialize LED pin data to off state


mov W0,LATD
mov #0xff0f,W0 ;Set LED pins as outputs
mov W0,TRISD
bset LATD,#4 ;Turn LED RD4 on

;------------------------------------------------------------------------------
;Loop to wait toggle LED RD4 every Timer1 period

MainLoop: btss PORTC,#13 ;Test if S1 is pressed


bset LATD,#7 ;LED RD7 on if S1 pressed
btsc PORTC,#13 ;Test if S1 is not pressed
bclr LATD,#7 ;LED RD7 off if S1 not pressed

call Delay100ms ;Wait 1/10 second


btg LATD,#4 ;Toggle LED RD4

bra MainLoop ;Loop back

;------------------------------------------------------------------------------

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; ;
; Software License Agreement ;
; ;
; The software supplied herewith by Microchip Technology ;
; Incorporated (the "Company") for its dsPIC controller ;
; is intended and supplied to you, the Company's customer, ;
; for use solely and exclusively on Microchip dsPIC ;

75
; products. The software is owned by the Company and/or its ;
; supplier, and is protected under applicable copyright laws. All ;
; rights are reserved. Any use in violation of the foregoing ;
; restrictions may subject the user to criminal sanctions under ;
; applicable laws, as well as to civil liability for the breach of ;
; the terms and conditions of this license. ;
; ;
; THIS SOFTWARE IS PROVIDED IN AN "AS IS" CONDITION. NO ;
; WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, ;
; BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND ;
; FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. THE ;
; COMPANY SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, ;
; INCIDENTAL OR CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER. ;
; ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

.end ;End of code in this file

76
12.2 Software delay loop.s
;------------------------------------------------------------------------------
; Software delay loop
;------------------------------------------------------------------------------

.equ __30F6012, 1
.include "p30f6012.inc"

;------------------------------------------------------------------------------
;Global Declarations:

.global Delay100ms ;Declare the label for the start of code

;------------------------------------------------------------------------------
;Code Section in Program Memory

.text ;Start of code section

Delay100ms: do #9,Dly100msEnd ;Do the timing loop 10 times


repeat #9998 ;Repeat NOP for 10,000 cycle delay
nop ;Delay by executing NOP
Dly100msEnd: nop ;End of DO loop - last 2 instr cannot be REPEAT
return

;------------------------------------------------------------------------------

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; ;
; Software License Agreement ;
; ;
; The software supplied herewith by Microchip Technology ;
; Incorporated (the "Company") for its dsPIC controller ;
; is intended and supplied to you, the Company's customer, ;
; for use solely and exclusively on Microchip dsPIC ;
; products. The software is owned by the Company and/or its ;
; supplier, and is protected under applicable copyright laws. All ;
; rights are reserved. Any use in violation of the foregoing ;
; restrictions may subject the user to criminal sanctions under ;
; applicable laws, as well as to civil liability for the breach of ;
; the terms and conditions of this license. ;
; ;
; THIS SOFTWARE IS PROVIDED IN AN "AS IS" CONDITION. NO ;
; WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, ;
; BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND ;
; FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. THE ;
; COMPANY SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, ;
; INCIDENTAL OR CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER. ;
; ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

.end ;End of code in this file

77
12.3 Flash LED with timing loop and switch press.c
//-----------------------------------------------------------------------------
// Tutorial code to light a LED when a switch is pressed
// and flash a LED with a Timer1 delay loop
//-----------------------------------------------------------------------------

#include "p30F6012.h"

//-----------------------------------------------------------------------------
// Constants

#define Fcy 1000000 //Define instruction cycle rate

//-----------------------------------------------------------------------------
// Main routine

int main(void)
{
LATD = 0xFF0F; //Turn all LEDs off
TRISD = 0xFF0F; //Set LED pins as outputs
LATDbits.LATD4 = 1; //Turn LED RD4 on

T1CON = 0; //Turn off Timer1 by clearing control register


TMR1 = 0; //Start Timer1 at zero
PR1 = Fcy/512; //Load Timer1 period register for 1/2 second
T1CON = 0x8030; //Load Timer1 settings for 1:256 prescaler

while(1) //Loop forever


{
if(PORTCbits.RC13 == 0) //If S2 is pressed
LATDbits.LATD7 = 1; //Then turn on LED RD7
else
LATDbits.LATD7 = 0; //Else turn off LED RD7

if(IFS0bits.T1IF) //Check for Timer1 timeout


{
IFS0bits.T1IF = 0; //Clear Timer1 interrupt flag
LATDbits.LATD4 = !LATDbits.LATD4; //Toggle LED RD4
}
}

/****************************************************************************
* *
* Software License Agreement *
* *
* The software supplied herewith by Microchip Technology Incorporated *
* (the "Company") for its dsPIC controller is intended and supplied to *
* you, the Company's customer, for use solely and exclusively on *
* Microchip dsPIC products. The software is owned by the Company and/or *
* its supplier, and is protected under applicable copyright laws. All *
* rights are reserved. Any use in violation of the foregoing *
* restrictions may subject the user to criminal sanctions under *
* applicable laws, as well as to civil liability for the breach of the *
* terms and conditions of this license. *
* *
* THIS SOFTWARE IS PROVIDED IN AN "AS IS" CONDITION. NO WARRANTIES, *
* WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, *
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR *
* PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT, IN ANY *
* CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL OR CONSEQUENTIAL *
* DAMAGES, FOR ANY REASON WHATSOEVER. *
* *

78
****************************************************************************/

} //End of main()

79

Anda mungkin juga menyukai