dsPIC Elmer 166 An introduction to using the dsPIC John J.
Elmer 166 dsPIC Elmer 166 An introduction to using the dsPIC Edition 1 Author John J. McDonough, WB8RCR wb8rcr@arrl.net The text of and illustrations in this document are licensed by John J. McDonough, WB8RCR under a Creative Commons Attribution--Share Alike 3.0 Unported license ("CC-BY-SA"). An explanation of CC-BYSA is available at http://creativecommons.org/licenses/by-sa/3.0/.
Preface v 1. Overview 1.1. Overview of Microcontrollers ............................................................................................... 1.2. The dsPIC30F4011 ............................................................................................................ 1.3. Building Programs ............................................................................................................. 1 1 2 3 2. First Program - Blink an LED 5 2.1. Creating the project ........................
Elmer 166 C.4. C.5. C.6. C.7. C.3.3. Structure and Union types ..................................................................................... Control Flow ................................................................................................................... Functions and Program Structure ..................................................................................... The C preprocessor ...............................................................................................
Preface v
vi
Chapter 1. Overview 1.1. Overview of Microcontrollers 1 A microcontroller is a microprocessor intended for embedded applications. Microcontrollers differ from traditional microprocessors in a few key ways: 1. Microcontrollers generally are totally self-contained, requiring no external support other than power and sometimes a clock source. 2. Microcontrollers generally include non-volatile program memory so that the program need not be read from external media during startup.
Chapter 1. Overview Figure 1.1. dsPIC Overview Table 1.1. The dsPIC30F Family Minimum Maximum dsPIC30F4011 Program Memory 6K 144K 48K Data Memory 256 8192 2048 EEPROM Memory 0 4096 1024 Pin Count 18 80 40 UART 1 2 2 SPI 1 2 1 I2C 1 2 1 CAN 0 2 1 Comparators 0 4 4 A/D Channels 6 18 9 Quadrature Encoder Inputs 0 1 1 Timers 2 5 5 Volume Price $2.23 $7.25 $4.02 Quantity One Price $3.09 $11.94 $5.
Building Programs 1.3. Building Programs Figure 1.3.
4
Chapter 2. First Program - Blink an LED The first program will be the classic "flash an LED" program. This provides a simple look into programming the PIC without any unnecessary complexities. Well, maybe without too many complexities. 2.1. Creating the project Everything done within MPLAB-X is done within the context of a project, so the first order of business is to set up a project. Begin by launching MPLAB-X, either by double-clicking the desktop icon or selecting the MPLAB-X IDE from the menu.
Chapter 2. First Program - Blink an LED The first time MPLAB-X is launched it will display the MPLAB-X "Start Page". The start page has many interesting links worth pursuing at a later date. Figure 2.2. MPLAB-X Opening Screen On successive launches, MPLAB-X will open with the same project that was opened when it was closed. To create a new project, click the new project button at the left of the toolbar, or click "Create New Project" under "Dive In" on the start page. Figure 2.3.
Creating the project The first panel chooses the overall type of project. Almost always the default selections of "Microchip Embedded" and "Standalone Project" are the desired choices. Figure 2.4. Select type of project The next panel selects the specific processor. For this lesson, choose the "16-bit DSCs (dsPIC30)" Family and within that family, the "dsPIC30F4011" Device. Figure 2.5.
Chapter 2. First Program - Blink an LED The next selection is for the hardware programming or debugging tool. In this exercise, the simulator will be used to get a detailed view of what the program is doing before actually downloading it into the dsPIC, so select "Simulator". Figure 2.6. Select hardware tool In the next panel, the compiler is selected. Choose "XC16". (The version and path to the compiler may be different.) Figure 2.7.
Creating the project In the final project wizard panel, enter a name for the project. Figure 2.8.
Chapter 2. First Program - Blink an LED Two panes will open on the left of the main MPLAB-X window. The upper pane (labeled Projects) will list the various possible components of a project, while the lower will show an overall view of the project (called the "Dashboard"). In addition, a "Tasks" pane will open beneath the Start Page. Figure 2.9.
Editing and Compiling the Source 2.2. Editing and Compiling the Source Once a project has been created, the next order of business is to create a file in the project to contain the code. Within the upper left (Project) pane, right-click on "Source Files", roll over "New" and select "Empty File ...". Figure 2.10.
Chapter 2. First Program - Blink an LED A dialog will open allowing you to provide a name for the project. Be certain the filename you choose ends in .c. At this point it is worth considering your conventions for naming source files. It is the C tradition to name the mainline of a C program main.c. However, there will be a lot of main.c's, so it could be preferable to name the mainline source the same as the name of the project. If you really like to type, you may prefer to combine both, as shown below.
Editing and Compiling the Source Figure 2.12. Add code Figure 2.13.
Chapter 2. First Program - Blink an LED 2.3. Running the Simulator Figure 2.14. Set a breakpoint Figure 2.15. Debug program button Figure 2.16.
Running the Simulator Figure 2.17. Second toolbar row Figure 2.18.
Chapter 2. First Program - Blink an LED Figure 2.19. Create a watch expression Figure 2.20. Select the variable to watch Figure 2.21. Observe the value change 2.4.
Debugging the program Figure 2.22. Download program button 2.5. Debugging the program 2.6. Documenting the program /* Exercise01_main.c - Blink an LED */ #include int main() { /* Set the LED pin to be an output */ TRISDbits.TRISD1 = 0; /* Keep doing this a very long time */ while( 1 ) { /* Turn the LED on */ LATDbits.LATD1 = 0; /* Turn the LED off */ LATDbits.LATD1 = 1; } } Figure 2.23.
Chapter 2. First Program - Blink an LED // Ex02.c - Blink an LED #include int main (void) { _TRISD3 = 0; while (1) { _LATD3 = 1; _LATD3 = 0; } } Provides definitions for the dsPIC registers. Sets the pin connected to the LED to be an output. It will take some time before one becomes zero. Turns off the LED. Turns on the LED.
Chapter 3. Configuration Registers // Configuration fuses _FOSC (XT) _FWDT (WDT_OFF) _FBORPOR (PWRT_16 & BORV27 & MCLR_EN) _FGS (GWRP_OFF & CODE_PROT_OFF) // // // // 7.3728 xtal / 4 = 1.
20
Chapter 4. Timers // Set up timer // 7.3728 MHz * 16xPLL /Fosc/4 / 256 prescaler / 57600 counter // timer should fire twice per second. Since the LED // will toggle once per interrupt, the LED should come on // once per second for a half second. TMR2 = 0; // Clear timer 2 PR2 = 57600; // Timer 2 counter to 576000 T2CON = 0x8030; // Fosc/4, 1:256 prescale, start TMR2 if ( IFS0bits.T2IF ) { IFS0bits.
22
Chapter 5. Interrupts // Set up timer // 7.3728 MHz * 16xPLL /Fosc/4 / 256 prescaler / 57600 counter // timer should fire twice per second. Since the LED // will toggle once per interrupt, the LED should come on // once per second for a half second. TMR2 = 0; // Clear timer 2 PR2 = 57600; // Timer 2 counter to 576000 T2CON = 0x8030; // Fosc/4, 1:256 prescale, start TMR2 IEC0bits.
24
Chapter 6.
26
Chapter 7. 2 The I C Device Routines 2 There are a large number of parts available using the Inter-Integrated Circuit, or I C, communications 2 protocol. I C allows multiple devices to share a two line bus. Although communication with the devices may occur at any speed up to 3.4 Mb/s, common rates are 100 kb/s, 400 kb/s, 1 Mb/s, 1.7 Mb/s and 3.4 Mb/s. The clock is controlled by the bus master. To allow multiple devices to share a single bus, each device has an address.
2 Chapter 7. The I C Device Routines Since the DAC is a relatively simple device, using the routine is quite straightforward. Although the MCP4726 includes a number of other features like RAM & EEPROM[MCP6], what the designer generally wants from a DAC is to output a specific voltage. The MCP4726write() function provides that capability. 2 In order to use any of the I C routines, the user must include i2c.h and the header file for the particular device, in this case, MCP4726.h. #include "../include/i2c.
Using the MCP23008 I/O Expander The MCP23008 I/O Expander is a more complex device[MCP5]. It has eight I/O pins, each of which may be configured as an input or an output. This makes it useful when a large number of I/O devices are 2 required and speed is not an issue (I C can only send thousands of commands a second, compared to millions of changes or tests per second possible directly to a port).
2 Chapter 7. The I C Device Routines 7.4. Using the MB85RC16V FRAM The MB85RC16V Ferroelectric Random Access Memory[FUJ1] is a 2Kx8 non-volatile memory chip. It is useful in cases where the microcontroller does not include enough EEPROM for the application. Many of the 16-bit families do not include any EEPROM, so this can be useful in cases where other families are selected. The part can be used in both 3.3 and 5 volt designs.
Chapter 8. 2 The I C Library In addition to the device routines, the library includes a complete set of low level I2C routines for devices 2 2 with seven bit I C addresses. Almost all I C devices may be supported with these routines. 2 Table 8.1.
2 Chapter 8. The I C Library 2 8.3. Sending data to an I C device Thus to send data to a device the sequence is: starting the transaction, sending the control byte, sending the data, and stopping the transaction. Once again, it is important to study the device datasheet. Many devices expect to receive multiple bytes of data in each transaction. As an example, consider the MCP4726 DAC[MCP6]. This is a 12 bit DAC.
Chapter 9.
34
Chapter 10. Analog Inputs // Initialize ADC /* set port configuration here */ ADPCFGbits.PCFG8 = 0; // ensure AN8/RB8 is analog /* set channel scanning here, auto sampling and convert, with default read-format mode */ ADCON1 = 0x00E4; /* No channel scan for CH0+, Use MUX A, SMPI = 1 per interrupt, Vref = AVdd/AVss */ ADCON2 = 0x0000; /* Set Samples and bit conversion time */ ADCON3 = 0x1f3f; //(as slow as possible) /* set channel scanning here for AN8 */ ADCSSLbits.
36
Chapter 11.
38
Chapter 12. Pulse Width Modulation // Set up timer 2 for PWM TMR2 = 0; // Clear timer 2 PR2 = 1000; // Timer 2 counter to 1000 T2CON = 0x8010; // Fosc/4, 1:4 prescale, start TMR2 // Set up PWM on OC2 (RD1) OC2RS = 1024; // PWM 2 duty cycle OC2R = 0; // OC2CON = 0x6; // Set OC2 to PWM mode, timer 2 // Loop through 360 degrees for ( theta=0.0; theta
40
Chapter 13.
42
Chapter 14.
44
Chapter 15.
46
Appendix A. Installing MPLAB-X Figure A.1. Locate the Development Tools Figure A.2.
Appendix A. Installing MPLAB-X Figure A.3. Open Downloaded Installer Figure A.4.
Figure A.5. Install Wizard Figure A.6.
50
Appendix B. Setting up a project in MPLAB-X Figure B.1. MPLAB-X Desktop Icon Figure B.2. New Project Button Figure B.3.
Appendix B. Setting up a project in MPLAB-X Figure B.4. Selecting the Processor Figure B.5. Select Programmer/Debugger Figure B.6. Selecting the Toolchain Figure B.7.
Figure B.8. Create a Source File Figure B.9.
54
Appendix C. The C Language C.1. Introduction This appendix will not turn you into an expert C programmer, nor is it even a decent tutorial. it will, however, give you a little bit to get started with. C is actually quite a simple language. There are only a handful of keywords and precious few rules. Indeed, this lack of rules does tend to be difficult for folks coming from older languages such as Basic or FORTRAN. 1 In this course, we won't be making use of a lot of elaborate code.
Appendix C. The C Language that long. Of course, this can have very unfortunate side effects. But C has great faith that you knew what you were doing when you wrote that. C.2. Identifiers Variables and functions in C are assigned names called identifiers. ANSI C sets some minimum requirements for identifiers, but also allows some implementation flexibility. As a general rule, XC16 makes maximum use of that flexibility. An identifier is a sequence of letters and/or digits which must begin with a letter.
Array and Pointer types Type unsigned long long Bits 64 Min Max 0 18446744073709551615 The following are the floating point types: Table C.2. Floating Point Types Type Bits Exponent Min Exponent Max float 32 -126 127 double 32 -126 127 long double 64 -1022 1023 A number containing no decimal and not beginning with a zero is assumed to be a decimal constant of the type int. In many contexts, however, the compiler may recognize that some other type was intended such as unsigned or long.
Appendix C. The C Language A pointer is specified by prefixing the name with an * in the declaration. Thus, int *n; specifies a pointer, n, which points to an integer. A pointer declaration does not allocate memory The declaration of a pointer only allocates the pointer. It does not allocate any space for the thing that might be pointed to. An array is declared by suffixing the name with the ordinality surrounded by square brackets ([]).
Structure and Union types C.3.3. Structure and Union types struct { int PointID; double Temperature; double ScalingFactor; double Offset; char Name[32]; } TemperaturePoint[10]; union { long a; struct { int b1; int b2; } b; } longintunion; C.4. Control Flow C.5. Functions and Program Structure C.6. The C preprocessor C.7.
60
Appendix D.
62
Appendix E. Microchip PIC Families Figure E.1.
64
Appendix F. Compiler Support Locations The following directories are all relative to the compiler install directory which is typically something like (some directory)/microchip/xc16/(version)/. The following tables show only locations relevant to the dsPIC30F family of processors. There are additional directories for other processors. Your installation may use \ instead of /. Table F.1.
66
Appendix G. Revision History Revision 0-3 Sun Jan 20 2013 Earl corrections John McDonough wb8rcr@arrl.net Revision 0-2 Wed Jan 9 2013 Add chapters on I2C John McDonough wb8rcr@arrl.net Revision 0-1 Initial prose John McDonough wb8rcr@arrl.net Fri Oct 26 2012 Revision 0-0 Tue Sep 4 2012 Initial creation of book by publican John McDonough wb8rcr@arrl.
68
Bibliography [Barr] Michael Barr. Copyright © 2012 Barr Group. Barr Group . Embedded Systems Glossary. E. [FUJ1] Sales Promotion Department, Fujitsu Semiconductor Limited. Copyright © 2011 FUJITSU 2 SEMICONDUCTOR LIMITED. Fujitsu Semiconductor . Memory FRAM. 16 K (2 K x 8) Bit I C MB85RC16V. DS501-00010-2v0-E. [KandR] Brian Kernighan and Dennis Ritchie. Copyright © 1988, 1978 Bell Telephone Laboratories, Inc. Prentice Hall P T R . 0-13-110370-9. The C Programming Language. [MCP1] Microchip.
70
Index F AckI2C, 31 ACKstatusI2C, 31 ANSI C, 56 Array, 55 float, 57 Floating point, 28 Formfeed character in character literals, 57 FORTRAN, 55 FRAM MB85RC16V, 30 B G Backspace character in character literals, 57 Basic, 55 Bell character in character literals, 57 Brownout protection configuration setting, 19 getI2C, 31, 32 GPIO MCP23008 register, 29, 29 A C C, 55 ANSI, 56 Carriage return character in character literals, 57 Case Sensitivity, 55, 56 char, 56 Code protection configuration setting, 19 C
Index MCP23008writeRegister, 29 MCP4726, 27, 32 MCP4726write, 28 MPLAB-X icon, 5 launching, 5 New project, 6 New project wizard, 6 Start page, 6 MPLAB-X project, 5 N New Project, 6 Newline character in character literals, 57 NotAckI2C, 31, 32 NULL character in character literals, 57 O Octal value in character literals, 57 OLAT MCP23008 register, 29, 29 Oscillator configuration setting, 19 P Power up timer configuration setting, 19 Processor in New Project wizard, 7 Project in MPLAB-X, 5 Project type in N