Professional Documents
Culture Documents
Hands-on Workshop
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 1
You are attending a hands-on workshop to get familiar with Microchips new Digital Signal Controller namely the dsPIC30F 16-bit MCU.
Goals
Gain knowledge of dsPIC DSC architecture Use MPLAB IDE development environment Learn how to develop code on a dsPIC DSC MPLAB C30 compiler Use Peripherals and C Peripheral Libraries Use DSP FilterLab software Use MPLAB ICD 2 In-Circuit Debugger Debug on dsPICDEM 1.1 Development Board
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 2
After a brief introduction to Microchip and the DSC family of products, we will start our hands-on portion, by getting to know the development tools. After creating a project in MPLAB IDE, we will use the MPLAB C30 C compiler to develop code and then use the MPLAB ICD 2 to program and debug the dsPIC30F6014 chip on the dsPICDEM 1.1 board. We will then learn about DSC peripherals and finally, we will learn how to use a DSP function. During the course of the training, you will use the MLAB ICD debugger and the dsPICDEM 1.1 development board.
Corporate Overview
Leading semiconductor manufacturer:
of high-performance, field-programmable, 8-bit & 16-bit RISC microcontrollers of analog & interface products of related memory products for high-volume embedded control applications
$651M in product sales in FY03 More than 3,000 employees Headquartered near Phoenix in Chandler, AZ
Microchip is the leading 8-bit semiconductor company. It offers high performance field programmable microcontrollers (MCU). Many have built-in analog and digital peripherals. In 1993 Microchip went public. At that time the revenue was $90M, with less than 1000 people. Now Microchip is #1 in volume shipment of 8-bit MCUs. Revenue in FY2003 was $651M and Microchip has over 3000 employees worldwide.
212 Products
Flash, OTP and ROM Superior Analog functionality Outstanding Flash Endurance Industrys strongest product and family migration path
28-Pin Family 40/44-Pin Family
64/68-Pin Family
4K - 64K Words
14-Pin Family
18/20-Pin Family
2K - 16K Words
.5K - 4K Words
1K - 2K Words
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 4
Microchip is the leader in 8-bit MCUs. How did this transformation occur? Well the secret lies in the fact that Microchip offers customers a very flexible product line of over 194 products available in Flash, OTP and ROM. Many functions are built-in like analog and digital peripherals. Microchip offers outstanding Flash endurance. Lastly, it has the strongest product and product migration paths in the industry.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 5
Microchip now offers over 80 Flash MCUs. Microchip was the first to introduce field programmable Flash in 1993 with the PIC16C84, which is now called the PIC16F84. So it is no surprise that Microchip is still the leader in this field. In addition, Microchip offers world class endurance for data retention (greater than 40 years) Why customers prefer Flash? Streamlines Complete Product Development: Development MPLAB ICD - Lower cost development tools Develop with the production material Fast erase with no additional hardware (compared to UV erase) Production No Mask ROM charge - Program and run Can be reprogrammed - Less scrap Improved inventory management - use the same device for different applications Flash program memory typical endurance is about 100K Erase/Write(E/W) cycles. Data EEPROM on the other hand, has 1 million E/W cycles. Data EEPROM is typically used to save calibration constants, serial numbers and variables which need to be preserved through a power down cycle. Lastly, Flash offers the developer a easy development tool. Microchip offers the most cost effective and useful development tools in the industry.
What is DSC ?
e Th
P DS
ce pa S
dsPIC30F
PRICE
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 6
The dsPIC 30FXXXX devices are 16-bit MCUs with a full DSP engine. As previously discussed, Microchip is widely known for its 8-bit MCU with a maximum through put of 10 MIPS. In many applications faster through put is required in which case 16-bit MCU are a logical choice. Microchip decided that a 16-bit offering would satisfy some customers however a wider application pool could utilize a 16-bit architecture with a built-in DSP engine. This would be specially useful in applications requiring control algorithm to run. The dsPIC DSC meets the high end 16-bit MCU market needs as well as the low end 32-bit market needs. The dsPIC family architecture includes the easy-to-use microcontroller programming and makes this available for more complex DSP functions. Simply put, you dont have to hold a Ph.D. in electrical engineering to use the dsPIC DSC family.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 7
As mentioned before, the dsPIC device looks like a MCU, performs in the same class as 16- and 32-bit DSPs and best of all is priced like a MCU. All the easy-to-use features of an 8-bit PICmicro MCU have been moved to the dsPIC family plus a very powerful DSP engine. These features include ultra-reliable Flash technology in small 18, 28 and 40 pin packages; easy single cycle and single word instructions. built-in peripherals: ADCs, UARTs, CAN, I2C, SP, PWM etc.; and finally, system level features like programmable brown-out detects, fail safe clock monitors, watchdog timers, etc. All these features make it possible to design a single chip solution for your application at a very affordable price.
Seamlessly integrates a DSP and an MCU MCU look and feel, easy to use Competitive DSP performance Optimized for C compiler Fast, deterministic, flexible interrupts Excellent RTOS support
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 8
The dsPIC family offers all the easy-to-use functions of our 8-bit MCU migrated to 16-bit with an integrated DSP engine. The look and feel are very much like our PICmicro architecture, which is well known for its ease of use. Yet, the DSP engine gives a user a high performance machine for the application. The dsPIC instruction set and architecture has been fine tuned and optimized for a C compiler. It has DO and REPEAT instructions as part of the built-in micro code, much like the DO-While ad FOR Loop instructions in a C compiler. Unlike most architectures, the interrupts are fast and fixed, that is, an interrupt will be responded to in 5 and only 5 instructions cycles, no exceptions. In other architectures, depending on which instruction is being executed, an interrupt may respond in 3, 4 N instructions cycles. Also, the dsPIC DSCs have a unique interrupt vector for each interrupt, so there are no extra cycles taken in the interrupt service routine to check which peripheral caused which interrupt, hence faster response to an interrupt. Lastly, the dsPIC has new features in the architecture like interrupt response, software stack etc., which makes it excellent for RTOS based applications.
Co-Development
Assembler
Simulator
Compiler
Verilog Model
Applications
DSP Benchmarks
MCU Benchmarks
Compiler Benchmarks
Co-development of Architecture, Compiler, Applications & Algorithms In-house compiler team Motor control consultants 3rd party compiler vendor RTOS vendors Speech/modem consultants Encryption consultants
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 9
Many of the features talked about on the dsPIC DSC were designed in at the very start of the architectural design phase. The architects sat down with C compiler, RTOS, motor control and other 3rd party designers and consultants. The architects understood the needs and requirements of the applications. Based on those discussions, special hooks and features were added to the dsPIC architecture, thereby making the dsPIC device well suited to meet the application, RTOS and C compiler needs.
C Compiler Efficiency
dsPIC30F Processor includes features to enhance C code efficiency New instruction types + More flexible addressing + Software stack = Compact C code
32-bit Math intensive Code 16-bit Competition (~ 50 kB code)
221% 190% 157% 138% 100%
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 10
The dsPIC30F includes features in the architecture which enhance C code efficiency. With new instruction types, more flexible addressing feature, a software stack, etc the final result is a very compact and efficient C compiler and code generation. In the benchmark analysis done for 32-bit math intensive code, dsPIC30F stood 15% better than the nearest competitor and nearly 121% better than the worst.
Furthest Competitor
115%
Nearest Competitor
dsPIC30F
dsPIC30F Families
Power Conversion and Motor Control Family Sensor Processor Family General Purpose Controller Family
DSCs are offered in three basic family types: Power conversion and Motor Control Family of parts which basically has peripherals like motor control PWMs, high speed ADC, etc. Sensor family of products which has high resolution ADCs, DCI, etc. Finally, the General Purpose Family of products which has high resolution ADCs, CAN, UARTs, etc. Let us look at some of the family offerings.
dsPIC30F Products
Power Conversion & Motor Control Family
Product dsPIC(R) DSC P i n s A/D Output Motor 10-bit Flash SRAM EE Timer Input Comp/ Cntrl 500 KB Bytes Bytes 16-bit Cap Std PWM KSPS PWM U Quad A Enc R T S P I I 2 C ( ( T T M M ) ) 1 1 1 1 1 2 2 1 1 1 1 1 1 1 1 1 2 1 C A N
28 28 28 40 40 64 80
12 24 48 24 48 66 144
3 5 5 5 5 5 5
4 4 4 4 4 4 8
2 2 2 4 4 4 8
6 6 6 6 6 8 8
6 ch 6 ch 6 ch 9 ch 9 ch 16 ch 16 ch
1 1 1 2 2 1 2
Brushless DC Motor Control AC Induction Motor Control Switch Reluctance Motor Control UPS, Inverters and Power Supplies
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
The Power Conversion Family has 7 products from 28 pins to 80 pins and from 12 kB to 144 kB. The key features offered are motor control PWMs and high speed 10-bit ADC. The family can be used for a host of motor control applications used in appliances, automotive and industrial controls.
dsPIC30F Products
General Purpose Controller Family
Product Pins dsPIC(R) DSC Flash KB SRAM Bytes Output EE Timer Input Compare Bytes 16-bit Capture Std PWM A/D 12-bit 100 KSPS U A R T S I P 2 I C ( T M ) C A ( N T M ) Codec Interface
40 40 64 64 64 80 80 80
3 5 5 5 5 5 5 5
2 4 8 8 8 8 8 8
2 4 8 8 8 8 8 8
13 ch 13 ch 16 ch 16 ch 16 ch 16 ch 16 ch 16 ch
2 2 2 2 2 2 2 2
1 1 1 1 2 1 2 1 2 1 2 1 2 1 2 1 1 2 2 2 2 2 2 AC97, I2S AC97, I2S AC97, I2S AC97, I2S AC97, I2S
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 13
The General Purpose Family has 8 products from 40 pins to 80 pins and from 12 kB to 144 kB. The key features offered are high resolution 12-bit ADC, codec Interface.
dsPIC30F Products
Sensor Processor Family
Product Pins dsPIC(R) DSC Flash KB SRAM Bytes Output EE Timer Input Compare Bytes 16-bit Capture Std PWM A/D U A R T S I P 2 I C ( T M ) C A ( N T M ) 1 1 1 1
18 18 28 28
12 24 12 24
3 3 3 3
2 2 2 2
2 2 2 2
1 1 1 2
Glass Break Detect Gas Sensor Torque Sensor Tire Pressure Sensor Steering Angle Sensor
Rain Sensor Low power, Smart Sensor Airbag Sensor Processor Pressure Sensors Vibration Measurement
Slide 14
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
The Sensor Family has 4 products from 18 pins to 28 pins and from 12 kB to 24 kB. The key features offered are high resolution 12-bit ADC and small package. The family can be used for a host of sensor applications in smart sensor applications.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 15
Lets now get to the hands-on section of this workshop: We will start by getting to know the development tools. After creating a project in MPLAB IDE, we will use the MPLAB C30 compiler to develop code and then use the MPLAB ICD 2 to program and debug the dsPIC30F6014 chip on the dsPICDEM 1.1 development board.
Hands-on Labs Learn to use important features of the dsPIC Digital Signal Controller
I/O Ports Timers Interrupts UART A/D Converter DSP Features
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 16
Once you are familiar with the code development and debugging process, we will move onto code examples to use the various features of the dsPIC family. We will be using the specific features and peripherals shown here. These are important features of the processor and commonly used peripherals. Please consider these labs as a starting point for experimentation and learning. If you finish the labs early, feel free to modify the code to see what happens. Please remember the additional literature you have been given. There are instructions for the labs on the printed sheets we have provided so if you get lost, follow the instructions!
Main Features
Single Core Integrating an MCU & a DSP Modified Harvard Architecture Data is 16-bit wide Instruction is 24-bit Wide Linear Program Memory up to 12 MB Linear Data (RAM) up to 64 kB True DSP Capability Many Integrated Peripherals
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 17
The dsPIC DSC is a single core integrated MCU with a DSP engine. Just like all PIC MCUs, it is a Harvard architecture which means that there are separate paths for the data and program memory. These separate paths give Harvard architecture devices a faster throughput than conventional Von Neuman architecture devices. The data or RAM path is 16-bit wide while the program memory or Flash ROM or instruction path is 24-bit wide. Again, the different path width is a Harvard architecture advantage over Von Neuman machines (where both paths are 16-bit wide). This allows the majority of instructions in the dsPIC DSC to be single word and single cycle execution. The dsPIC DSC has a linear program memory (up to 12 MB), meaning no paging in the architecture and the data memory is also linear(up to 64 kB), meaning no banking in the RAM access. The DSP engine is fixed point and has two 40-bit multiply/accumulate accumulators along with a barrel shifter and special DSP features like Modulo addressing to maintain circular buffers and bit-reversed addressing for FFT functions, to name a few. As with all PIC microcontrollers, the dsPIC DSCs have a multitude of very useful analog and digital peripherals fully integrated with the MCU.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 18
The working register array has 16 general purpose working registers. In the PIC MCU nuance, these can be viewed as 16 Wregs or W registers. The dsPIC DSC has a software stack and working register number 15 or W15 is initialized as the Top of the stack address in RAM. As mentioned earlier, the interrupts are fast, responding in 5 cycles and each has its own interrupt vector. Three operand, single cycle/word instructions can be executed where, for example, the contents of two 16-bit registers can be added and placed in a third register. Multiple addressing modes are available with preand post-incremented pointer capability. This allows for efficient execution of C code. Finally, a unique feature is available allowing additional 32 kB of data space that can be addressed or mapped from program memory using the Program Space Visibility feature of the dsPIC device. This allows the user to retrieve constants stored in program memory, just as if they were RAM locations.
Programmers Model
15 W0 W1 W2 W3 W4 W5 W6 W7 W8 W9 W10 W11 W12 W13 W14 W15 0
DSP OPERAND Registers DSP ADDRESS Registers MAC Prefetch Offset MAC Write Back
ACCA ACCB
39
0
16 15
0
23 22
15 SRL
N OV SZ C
Status Register
DSP Status
MCU Status
Slide 19
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
The programmers model consists of 16, 16-bit working registers with two 40-bit accumulators. Certain W registers are pre-assigned for DSP and MAC operations, with W15 assigned as the stack pointer and W14 as the frame pointer. These W registers can be used as general purpose working registers when not being used in special DSP or addressing modes. The program counter is 23-bits wide. The Status register contains status bits applicable to the operations of the processor. It is divided into two halves, the upper for DSP status and the lower for MCU status.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 20
With additional working registers, the user has more flexibility in DSP and MCU algorithms. By preloading addresses in the appropriate registers a user can execute complex FFT, FIR and IIR algorithms quickly and efficiently. Stack manipulating using the PUSH and POP instructions can also be executed.
0x0000FE 0x000100
0x7FF000 0x800000
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 21
The program memory is Flash based and is a linear addressed space. The reset vector is at zero; however, executable code starts at hex 100. In between we have two sets of interrupt vector tables. The alternate vector table can be assigned, for example, by the user for debugging purposes during code development. The user space is 20 MB, but the max size on parts available at this time is 144 kB. Note that the Data EEPROM is also mapped in the program memory. The data EEPROM is a high endurance section of the same PEEC Flash Technology used by Microchip. Finally, the configuration space is the second half of the program memory space, and most of that space is not implemented or used for test purposes. The sections which are implemented are the configuration fuse bytes which preconfigure the device during the programming phase.
LS Byte Address
0x0000 0x07FE 0x0800
8 kB SRAM Space
0x17FE 0x1800
0x1FFE 0x27FE
0x8001
0x8000
0xFFFE
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 22
The data memory is implemented as a 64 kB block. Please note that there are 32K words each 2 bytes wide. Some important points to note: The first 2 kB of data memory is used for special functions registers. These control the core and peripheral functions. Present dsPIC30F devices have up to 8 kB of on-chip data RAM starting just after the SFR space. The data space is broken into a X and Y section to allow easy access for DSP instructions using pointers. Example: if the user wants to access two RAM locations using indirect addressing, then two pointers can be setup: one for the X space and the other for Y space and data retrieved in one instruction word. The near data space of 8K can be accessed directly using one word instructions. Beyond 8 kB, indirect addressing or MOV instructions must be used. The upper 32 kB can be optionally mapped into program memory and accessed just like data memory. This feature is useful to retrieve constants stored in the Flash program memory. Note that in most devices, the upper 32 kB may not be physically implemented as RAM.
The dsPIC DSC has 84 unique instructions (not counting the multiple addressing modes). Most are single cycle and take up one word of program memory. Three operand instructions are there to improve instruction efficiency. There are a special set of DSP instructions which optimise the DSP engine. The DO instructions repeats a set of instructions marked by an address label specified in the instruction and repeats these instructions N number of times specified as a value in a W register. REPEAT on the other hand repeats the very next instruction N time specified in a W register value or a literal value. DO and REPEAT instructions significantly improve the efficiency of repetitive code loops.
Some generic addressing modes are discussed here: ADD W0,W1, and W2 instructions add the contents of W0 to the contents of W1 and saves the result in the contents of W2. If an overflow occurred, the CARRY bit will be set. CLR CORCON instructions, loads zeros to the CORCON register. DEC[++W0],W1 instruction, pre-increments the address in W0, then retrieves the value from that pre-incremented address and loads it in W1. MOV[W0+#0xC3],W1 instruction, adds an offset of 0xC3 to the address in W0 and retrieves the contests of that offset address and loads that value in W1. SUB #0x1d7,W0 instruction, subtracts a value of 0x1d7 from the contents of W0 and saves the result back into W0. Note the max value of the immediate value is 10-bits(0x3ff) only. MOV [W0+W1],W2 instruction, creates an address by adding the value in W0 and W1 and retrieves the contents from that address and loads it in W2.
Interrupts
Stack Operation Prior to ISR Entry
15
0 0x0800
SRL pushed onto stack to preserve IPL<2:0> and MCU ALU status (except DC)
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 25
This slide graphically shows the stack push operation for an interrupt. Remember, the PC is 23-bits wide, the SRL is 8-bits wide and the RAM space is 16-bits wide. Note that the SRL register contains the IPL status bits so the CPU priority before the interrupt is saved. The user could potentially modify the values saved on the stack to allow the CPU to return to a higher or lower priority at the end of the ISR.
Editor Text editor, integrated with MPLAB IDE Context sensitive color coding
For assembler and C compiler
MPLAB IDE includes a basic text editor which supports custom color coding by file type. There is also context sensitive color coding for the assembler and C compiler. The editor has many powerful features including cut/paste/copy, find/replace, match brace etc. Some of these will be reviewed in the following slides.
Editor
Title bar with file changed indicator Gutter display
d de co or ol C
x te
n pa t
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 28
The main areas of the editor window are the title bar with file change indicator, color-coded text pane, gutter display for line numbers and break indicators and vertical and horizontal pane controls.
Editor
The green arrow indicates the point where the execution stopped and a blue vertical mark indicates a bookmark, which can be placed anywhere in the code. The user can move from bookmark to bookmark as desired. A red round mark with a B in it indicates the presence where a breakpoint has been set. If the program hits that mark, it stops right after its execution. A mouse over feature allows the user to find the address and contents of a SFR register or bit. When the right mouse button is clicked, the properties box appears. One of the advanced features of this box is to look for matching braces. So if the right mouse is clicked at one brace, the user could easily find out its matching brace. This is useful when writing code in C.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 30
In addition, to the standard Find function, MPLAB IDE now supports Find-inProject Files. Select Project>Find in Project Files... and enter the search text in the dialog box. All occurrences of the string will be show in the output window. Double clicking on a entry will move the focus to that occurrence in the source file.
Multiple breakpoints Stopwatch for time measurement Trace memory to see past execution View and modify variables and registers External stimulus
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 31
The simulator included with MPLAB IDE operates on an instruction cycle boundary, that is resolution of simulated events is an instruction cycle. Program memory and data can be modified and external stimulus can be applied to I/O pins. Some important features of the Simulator: Stopwatch function allows user to easily calculate execution time of functions and subroutines in a program Trace memory allows user to view past variable values and help debug programs External stimulus file can be generated to simulate external signal conditions Certain peripherals are not completely simulated: for example, the A/D conversion cycle is simulated, but an analog source on the input pin is not.
GNU based Comes with assembler, linker and librarian ANSI C compliant with standard libraries Optimized for dsPIC architectural features
16-bit native data type Uses 3-operand instructions Complex addressing modes Efficient multi-bit shift operations Efficient signed/unsigned comparisons
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 32
The C compiler is GNU based and comes with an assembler, linker and librarian. The compiler is ANSI C compliant and has standard libraries. We will explore the use of these libraries in later exercises. The code generated is optimized and uses some of the architectural features for the optimization, including 16-bit data type, complex addressing schemes, 3 operand instructions, efficient multi-bit shift operations. (Example: shift right 4 times) and signed/unsigned comparisons.
.O .A .GLD
.COF
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 33
The compiler, compiles the source code written either in C or assembly. This, in turn, is converted to the appropriate object code. At this point, users can link object files or archive files using the linker and the linker header file (*.gld) to create an executable hex file which can be programmed into a Flash device and made to run or code the object file (*.cof) to run with the debugger.
Libraries
Math - sin(), log(), sqrt(), etc. Peripheral Driver - ADC, PWM, UART, etc. DSP Algorithm - IIR filter, Convolution, etc. TCP/IP and Soft Modem Speech recognition Noise and Echo Cancellation Encryption RTOS compatible - CMX, OSEK
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 34
As mentioned before, the C compiler comes with a bundle of very useful libraries: Math, peripherals drivers and, DSP algorithms. There are also applicationspecific libraries available which include: TCP/IP, soft modem, speech recognition, noise and echo cancellations, encryption and RTOSs.
Lab 1
Learn to Use dsPIC30F Tools in MPLAB Integrated Development Environment
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 35
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 36
In this first lab, we will use the latest MPLAB IDE version 6.XX. This XX will be constantly changing since we introduce new versions on a monthly if not more often basis. This is done to cover new parts introduced by Microchip. Please get the latest version of MPLAB free from www.microchip.com. We will also use the C30 C compiler, the LINK30 linker and the debugger called MPLAB ICD 2. To help you we have a quick reference card provided.
In lab 1 we will create a project, with a pre-exiting project, we will then compile the code using the C30 compiler and Lastly, we will program the dsPIC30F6014 device on the dsPICDEM 1.1 Development Board using MPLAB ICD 2. We will then run the code and execute some of the debugging features of the MPLAB ICD 2.
Lab 1
Start MPLAB IDE
Menu Bar
You will find a MPLAB IDE icon on your computer, double click it to start MPLAB. Note the following: Two windows open 1. Project Window and 2. Output Window. The tool bar shows icons for various tools selected, the menu bar is right at the top and the status bar at the bottom tell you what devices has been selected. Please note that at the start, this window may differ from what you see on your computer.
Lab 1
Click Project Menu Select Project Wizard
We will now create a project in the MPLAB IDE: Select Project from the menu and select Project Wizard. On the Welcome screen, click Next.
Lab 1
Select dsPIC30F6014 Click Next
From the device list select dsPIC30F6014 and then click Next. Select Microchip C30 Toolsuite and then click Next.
Lab 1
Type Lab 1 for Project Name Click Browse
Type Lab 1 in the Project Name and click Browse, navigate to the C:\WIB1.1\Lab1 directory and click Select.
Lab 1
Click Next
Select Lab1 Flash LED with timer delay.c Click Add Click Next
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 42
Click Next and then from the Step Four window, select the Lab1 Flash LED with Timer delay.c file. Click Add, and then click Next.
Lab 1
Summary Screen Appears Click Finish
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 43
The summary screen informs you about the device selected, the Toolsuite selected and finally, the project file where the project will be created. If all looks well then click Finish.
Lab 1
Project Window Now Shows the Lab 1 Project
The project window now shows the source file selected. In order for the file to be compiled and linked, the linker script file needs to be identified. This file basically is the location where all the definitions related to the linker are declared: for example, the locations of the interrupt vector, the amount of RAM, Flash and EEPROM, etc. If a right click is done on the Linker Script section, and Add Files is selected, then the user can add the linker script file.
Lab 1
If during installation, the user selected the default setting (which is recommended), then the linker script file will be located in the C:\PIC30_Tools\support\gld directory. In any case, look for the *.gld files in the appropriate directory on your computer and select the p30f6014.gld file. Click Open.
Lab 1
Project Window Now Shows the Linker Script File
The Linker Script file now shows the right linker file for the device selected. If any file needs to be edited or viewed, then double clicking of the file name will open a window and the user can edit the file as needed.
Step 2
Compile and Link the Project
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 47
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 48
Before we link and compile, you will notice that a file has been referred to in the main program, namely the header file called p30f6014.h. This header file defines the exact address and location of the SFRs, PORTs etc. The header file is useful because the user can now name the PORT and SFR definitions and syntax as seen in the data sheet and the linker will automatically compile and link the right address pertaining to the syntax used. So we need to indicate to the compiler the location of the header file. If we are using the MPLAB ICD 2 to do debugging, then we also need to reserve some memory for the debug code which resides in the part.
Lab 1
Click Project Menu Select Build Options and Project
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 49
Click on the Project Menu and select the Build Options and finally, Project.
Lab 1
Find Include Path Click Browse
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 50
A build option for the project window opens up, which will normally show a blank for the Include Path. Click the Browse button to search for the Include Path.
Lab 1
Go to C:\PIC30_Tools\support\h Click Select
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 51
Again, if the tools were installed using the default setting (which is recommended), then the header files should be located at C:\PIC30_Tools\support\h. Go to that directory and click Select. If you have selected some other locations for your header file, please indicate that path here.
Lab 1
Include Path Now Points to Header Files
Click MPLAB LINK30 Tab Select Link for ICD2 and Click OK
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 52
If the default include path was selected, the include path would be as above C:\PIC30_tools\support\h\. Next click on the MPLAB LINK30 tab and select the Link for ICD2 and click OK. This will indicate to the linker that the MPLAB ICD 2 is being used for debugging and hence space will be reserved for the debug executive code.
Lab 1
Click Project Menu Select Make
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 53
Now that everything has been set so, let us build or make the project. Click the Project menu and select Make. You can also hit the F10 key to do this.
Lab 1
Build Results are Shown in Output Window
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 54
A output window will open and the make process outputs will be displayed. If any errors occur during the make process those will be indicated in this window. The user can then double click on the Error line and MPLAB IDE will directly take the user to the place where the compiler or linker encountered the error. In the case of Lab 1, the project is already debugged so no errors should occur and the Build Succeeded indicator should be shown at the bottom the output window.
Step 3
Use the MPLAB ICD 2 to Program and Run the Code
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 55
Lab 1 Hardware
MPLAB ICD 2 dsPICDEM 1.1 Development Board
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 56
In order to program the part on the dsPICDEM 1.1 Development Board, the user needs to use the MPLAB ICD 2 programmer/debugger connected to the dsPICDEM 1.1 Development Board. Please connect the MPLAB ICD 2 to the PC using the USB cable and connect the 6-pin RJ-11 phone plug from the MPLAB ICD 2 to the phone connector on the dsPICDEM 1.1 Development Board. Power the dsPICDEM 1.1 board with the supply provided (9VDC 1.0 Amp).
Temp Sensor
LCD
CODEC MIC In/ Spkr Out Switches (4) LEDs (4) POTs (3)
Slide 57
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
The dsPICDEM 1.1 Development Board is a very useful tool for applications development. The section which will be used in the labs are: The Switches SW1 to SW4 The LEDs, LED1 to LED4 The 3 potentiometer RP1 to RP3 The RJ11 ICD plug in connector to connect to the MPLAB ICD 2 debugger The LCD display which is a dot matrix LCD
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 58
Please connect power to the dsPICDEM 1.1 board. Please connect the MPLAB ICD 2 to the PC using the USB cable and connect the 6-pin RJ-11 phone plug from the MPLAB ICD 2 to the phone connector on the dsPICDEM 1.1 board.
Lab 1
Click Debugger Menu Choose Select Tool and MPLAB ICD 2
Once the hardware connections are done, click Debugger on the menu bar, click on Select Tools and click on MPLAB ICD 2. If the MPLAB ICD 2 is already selected, then click on Debugger on the menu bar and click on Connect. This will connect the MPLAB ICD 2 to the MPLAB software.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 60
If in case the firmware on the MPLAB ICD 2 is an older version, a warning window will tell you that a new firmware is available. If this is the case, please click Yes and download the latest firmware for the MPLAB ICD 2. This will ensure that you are using the latest and the greatest firmware algorithms for the silicon. This window will not appear if you have the latest updates to the software and firmware.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 61
Once the hardware is connected, the output window will indicate the status of the connection and indicate that the MPLAB ICD 2 is ready for operation. If an error occurred during the connection, that will be indicated. The best way to solve any error problem is to make sure all the connections are correctly made and retry the connection following the process mentioned in the previous slides. Hardware Steps to check in case of error: Power to dsPICDEM 1.1 Development Board (power LED should light) -> USB connection from ICD 2 to PC -> RJ-11 connector from ICD 2 to the dsPICDEM 1.1 Development Board. Hardware check if problems occur: 1. Check if the device selected on MPLAB ICD is dsPIC30f6014. 2. Check if power on dsPICDEM 1.1 Development Board is on -> POWER LED should be ON 3. ICD 2 is properly connected to PC through the USB cable 4. ICD 2 is properly connected to dsPICDEM 1.1 Development Board through the RJ-11 connector.
Lab 1
Click Debugger Menu Choose Program
Output window
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 62
If the connection is successful, we are ready to program the part. Click on Debugger on the menu bar, choose Program. The output window will open and the steps during the programming stage will be displayed. If all the steps are successful, the message on the bottom will indicate that the programming succeeded and the MPLAB ICD 2 is ready for the next operation.
Lab 1
Click Debugger Menu Choose Run
Once the part programmed successfully, click on Debugger on the menu bar and click on Run. The program should run and LED1 should blink at a constant rate of 1 Hz.
Step 4
Use the MPLAB ICD 2 debugging features
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 64
We will now go through some of the debugging features of the MPLAB ICD 2.
Lab 1
Click View Menu Choose Program Memory
Press F5 to Halt Press F6 to Reset Green Arrow Shows Code at Reset Vector 0x00000
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 65
In order to view the program memory, click on View on the menu bar then click on Program Memory. A program memory window will appear which shows a green arrow at the reset vector of 0x00000, where a goto_reset instruction resides. Hit the F5 key to halt the program execution, hit the F6 key to reset the program.
Lab 1
Press F7 to Single Step Green Arrow Points to Code at _reset
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 66
The F7 key single steps through the program. Hit F7 once and the program goes to the _reset location. Notice that this is at address hex one hundred. The code at the beginning of the reset location is the startup code inserted by the C compiler. Notice it initializes the stack and calls other initialization routines before the first call to main is done.
Right Click
Set Breakpoint Run to cursor
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 67
Keys for program execution: F5 halts program execution F6 resets the program F7 single steps through the program F9 runs the program Try these out and see if they work on your program To set a breakpoint, you have to first stop execution by pressing the F5 key, then go to the location in the program memory window to see where you would like to set a breakpoint. Click the mouse left key at that location to set the cursor and then right click at that point. A menu appears which allows the user to Set a breakpoint, Run to Cursor etc. Let us explore these possibilities.
Lab 1
Right Click LATD = 0xFFFF; and Choose Run to Cursor Green Arrow Points to Next Line, TRISD = 0xFFF0;
From the project window, double click on the <Flash LED with Timer delay.c> file. A window showing the code in that file will open. Move up and down in that file until you reach the code depicted in the slide. Click on the LATD = 0xFFFF; line and using the right click of the mouse, select Run to Cursor. You will notice that the green arrow points to the next line which is TRISD = 0xFFF0;. This is because the instruction LATD = 0xFFFF executes and stops at the very next instruction after that.
Lab 1
Find Line if(IFS0bits.T1IF == 1) Right Click and Choose Set Breakpoint
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 69
Next let us explore how to use a breakpoint. Search the file for the line if(IFS0bits.T1IF == 1);. Select that line and right click the mouse and choose Set Breakpoint. A red breakpoint indicator will appear in the left gutter of the line.
Lab 1
Press F9 to Run Green Arrow Points to Breakpoint Line
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 70
Hit the F9 key to run the program and after a short delay (of about 1 second), the program will stop and the green arrow will overlap with the red dot. Please note that the if statement in C is a complex set of assembly instructions. The program is probably stopped at some instruction right after the first one in that statement, so it is still in the process of executing that complex C statement.
Lab 1
Press F7 to Single Step Green Arrow Points to if(PORTA bits.RA12 == 0)
Press F7 to single step and you will notice that the green arrow points to if(PORTCbits.RC13 == 0), which is the next logical statement in the code. Note several steps have occurred in the output window to indicate that this C statement had several assembly level instructions in its execution.
Lab 1
Click View Menu Choose Watch
Select PORTA from the Add SFR Field Click Add SFR
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 72
Now let us explore how to View and Watch variables. Click View on the Menu bar and click Watch A window will open with Add SFR and Add Symbol scroll down screens. In order to select a desired SFR to view, use the down arrow in the Add SFR menu and select it. In this case let us view PORTA, so please scroll down and select PORTA and click the Add SFR button.
Lab 1
Hold Down Switch SW1 or SW2 and Press F9 PORTA Value Changes Depending on SW1 and SW2 Being Pressed
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 73
The watch window will now show PORTC value displayed as above. To see how the PORTA value changes in the watch window, hold down SW1 or SW2 and hit F9. Remember that the breakpoint is still set in the last exercise, so the program will stop every time it hits the breakpoint, and at that time, the watch window will be updated and the value of the key hit will be displayed.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 74
The dsPIC30F has a unique interrupt vector for each source of interrupt. These are true vectors -- each vector is programmed with the address of the ISR. There can be up to 8 non-maskable trap vectors for critical hardware problems, such as an oscillator failure, math errors, etc.. The dsPIC DSC presently has 5 trap sources implemented. The IVT supports up to 54 sources of interrupt. The dsPIC DSC presently has 45 vectors implemented. There are 8 user assigned levels of interrupt priority, 0 through 7. 0 is low and 7 is high. Traps have priority over all other interrupts. A trap can be viewed as a level 8 priority interrupt. There is an Alternate IVT (AIVT) that can be enabled. The AIVT can be loaded with a different set of ISR addresses than the IVT. The AIVT is useful for diagnostic modes, etc. By using a different ISR, a peripheral can be used differently for the alternate mode. For example, you might want to program the UART to upload test data to a PC when testing an application. The interrupt response time is deterministic and fixed at a 5 cycle latency for all instructions. This is a very unique feature when compared to other architectures. Users can be assured that an interrupt will be responded to in a fixed duration of time. The return latency is 3 cycles.
0x00007E
0x0000FE
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 76
This slide shows a memory map of the IVT and AIVT. Each vector location is programmed with the 24-bit address of an ISR. Interrupt and trap vectors with a higher address have lower natural priority. Note that the Reset vector consumes two locations. The Reset vector is loaded with a GOTO instruction that jumps to the startup code. The Reset vector location is not a true vector because resets are not handled by the interrupt controller.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 77
There are 8 user-assigned priority levels for each source of interrupt. The SRL has status bits that indicate the present CPU priority. If a pending interrupt is greater in priority than the current CPU priority, the interrupt will take place. During the interrupt, the SRL is pushed on the stack to save the old priority level and the IPL bits are changed to the priority of the current interrupt task. Conflicting interrupt sources with the same user programmed priority level will be resolved by their natural order priority in the IVT. The position of each interrupt source in the IVT determines its natural order priority. A low order priority in the IVT can be overcome by assigning the interrupt a high user priority via the IPC (interrupt priority control) bits for that source.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 78
It is important to note that the CPU has some priority level at all times. This is quite different than other PIC microcontrollers. It starts at zero at Reset. The CPU priority level is located in the Status Register bits IPL<2:0>. The IPL<3> bit is located in the CORCON register. The CPU can be interrupt by a higher level priority and then assumes that priority. The old priority is saved on the stack.
There are 8 user-assigned priority levels for each source of interrupt. The SRL has status bits that indicate the present CPU priority. If a pending interrupt is greater in priority than the current CPU priority, the interrupt will take place. By default, the CPU priority is 0 and all user priorities are kept at 4. During the interrupt, the SRL is pushed on the stack to save the old priority level and the IPL bits are changed to the priority of the current interrupt task. Conflicting interrupt sources with the same user programmed priority level will be resolved by their natural order priority in the IVT. The position of each interrupt source in the IVT determines its natural order priority. A low order priority in the IVT can be overcome by assigning the interrupt a high user priority via the IPC (interrupt priority control) bits for that source. To disable all user interrupts, the CPU priority can be set to 111 that is the IPL<2:0> = 111. This would not allow any user interrupts to occur. Traps and non maskable interrupts could still occur. Note that IPL3 bit is read only, so traps cannot be disabled. There is also a DISI instruction which disabled interrupts between 1 - 6. This allows the CPU to still run since by default the CPU interrupt is 0. Also priority level 7 or higher interrupt still can interrupt the DISI instruction.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 80
The SRL register and the PC are saved automatically. This preserves the MCU status bits (except DC), the old CPU priority and the Repeat Active (RA) Status bit. Any other registers can be saved using PUSH instructions to place them on the software stack. The PUSH.S and POP.S instructions can be used to save the W0 W3 into shadow registers in one cycle. They also save the PSVPAG, TBLPAG, MCU status bits and RA Status bit. The shadow registers are only one level deep, so there are restrictions. Basically, the CPU cannot be interrupted by any other process that uses the shadow registers or the contents will be destroyed.
0x801 0x803
0x800 0x802
IPL3 bit
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 81
This slide graphically shows the stack push operation for an interrupt. Note that the SRL register contains the IPL status bits so the CPU priority before the interrupt is saved. The user could potentially modify the values saved on the stack to allow the CPU to return to a higher or lower priority at the end of the ISR.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 82
The software has to declare the interrupt vector in order for the compiler and linker to create the correct jump to the location during a ISR. The interrupt attribute can be declared for a particular function to make it an interrupt function. There are standard names for the interrupt routines which are recognized by the linker. Certain attributes can also be associated with an interrupt routine, for example in the statement: void __attribute__((interrupt(save(Var1,Var2))))_INT1Interrupt(void), the variables Var1 and Var2 will be saved on the stack during the INT1 Interrupt. Alternatively the user may choose to save Var1 and Var2 on the stack by using the PUSH and POP instructions in the ISR itself.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 83
ISR can be interrupted by higher interrupts so nesting of interrupts is supported by default. In order to disable nesting, set the NSTDIS bit in the INTCON1 register. When this is done, the CPU priority is forced to 7 during all interrupts.
Lab 2
Using Interrupts
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 84
Lab 2 Light LED3 and LED4 using INT1 and INT2 Interrupt
Learn about interrupts
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 85
In this lab we will learn how to set up an interrupt, in this case, a INT1 and INT2 interrupt
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 86
In order to enable an interrupt, the user has to set the interrupt enable control bit: in this case the INTxIE bits. When an interrupt occurs, the interrupt status flag(IFS bit) is set and the ISR occurs. In the ISR, the user has to clear the IFS bit, in this case the INTxIF bit. The bit syntax and naming is well documented in the data sheets and the dsPIC Family Reference Manual. Another location to view the syntax is the device header file. For example p30f6014.h is the header file for the 84-pin dsPIC device used in the dsPICDEM 1.1 Development Board.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 87
The linker script file defines the syntax for the Interrupt Service Routine Call. Note the double (two) underscore before the INTxInterrupt, ( __ ).
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 88
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 89
Please use the already created workspaces in C:\wib1.1\lab2\lab2.mcw. The easiest way is to close the existing workspace under File->close workspace. Then open a new workspace by selecting File->open workspace and choosing C:\wib1.1\lab2\lab2.mcw. Scroll down to the light blue section where clearly marked labels indicate where code needs to be added:
Lab 2 Solution:
Line 46: Line 47: Line 67: Line 78: Line 69: Line 80: IEC1bits.INT1IE = 1; IEC1bits.INT2IE = 1; void _ISR _INT1Interrupt(void) void _ISR _INT2Interrupt(void) IFS1bits.INT1IF = 0; IFS1bits.INT2IF = 0;
Slide 90
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Lab 3
Using Interrupt Priorities
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 91
Lab 3 Set Timer Interrupts to Different Priorities Change CPU Priority in Code
Learn about interrupt priorities and interaction
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 92
In this lab, we will explore the interrupt priority scheme of the dsPIC device. We will learn the interaction between high and low interrupt.
At first the CPU priority will be set to 4. Timer1 priority will be set to level 3, which is setup to occur every 1/10 second. Timer2 priority is set to level 5 and is setup to occur every second. What we notice from the setup is that the Timer1 ISR will never occur, since its priority of 3 is lower than the CPU priority of 4.
Next what we will do is change the priority when SW1 is pressed. When SW1 is pressed we will set the CPU priority to 6, which is top priority in this program, so neither Timer1 nor Timer2 should interrupt it. Finally, when SW1 is released, the CPU priority is set to 2, so now it has the lowest priority and can be interrupted by Timer1 and Timer2.
Lab 3
A Picture is Worth a Thousand Words!
Reset
Slide 95
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
This is an interactive slide so read each slide note: On reset, the CPU priority is set to 0.
Lab 3
Initialize CPU, Timer1 and Timer2 Priority Level
Event 7 6 5 4 3 2 1 0
Pending
LED2 LED1
Reset
Slide 96
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
In the initialization, the CPU priority is set to 4, Timer1 to Timer3 and Timer2 to Timer5. So the Timer1 interrupt will never be serviced since its priority is lower than the CPU.
Lab 3
Timer2 Interrupt Occurs
Event 7 6 5 4 3 2 1 0
Pending
LED2 LED1
Reset
Slide 97
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
However when Timer2 interrupt occurs every second, the ISR will be executed and LED2 will light up. LED 1 will still be off.
Lab 3
Timer2 Interrupt Returns
Event 7 6 5 4 3 2 1 0
Pending
LED2 LED1
Reset
Slide 98
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Lab 3
Timer2 Interrupt Occurs
Event 7 6 5 4 3 2 1 0
Pending
LED2 LED1
Reset
Slide 99
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Lab 3
Timer2 Interrupt Returns
Event 7 6 5 4 3 2 1 0
Pending
LED2 LED1
Reset
Slide 100
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Lab 3
Code Changes CPU Priority When S1 Pressed
Event 7 6 S1 pressed Timer2 5 4 Initialized Timer1 3 2 1 Reset 0 LED4 LED2 LED1 SW1
Pending Pending
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 101
When SW1 is pressed, CPU priority is set to 6, so neither a Timer2 or Timer1 are serviced. So if LED2 is on, it will continue to stay on or if LED2 is off then it will continue to stay off.
Lab 3
Code Changes CPU Priority When S1 Released
Event 7 6 S1 pressed Timer2 5 4 Initialized Timer1 3 2 S1 released 1 Reset 0 LED4 LED2 LED1 SW1
Pending Pending
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 102
When SW1 is released, CPU priority is now set to 2, so both Timer1 and Timer2 will be serviced.
Lab 3
Pending Timer2 Interrupt is Handled
Event 7 6 S1 pressed Timer2 5 4 Initialized Timer1 3 2 S1 released 1 Reset 0 LED4 LED2 LED1 SW1
Pending
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 103
Lab 3
Pending Timer1 Interrupt is Handled
Slide 104
Lab 3
Return from Timer1 Interrupt
Slide 105
Lab 3
Timer1 Interrupt Occurs
Slide 106
Lab 3
Return from Timer1 Interrupt
Slide 107
Lab 3
Timer2 Interrupt Occurs
Slide 108
Lab 3
Return from Timer2 Interrupt
Slide 109
Lab 3
Timer1 Interrupt Occurs
Slide 110
Lab 3
Timer2 Interrupt Occurs
Slide 111
Lab 3
Return from Timer2 Interrupt
Slide 112
Lab 3
Return from Timer1 Interrupt
Event 7 LED4 6 S1 pressed LED2 Timer2 5 4 Initialized LED1 Timer1 3 SW1 2 S1 released 1 Reset 0 One click too many!
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 113
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 114
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 115
Lab 3 A Solution
Line 38: Line 51: Line 66: Line 73: Line 98: SRbits.IPL = 4; IPC0bits.T1IP = 3; IPC1bits.T2IP = 5; while(!SW1); while(IFS0bits.T1IF == 0);
Slide 116
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 117
dsPIC30F Peripherals
Real Time Clock 16 / 32 bit Timers Timer2 / Timer3 16 / 32 bit Timers Timer4 / Timer5
Timer1
Input Capture
(8 ch / 16-bit)
16-bit, 6-8 ch
Quadrature Encoder
(Timer6)
UART 1
UART 2
SPI 1
4 kB
AC97, I2S
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
CAN 1
I2C
SPI 2
CODEC interface
80 TQFP
Slide 118
The dsPIC device has a host of built-in peripherals to make it truly a single chip solution for design applications. Some of the key new peripherals are: High speed ADC: 10-bit 500 Kilo samples per second (kps) or 12-bit 100 kps with 16 deep buffers and automatic conversion setups. Details to follow. Motor Control PWM: These PWM are available as 4 complementary pairs or 8 independent PWMs with centered or edge aligned PWMs. Quadrature Encoder: with inputs QA, QB and index. The output is a 16-bit value marking the position of the rotor in a Motor control application. CODEC interface with AC97 and I2S support. Details to follow. The other existing peripherals are enhanced to give advanced and faster performance. For example the UART has a 4 deep buffer for Rx and Tx. The I2C has full multi-master support. The SPI has a 8- and 16-bit interface. Some devices also have two instances of the same peripheral. Now we will briefly touch upon some of the peripherals and their features.
Timers/Counters Overview
Five 16-bit General Purpose Timers / Counters
Similar functionality between all 5 timers
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 119
The dsPIC devices have up to five 16-bit general purpose timers. Key features: Each timer has its own 16-bit Period register, so when there is a match between the timer value and its period register, then an interrupt is generated and the timer is automatically reset to zero. No software intervention is required to reload the timer. Each timer has a gated timer operation Four of the timers can be concatenated to form two pairs of 32-bit timers
Duty Cycle Generator #4 Duty Cycle Generator #3 Duty Cycle Generator #2 Duty Cycle Generator #1 Dead Time Unit PWM Override Logic Dead Time Unit Dead Time Unit
PWM4H PWM4L PWM3H PWM3L PWM2H PWM2L Dead Time Unit PWM1H PWM1L Fault A Fault B
Two fault pins w/ programmable fault states Four PWM output pairs with output polarity control
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 120
This is a general block diagram of the Motor Control PWM module. Up to 8 outputs and 2 fault inputs are available. The module has a dedicated timebase and four PWM duty cycle generators. Each duty cycle generator is connected to a dead time unit to insert dead band during rising or falling edges of the PWM. This feature is useful for driving complementary pair transistors or FETs. Finally, a control logic block, produces complementary outputs on each pair of PWM output pins. Edge aligned or center-aligned PWM wave-shapes can be produced. The commutation logic block controls output polarity, programmable fault shutdowns and allows the user to manually manipulate the PWM pins for motor commutation. The A/D conversion trigger allows a sequence of A/D conversions to be triggered at any point relative to the PWM timebase.
Tcy
QEB/UP_ DN
Clock Reset
QEA/TQCKI GATE
0 1
TQCS UP/DOWN
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 121
Quadrature Encode Interface: A typical application may utilize the direction output as an up/down input control flag and either channel, A or B, as the count input trigger for a common up/down counter. The counter in an incremental system will increment or decrement as required to maintain a relative position or count output. The x2 or 4 Measurement mode relates to whether the up/down counter will increment based upon both edges from one channel or both edges from both channels. The x4 Measurement mode will inherently provide finer resolution data on motor position. For example, with a 512 line count (N) encoder and implementing a x4 Measurement mode, the position angle resolution is: = 360 / 4 x 512 = 0.17578125 per incremental count For the x2 Measurement mode = 360 / 2 x 512 = 0.3515625 per incremental count For those applications which utilize an incremental encoder but the encoder does not have a index pulse output, the position counter can be reset by using the Max Count Compare register or letting the counter roll over. If the Max Count reset mode is used when the position counter equals the Max Count Compare register, the Position Count register will reset to zero and the revolution counter will be incremented.
DCI Features
Support for PCM Audio Codecs
DCI supports speech, modem and general audio applications
Automatic Synchronous Serial Data Transfer Support for I2S and AC97 Protocols TDM Features Support up to 16 Data Time Slots Module has up to 4 Word Buffer (16-bit words) Master or Slave Operation Separate Baud Generator for SCK Signal
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 122
The Data Converter Interface (DCI) module allows the dsPIC DSC to be connected to audio coder/decoders (codecs). Speech processing, soft-modems and general audio algorithms require high-quality analog input and output to the DSP device. These applications require A/D and DAC resolutions between 13 and 16 bits. The DCI is a type of synchronous serial interface with four I/O pins; SCK, SDI, SDO and FS. A data transfer is initiated by the Frame Sync (FS) signal. These transfers occur with zero CPU overhead at the data sampling rate. The FS signal can be generated by the DCI (master) or by the codec (slave). Either device may generate the SCK, which is continuous in most applications. The internal codec clocks may be derived from the SCK signal using a PLL. One or more data words may be transferred when the FS signal is generated. The DCI supports TDM transfers with up to 16 time slots per data frame. This is an important feature since many codecs transfer both audio and control data at the same time. The DCI has enable bits that determine which of the 16 time slots are transmitted/received. Thus, only the time slots of interest have to be buffered. The SDO pin is automatically tristated during unused time slots so other devices may be attached to the serial TDM bus. The TDM features of the DCI permit data to be shared in multi-channel/multi-processor DSP applications. Up to four data words may be buffered before an interrupt is generated. This feature saves interrupt processing overhead. The buffers may be used in one of two methods. First, multiple data samples for an audio channel can be buffered before processing. This technique is called block processing. Second, various time slots in a data frame can be stored in the buffer before interrupting the CPU. Therefore, all of the control and data samples are available at the time of the interrupt. The DCI has a SCK generator optimized for codec applications. Typical SCK frequencies vary between 16x and 256x the audio sampling rate. Typical audio sampling rates for targeted dsPIC audio applications include 8 kHz - 32 kHz.
CSCK
COFS
CPU interrupt
CSDI
CSDO
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 123
This is a block diagram of the DCI module. The module is organized as a Serial Shift register connected to a block of memory through a local AGU. The SCK signal may be generated internally or provided to the SCK pin from another device. The FS signal can be generated internally (DCI master) or provided by the codec (DCI slave). The module has control bits to select the data word size (up to 16-bits) the data frame length (up to 16 data words) and the type of FS signal that is generated/received. The buffer AGU is incremented each time data is transmitted or received during a timeslot. The DCI may be configured to buffer 1 to 4 data samples. An interrupt is generated when the buffer is full or has processed the requested quantity of samples.
UART Module
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 124
We will discuss and go into hands-on exercise for a few of the peripherals to give the user a taste of how to program and use them, as well as talk about some of the more advanced features of the peripherals. The first is the UART.
UART - Overview
Serial TX and RX of 8-bit or 9-bit Data
Full-duplex, asynchronous communication Support for communication protocols such as RS-232, RS-422, RS-485 and LIN 4-deep transmit and receive buffers Transmit and receive interrupts Error detection Support for receiver addressing
Additional Features
Loopback mode Alternate TX/RX pins on some devices Wake-up from SLEEP
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 125
The UART module is used for transmission and reception of 8-bit or 9-bit data over a serial transmit line and a serial receive line. Many dsPIC30F devices contain two UART modules and therefore have two pairs of transmit and receive pins. UART communication is full-duplex, which means that a transmission and a reception can proceed simultaneously. It is also an example of Asynchronous communication, as each communicating entity is responsible for internally generating its own timing. The UART module may be used with standard protocols such as RS-232, RS-422, RS-485 and Local Interconnect Network or LIN. Besides basic transmission and reception capabilities, the UART has a number of useful features. For example, it includes independent buffering of up to 4 characters of transmitted data and up to 4 characters of received data, detection of communication errors, generation of interrupts and the ability to address individual UART nodes. Other features, which we will discuss in later slides, are Loopback, alternate communication pins and Wake-up from SLEEP.
UART
ABAUD ICx 0 1 To Input Capture Baud Rate Generator UxRX 0 1 LPBACK Module Control / Error Handling Logic
Error Status
16 Divider
UxRSR
Load UxRSR to Buffer PF
UxRXREG
UxTSR
Load UxTSR
UTXBRK
UxTXREG
This is a simplified Block Diagram of the UART module in a dsPIC30F device. Note that the communications interface consists of only 2 pins: UART Transmit and UART Receive. Observe also the 4-deep First In First Out (FIFO) buffering of data. The Transmit Shift register is used to shift out data through the UART Transmit pin, whereas the Receive Shift register is used to shift in data through the UART Receive pin. Data in successive locations of the transmit buffer are transferred to the Transmit shift Register and Receive Shift register contents are transferred to the Receive Buffer. Keep in mind that only the first location of the transmit buffer is memory-mapped and is therefore user-accessible as the UART Transmit register. Similarly, only the first received character of the receive buffer is user-accessible as the UART Receive register. There are some features provided mainly to support the LIN protocol. These features include autobaud features which allows the Rx pin to be directly connected to a capture input (which would have to be previously setup to accept this input). The timing of the incoming reception is detected and the new baud rate can then be appropriately set. Please note that the interrupt logic can be set to interrupt the CPU at the first, second, third or fourth serial byte reception.
The UART module contains a 16-bit baud rate generator, which is used to provide timing synchronization of data transfer and all other UART events. The Baud Rate Generator is memory-mapped and therefore user-accessible. Due to the communications being asynchronous, the user must configure the baud rate generators of the transmitting device, as well as the receiving device, such that both have the same baud rate. As is apparent from the equation, the maximum baud rate that can be attained is a sixteenth of the instruction cycle frequency Fcy.
UART
Registers to Configure the UART
UxMODE, UxSTA, UxBRG
When using the UART, the user has to set the following registers: UxMODE, UxSTA and UxBRG where x = 1 or 2 If the user is using C, then C libraries are available, which can greatly help the user when configuring and using the UART. C libraries help to initialize the UART, read UART data and write to the UART. For those users programming in the PC world, there are classic C libraries like getc, putc, gets and puts functions which are also implemented. These functions are a great help when using the UART. In the next lab, we will use these UART functions in C.
Lab 4 Instructions
Use Lab4.mcw Already Defined
libp30F6014.a and UART.h are already in the project
The workspace is already setup in Lab4.mcw. Choose the workspace in C:\wib1.1\lab4\lab4.mcw Key points to note: In order to use the C libraries, the user has to use the generic peripheral library module which is libp30f6014.a in this case. The user must also select the appropriate header file for the peripheral chosen, which in this case is UART.h. Note that these libraries have already been included in the project Lab4.mcw. Lab 4 consists of setting the UART baud rate to 9600 and transmitting a string of characters. To initialize the UART we will use the OpenUART1(U1MODEvalue,U1STAvalue,baudvalue); function, which has 3 parameters associated with it. The user has to define the baud value parameter. The string message displayed is Microchip, terminated with a NULL character. To transmit the characters, the user should use the WriteUARTx(int variable), function. Note that this function passes an int parameter not a Char. So if the actual data is char then it should be type cast as an int during the function call. Note the received buffer has already been setup to receive the transmitted characters by using the loopback feature of the dsPIC UART. The received characters are displayed on the LCD screen. Edit the program, compile and then run. Press SW1 on the board and one transmission should start. The word Microchip should be displayed on the LCD screen.
Lab 4 Instructions
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 130
Please look at the appropriate location in the main text file and make the required changes. Note that FCY and BAUDRATE are define so the user can directly use the formula for baud value provided in the slides.
Lab 4 Result
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 131
Edit, compile and run the program With the program running hit SW1 and with each hit Microchip will be displayed on the LCD screen as above.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 132
A/D Converters
10- or 12-bit High Speed, Multi-channel
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 133
12-bit A/D
12-bit resolution with +/- 1-bit accuracy 100K samples/second conversion rate Up to 16 analog inputs, single S/H amplifier
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 134
There are two ADCs available on dsPIC DSCs. The motor control family of devices have the 10-bit ADC which has a 500 kps conversion rate and has 4 simultaneous sample inputs. This is important for motor control apps where simultaneous sampling of current and voltage is important. The General Purpose and Sensor Family has a 12-bit ADC with a 100 kps conversion rate and one sample and hold.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 135
Some of the common features of the ADC are: External VREF capability with an analog range between VREF + and VREF-. The input is unipolar differential and the conversions are saved in 16 dual port buffers. It is possible to set the conversion for different trigger sources: PWM, timer timeout, INT pin input, etc. Several scheduling options are also available. Some of these will be discussed in the next few slides.
Conversion Control
BUFFER 16 deep
Data Format
Bus Interface
Input MUXes
AN15
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 136
The basic 12-bit ADC block diagram is as shown. There can be a max of 16 inputs MUXed into one sample and hold circuit and the converter. The result is saved in the 16 deep buffer and can be loaded for different sampling sequences and conversion control options. The saved data can then be read by the CPU in four different formats: signed and unsigned integer/fractional formats.
The are several methods for the sequence of sampling. One such method is to set the ASAM or Automatic Sample bit. In this method, the sampling automatically starts right after the conversion is done. This optimizes the sampling time. Another method is by not doing an automatic sampling but using manual sampling. Here the user would have to set the SAMP bit for sampling and clear SAMP bit to end sampling and start conversion.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 138
The conversion start can be controlled by several methods: The manual method involves the SAMP bit being set/reset by software as discussed in the previous slide. Auto sample time involves setting a internal TAD count. When this count times out, the conversion starts. Another method is from a PWM pulse trigger. This method is very useful in motor control applications where the user is interested in measuring the current consumption of the motor, thereby determining the torque or load on the motor. The current value however is only valid when the PWM is driving the circuit. Hence, the PWM trigger mechanism only reads the current when the PWM is active on that circuit. Still other methods of conversion starts are Timer3 period match or an active edge on a INT0 pin. As can be seen, the ADC is very flexible.
12-bit A/D Converter When is the Result Available? SMPI Bits Specify Samples per Interrupt Interrupt on Completion of nth Conversion
ADIF bit in IFS0
ADCON2 Register
VCFG2
bit15
VCFG1
14
VCGF0
13
OFFCAL
12
11
CSCNA
10
bit8
BUFS
bit7
SMPI3
5
SMPI2
4
SMPI1
3
SMPI0
2
BUFM
1
ALTS
bit0
Slide 139
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Once the conversion is done, the ADC allows the user to save the digital data in a buffer. There are 16 buffers available to save the results. This allows the user to develop applications where multiple sample/conversion are done and saved in the buffer. Only when the buffer is full or nearly full, the CPU, can be interrupted and the ADC values retrieved. This allows efficient use of the CPU as well as the ADC. The SMPI bits allow for an interrupt to be generated at the 1st, 2nd, 3rd, 4th 16th load of the ADCBUF. Please note that the loading of the buffer is done very sequentially. So for example, if the user loads say 16 ADC values from a sequential scan of 16 inputs starting from AN0 to AN15 then after the interrupt, the ADCBUF5 register value will correspond to the value of the AN5 input.
As mentioned in the last slide, the result is stored in the ADCBUF0 ADCBUFF registers. This buffer is very versatile and can be divided into two using the BUFM bit. This Fill mode bit allows one 8-bit section to be loaded while the other is being accessed by the CPU.
. .
ADCBUFx
AN0 AN15 - AN1 AN0 AN15 - AN1
+ CH 0 -
CHXSB
13
CH0NB=0
12 11
CH0SB<3:0>=0000
10 9 bit8
CHXNA<1:0>
bit7 6
CHXSA
5
CH0NA=1
4 3
CH0SA<3:0>=1111
2 1 bit0
Slide 141
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Let us explore some examples on how to use the ADC. In the above setup, the ALTS or alternate sampling mode is used. In this mode, the user can setup two modes. The first mode uses the MUX A inputs are used to sample AN0. In the second mode, the MUX B inputs are used to sample AN15 minus AN1 or the difference between the AN15 input and the AN1 input. In this setup the ADC will alternate and sample AN0 ,then AN15-AN1, then AN0, then AN15-AN1 and so on until the interrupt occurs. The ADCBUFx registers will thus reflect the conversion values.
ADCBUFx
AN0 AN3 AN4 AN6
+ CH 0 VREF-
ADCSSL Register
bit15 14 13 12
CSSL8=0
bit8
CSSL7=0
bit7
CSSL6=1
6
CSSL5=0
5
CSSL4=1
4
CSSL3=1
3
CSSL2=0
2
CSSL1=0
1
CSSL0=1
bit0
Slide 142
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Another example is to scan a series of inputs sequentially. To use this mode the CSCNA bit is set and the ADCSSL register is used to indicate which channels are to be scanned by setting the appropriate channel bits. So in this case shown in the slide, the bits which are set are for channel AN0, AN3, AN4 and AN6, the rest are zero. So after the first scan, the first value in the ADCBUF will be AN0 followed by AN3 and so on. These examples are used to show the flexibility of the ADC on dsPIC device. It can be truly said that the ADC can be setup for independent operations on the dsPIC MCU with minimal intervention needed from the CPU except to retrieve the results once the most efficient ADC conversion scheme is completed.
Lab 5 Setup
Channel Scanning on MUX A - CSCNA = 1
RP1
ADCBUFx
AN4 AN5 AN6 AN4 AN5 AN6 AN4 AN5 AN6 AN4 AN5 AN6
0 1 2 3 4 5 6 7 8 9 A B
AN15 AN14
. .
RP3
+ CH 0 VREF- = GND
RP2
CSSL8=0
bit8
CSSL7=0
bit7
CSSL6=1
6
CSSL5=1
5
CSSL4=1
4
CSSL3=0
3
CSSL2=0
2
CSSL1=0
1
CSSL0=0
bit0
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 143
In Lab 5, we will use the scan feature on the dsPIC family. The pot marked RP1 is connected to AN6, RP2 is connected to AN4 and RP3 is connected to AN5. The 3 pots are scanned four times to give us a total of 12 ADC values. At that point, an ADC interrupt is generated. The sample time is automatically generated by using the TMR3 match. The match occurs every 10 ms. Each pot is sampled for 10 ms and then converted in about 15 us. This is repeated automatically 12 times. When the ADC interrupt is generated, the program averages four readings of each of the ADC inputs and displays the average value in hex on the LCD screen. The pot values are transmitted over the serial port which is placed in a Loopback mode. So the received data is displayed on the LCD screen.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 144
In Lab5.mcw workspace is located in C:\wib1.1\lab5\lab5.mcw. On the dsPICDEM 1.1 board, there are 3 potentiometers RP1, RP2 and RP3 connected to AN6, AN4 and AN5 respectively. Steps for the user are highlighted in Yellow: 1. Set the ADC for Auto Sample mode using TMR3 match. The TMR3 is already setup to match every 10 ms so there is no need to set TMR3 registers. 2. Set the ADC to scan AN4, AN5 and AN6 3. Set the ADC to interrupt after 12 sample/convert sequences. The rest of the setup is already done. The user only needs to write lines of code needed to implement the above scheme.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 145
The 3 lines of code marked above are 3 registers in the ADC module, which need to be set for the scan routine mentioned earlier. The comments tell you what needs to be done in each instance.
Lab 5 Result
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 146
The result is displayed on the LCD screen as above. Move the 3 pot wipers and see the values change in the 3 locations.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 147
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 148
Up until this point we have talked about the dsPIC30F architecture, its powerful instruction set, interrupt handling and wealth of peripherals. Now we will dwell on the main feature of the dsPIC DSC namely the DSP engine and its use in real application. In order to keep it simple let us talk today about one very commonly used DSP function namely digital filtering. Before we do that, lets review what digital filtering is all about.
Digital Filters
What is Digital Filtering?
The digital processing of an input signal to produce a desired output signal with a certain frequency response or characteristic
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 149
Digital filtering is the digital processing of an input signal to produce an output signal which meets certain desired characteristics. A good real life example would be if you dont want to hear the scratches on a vinyl album in an audio application then you would design a filter which gets rid of the high frequency tick sound of the scratch without losing any of the high frequency fidelity of the sound or music. Most commonly, this would be know as notch filter. Like all electronics, such problems were dealt earlier on using analog circuits however with the advent of high speed DSPs, the analog circuit has been circumvented by the digital world. Let us look at some of the reasons: Digital filters are MUCH easier to tune since there are no component (capacitor, inductor or resistor) tolerances to consideration when designing the filter. Since they use digital processing, they dont have additional active or passive components which would typically draw more power, so they are low power. The are programmable since all the reprogramming is done in the algorithm or firmware. They are also less immune to temperature and age drift since again the digital filter is an algorithm.
Digital Filter Types Digital Filters are Classified into Two Types
Finite Impulse Response (FIR) Infinite Impulse Response (IIR)
FIR and IIR Filters can be Designed to Provide Some Desired Response
Low Pass Filter (passes low frequencies) High Pass Filter (passes high frequencies) Band Pass Filter (passes a frequency band) Band Stop Filter (stops a frequency band)
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 150
There are two types of digital filters: Finite Impulse Response (FIR) and Infinite Impulse Response (IIR). Using these two types, the user can design a Low/High/Bandpass filter and Finally, a Bandstop filter. What are these types of filters? Lets see the next slide ...
DSP Features
All DSP Operations Execute in a Single Cycle Single Clock Cycle MAC Instruction:
Dual Address Generator Units (AGU) support parallel operand (data and coefficient) fetches Accumulator write-back
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 151
The dsPIC DSC provides the best in class embedded control features of a 16-bit MCU, many applications can also benefit by employing DSP techniques to filter input signals or to analyze incoming data streams. Speed is essential to digital signal processing. You must complete the computations on the current data before the next data set arrives. This dictates that certain hardware functions exist on chip. The dsPIC family provides a performance solution that addresses the majority of embedded signal processing applications without the high cost of competing DSPs. The dsPIC30Fs Harvard Architecture is complemented with dual Address Generation Units, or AGUs, that support dual data fetches. A rich set of DSP instructions are provided and all operate in a single cycle. The Multiply and Accumulate Instruction (MAC), for example, can multiply and add or accumulate two operands, update two address pointers, fetch the next two operands, and transfer out the accumulator value, all in a single cycle. For DSP algorithms that only require multiplying without the accumulation, such as for FFTs, the dsPIC30F also supports 16-bit signed or unsigned fractional or integer math. Some applications such as space vector or PID loop motor control require two or more concurrent filters. Other algorithms, such as FFTs, require support for real and complex values. To support these and other applications which require multiple concurrent filters, the dsPIC30F provides two separate DSP accumulators. Each accumulator is 40-bits wide, reducing the need to scale input data. Optionally, overflow can be avoided entirely by enabling Saturation Mode. Each accumulator has its own overflow flags in the DSP status register, and separate branch instructions for each accumulator on overflow or data saturation.
DSP Features
40 Stage Barrel Shifter (up to 16-bits Left or Right)
Shift accumulators, W registers or memory
Modulo Addressing (for Filters): Both AGUs Bit Reversed Addressing (for FFTs): One AGU Zero Overhead Instruction Loop Support
REPEAT: Repeat next instruction N times DO: Repeat loop N times Constant or variable loop count
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 152
But thats not all! The dsPIC30F provides more features to ensure optimal algorithm efficiency. Data transferred from the 40-bit accumulators passes through a 40-bit barrel shifter. This hardware can shift the data up to 16-bits left or right before storing the results, all in the same instruction cycle. For added flexibility, the barrel shifter can also operate directly on the 16 general purpose registers or on data memory. Data transferred from the accumulators may be rounded before being stored. Two different ways of rounding, conventional and convergent, are provided. To support digital filtering, special support for circular buffers is provided by a modulo addressing mode. For FFT support, a bit reversed addressing mode is provided that automatically calculates the next matrix element address. Finally, special hardware is provided to support zero overhead looping. This equates to better optimized DO and REPEAT loops commonly used in DSP algorithms as well as other common MCU tasks.
Saturate
16
40 40
Barrel Shifter
Enable 16
40 40
Sign Extend
Zero-backfill
16
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 153
This slide shows a top level block diagram of the dsPIC30F DSP engine and how each of the block are interconnected. The basic components are Multiplier and data Scaler Sign-Extend and Zero-Backfill Logic Barrel Shifter Adder and Accumulators Round and Saturation Logic blocks
The DSP engines obtains it source operands from the W array for MACclass instructions, and from the X-bus for all other instructions requiring operand data. MAC-class instruction operands are pre-fetched concurrently from the X and Y data buses into specified W registers while the current instruction is executing using previously fetched data. All writes from the DSP engine are executed across the X-bus. We will look at each of the major components in more detail in module 8.
X Data Bus
Y prefetch source
Y prefetch destination
X prefetch destination
Basic Syntax
Optional Arguments
Slide 154
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
This slide shows the syntax of a MAC instruction. Note that only the source operand registers and the destination accumulator are mandatory arguments, whereas the other arguments are optional. The following operations may be performed in a single instruction cycle: 2 data fetches - one each from X and Y data space 2 updates to the X and Y effective addresses used for the data fetch operations 1 operation on Accumulator A or B with the data in two W-registers 1 write back of the other accumulator, Accumulator B in this example
Using dsPIC Digital Filter Design Simple as 1,2,3. Create a High Pass Filter with a Cutoff Frequency of 700 Hz
Design -> FIR Window Design -> Highpass
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 155
So lets design a filter using dsPIC Digital Filter Design or dsPIC FilterLite design. Open the program by double clicking on the icon. Then click on Design -> FIR Window Design -> Highpass. The window above will appear, select Highpass then Next. Note: The instructor can choose to give the dsPIC Digital Filter Design tool to the audience and ask them to step through this procedure in synch with these slides.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 156
Use the above values and fill in the highpass filter parameters. After these are filled in, hit Next. Please remember, you as a user will most likely know the parameters for your filter. The parameters here are for our filter and well explain the reasons for the value shortly.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 157
The design tool now offers you a whole lot of filter types which you can design to. Obviously there are some which have high tap value. The tool designer has marked that filter which is optimized for dsPIC designs. In this case, it is the Kaiser filter with 49 taps. Hit Next ...
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 158
Now we see the frequency, phase, impulse and step responses of this filter. You can go back and modify the input criteria before generating the filter taps. Point to note is the impulse response. You can see that a impulse basically stabilized after a period of time, which proves once again the stable nature of FIR filters.
So the filter parameters are complete. To generate code for the dsPIC devices, simply select: Codegen, then Microchip then dsPIC30. Select the header file and save the coeff in as x data space. Hit okay and viola - the code is generated. This generates a dsPIC30F assembly source file which contains the filter tap coefficients in a constant table. The format matches the FIR/IIR filter library needs.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 160
You can see the filter taps here as .hword definitions. The number of taps are also defined for the filter library. The actual code for the FIR filter calculations is located in the filter object module which is linked into this project. Please do a rough count and you will notice 49 coeff values for the 49 taps in the Kaiser filter we chose.
Notes: 1. Projected Results 2. Buyers Guide to DSP Processors, 2001 Edition 3. Buyers Guide to DSP Processors, 1999 Edition
Results (c) 1999-2004 Berkeley Design Technology, Inc. Contact info@BDTI.com for info.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 161
Addressing high-end audio and communications tasks requires performance that most cost sensitive embedded control applications neither need nor can afford. The goal of the dsPIC30F is to provide a performance solution that addresses the majority of embedded signal processing applications without the high cost of competing DSPs. We think we hit the mark, but you dont have to take our word for it. This data is from BDTI, an independent DSP industry benchmarking firm. It compares the number of instruction clock cycles each device takes to execute a certain DSP algorithm, with the dsPIC30F results normalized to one. As you can see, the performance compares very well with other embedded control DSP devices. Take a close look at the control benchmark. This specific benchmark speaks to the efficiency of the dsPIC30F device in support of a wealth of embedded control based applications.
Notes: 1. Projected Results 2. Buyers Guide to DSP Processors, 2001 Edition 3. Buyers Guide to DSP Processors, 1999 Edition
Results (c) 1999-2004 Berkeley Design Technology, Inc. Contact info@BDTI.com for info.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC Slide 162
Heres the same DSP algorithms compared by execution time. Even though the dsPIC30F is more efficient, other devices running faster than the dsPIC30F can produce quicker results on some DSP routines. However, the dsPIC30F was designed to optimize both MCU and DSP performance. Notice the circled MCU control algorithm row in the middle. The dsPIC30F excels on performing control tasks compared to typical DSP devices in the same operating MIPS region.
Additional Benchmarks
Benchmark FIR Filter Tap Biquad IIR (4 coeff) (single sample) PID (core only) Cycle Count 1 8 Execution @ 30MIPs 33 ns 267 ns
233 ns
1.02 us
600 ns
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 163
Here is code to base full benchmark for PID with error calculation, limit check, and anti-windup. This is realistic code, because it is a generic callable fxn. User passes pointer to structure that contains setpoint, feedback measurement, gains, integral, output limits, and output. See PI.inc for details of structure.
;;------------------ ASM30 API for PI routines --------------------; PIParm stucture: .equ PI_qdSumL,0 .equ PI_qdSumH,2 .equ PI_qKp,4 .equ PI_qKi,6 .equ PI_qKc,8 .equ PI_qOutMax,10 .equ PI_qOutMin,12 .equ PI_qInRef,14 .equ PI_qInMeas,16 .equ PI_qOut,18 .equ NKo,4
Interfacing to the DSP Library DSP Library is Both C Callable and Assembly Callable C Interface Requires Just 2 files:
LIBDSP.A and DSP.H Provided in C30Tools directory
Library Typedefs
typedef int fractional;
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 164
If you want to use this library, you have to include the library object module LIBDSP.A into our project so that it is linked with your code. You also have to include the DSP.H header file into any source files that will call these functions. Lastly, the libraries operate in fractional datatypes, which this typdef defines as integers. Please note that we have already included these files in the project for Lab 6.
Digital Filters and the DSP Library Library Filters Operate on Blocks of Data One Filter Initialization Call is Required FIR
FIRDelayInit (&fir_test1Filter); FIR (BLOCK_LENGTH, &filter_output_array[0], &array[0], &fir_test1Filter);
In order to use the FIR filter code generated, the user has to first call the FIRDelayInit routine to initialize the filter taps to prevent startup noise/instability. This only needs to be called during power-up to prevent random tap data. Then every time you want to use the filter, you call the FIR library, providing a pointer to your input and output data, size and tap coefficient table pointer.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 166
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 167
The dsPICDEM 1.1 Demonstration Board has hardware which can generate sine waves. We have used these to generate 3 sine waves and have mixed them up to give a rather distorted waveform of 847, 367 and 123 Hz. We will design a digital filter at a high pass of 700 Hz and remove the lower 367 and 123 Hz signals leaving only the 847 Hz and a nice clean waveform. All routines are in C. Extra credit will be given to those who use TMR1 and determine the time taken for the filter to run.
Input Signal
Pressing the SW1 Button Displays the Filter Input on the LCD Display:
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 169
A charting function has been implemented to display the waveforms on the LCD screen. If you hit the SW1 switch, you will be able to see a replica of the waveform above. The FIR is not implemented so hitting SW2 will only show a straight line. Once the filter is implemented and called, the waveform will look much better.
Output Signal
Pressing the SW2 Button Displays the Filter Output on the LCD Display:
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 170
Once the filter has been used and implemented, the filtered wave form will look as above.
Conclusion
The dsPIC30FXXXX Architecture and Peripheral Set is Ideal for DSP Applications Development Tools are Versatile, Inexpensive and Easy to Use When Developing Applications DSP Tools Reduce Mathematical Complexity With Easy Code Generation DSP Application Notes and Reference Designs: Motor Control, Filters, Speech and Connectivity
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 171
The DSP architecture and peripheral set is ideal for many DSP as well as MCU applications. Microchip development tools are also very easy to use and are inexpensive. This help the customer during the development process. DSP tools shorten the time taken to configure and handle complex mathematical equations during DSP-related processes. They also make the DSP process simple by generating code automatic. Finally, DSP application notes and reference designs are available from Microchip, to help customers in their own motor control or filter or speech recognition applications.
Survey
Please dsPIC30F Workshop in a Box Survey at:
http://techtrain.microchip.com/surveys/dspic/dspic_wsiab.aspx
Those Who Complete the Survey Will be Entered in a Drawing for Several Valuable Prizes
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 172
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 173
The Microchip name and logo, the Microchip logo, Accuron, dsPIC, KeeLoq, MPLAB, PIC, PICmicro, PICSTART, PRO MATE, PowerSmart and rfPIC are registered trademarks of Microchip Technology Incorporated in the U.S.A. and other countries. AmpLab, FilterLab, microID, MXDEV, MXLAB, PICMASTER, SEEVAL, SmartShunt and The Embedded Control Solutions Company are registered trademarks of Microchip Technology Incorporated in the U.S.A. Application Maestro, dsPICDEM, dsPICDEM.net, dsPICworks, ECAN, ECONOMONITOR, FanSense, FlexROM, fuzzyLAB, In-Circuit Serial Programming, ICSP, ICEPIC, Migratable Memory, MPASM, MPLIB, MPLINK, MPSIM, PICkit, PICDEM, PICDEM.net, PICtail, PowerCal, PowerInfo, PowerMate, PowerTool, rfLAB, Select Mode, SmartSensor, SmartTel and Total Endurance are trademarks of Microchip Technology Incorporated in the U.S.A. and other countries. Serialized Quick Turn Programming (SQTP) is a service mark of Microchip Technology Incorporated in the U.S.A. All other trademarks mentioned herein are property of their respective companies.
2004 Microchip Technology Incorporated. All Rights Reserved. dsPIC Workshop in a Box . dsPIC
Slide 174