Professional Documents
Culture Documents
with the
DS
Digital Signal Controller
1
Table of Contents
1 WELCOME............................................................................................................................... 4
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 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
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.
The X memory also supports bit-reversed addressing to greatly simplify input or output data
reordering for radix-2 FFT algorithms.
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
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.
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.
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.
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.
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
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.
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
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:
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.
MPLAB® IDE
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
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
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.
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.
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
MPLAB ICE4000
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:
MPLAB ICD2
However, you give up many of the features the ICE4000 has. This can be clearly seen in the
comparison chart on the following page.
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
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
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).
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:
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:
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.
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:
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).
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.
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:
These tool locations assume that MPLAB was installed with the default settings.
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.
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.
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.
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.
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.
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
.include "p30f6012.inc"
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.
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 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.
25
Selecting the Simulator.
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.
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.
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.
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.
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.
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
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.
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
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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.
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.
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.
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.
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.
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.
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.
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
.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.
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.
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.
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”.
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.
MPLAB® MPLAB®
ASM30 C30
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
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.
61
The next screen allows the part to be chosen. Select dsPIC30F6012 from the pull-down list and
click the Next button to continue.
Select the Microchip C30 Toolsuite from the pull-down as shown below and click the Next
button to continue.
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
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.
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.
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.
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.
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.
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.
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:
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.
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)
}
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 */
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.
/*
==================== 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 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);
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:
A 4 MHz crystal on the oscillator pins – use one of the XT oscillator modes
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
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)
;------------------------------------------------------------------------------
;Global Declarations:
;------------------------------------------------------------------------------
;Start of code
;------------------------------------------------------------------------------
;Initialize LED outputs on PORTD bits 4-7
;------------------------------------------------------------------------------
;Loop to wait toggle LED RD4 every Timer1 period
;------------------------------------------------------------------------------
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; ;
; 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. ;
; ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
76
12.2 Software delay loop.s
;------------------------------------------------------------------------------
; Software delay loop
;------------------------------------------------------------------------------
.equ __30F6012, 1
.include "p30f6012.inc"
;------------------------------------------------------------------------------
;Global Declarations:
;------------------------------------------------------------------------------
;Code Section in Program Memory
;------------------------------------------------------------------------------
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; ;
; 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. ;
; ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
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
//-----------------------------------------------------------------------------
// 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
/****************************************************************************
* *
* 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