MPLAB IDE/C18 Tutorial for C Programming

MPLAB IDE/C18 Tutorial for C Programming
This document provides information for a quick start. The MPLAB IDE software contains extensive help manuals under Help menu.

1.

Create a New Folder for The Project

It is best to contain all the files related to a project in a folder. Use Windows Explorer to create a directory C:\blink for all your project files. Do not create the directory in a network drive (H:) or you may risk crashing the program or the computer.

2.

Starting MPLAB IDE

To launch MPLAB IDE click the MPLAB IDE icon on the desktop.

Figure 1:

MPLAB IDE icon

The Microchip splash screen will appear while MPLAB IDE is loading.

3.

Create a New Project

You need a project to build the program. Follow the steps below to create a new project. From MPLAB IDE, select Project>New... or click on the New Project button; the New Project dialog box will open.

Figure 2:

New project button

Enter a name for your new project (blink). The project name and the project directory name do not have to match but they will for this exercise. Use the Browse button to select the path to the directory you just created. Click OK.

4.

Select the Device

You must first tell MPLAB IDE the device that you are going to use. For this tutorial, we will use the PIC18F458. Select Configure>Select Device… Select PIC18F458 from the device pull-down list. Click OK.

Page 1 of 12

© S. Chen 2005

MPLAB IDE/C18 Tutorial for C Programming

5.

Set Language Toolsuite

Select Project>Set Language Toolsuite…to choose the programming language. Select “Microchip C18 Toolsuite” for this tutorial.

6.

Create Source Code

Select File>New to open a new file for edit. Enter the example code below.

Figure 3:

Sample code for the tutorial

Once you have completed entering the code, select File>Save and save the file in the project directory as: blink.c. The editor is context sensitive. As soon as the file extension is known, it shows different colors and emphasis for reserved words.

7.

Add the Source Code File to the Project

Now that you have created the source code file, it needs to be added to the project so that you may build the product. Select Project>Add Files to Project… Select the file you just created and saved (blink.c). Click Open. The newly inserted file should appear in the project window (the window with the title blink.mcw) under "Source Files". If not, either the file extension is incorrect or the project language suite selection does not match the file extension. Save the project files by selecting Project>Save Project.

Page 2 of 12

© S. Chen 2005

MPLAB IDE/C18 Tutorial for C Programming

8.

Select Linker Script

Linker takes the outputs of the compiler and links them with other essential parts to generate a memory image for the product. Linker script contains three pieces of information for linker: the name of the startup object file, the names of the library files, and the memory allocation. A special version of linker script written for use with bootloader program (to be covered in next lab session) is included as C:\mcc18\18f458b.lkr. Right click on Linker Scripts entry of the project window, select Add Files… and browse to the file mentioned above. After the linker script is added to the project, the project window should look like:

Figure 4:

Project Window showing blink.c in source file and 18f458b.lkr in linker script

8.1 C startup file
At reset vector, a piece of code initializes the registers and the initialized data (idata section in C18). It then goes into an infinite loop that calls main( ) repetitively. (Therefore, if you allow a return from main( ), it will go right back to main!) A special version of startup program modified to work with the bootloader program is precompiled and store as an object file with the name c018ib.o in the C:\mcc18\lib\ folder.

8.2 Library file
Simplicity was the mantra of C language. A large portion of the C functions is compiled into library files. An intelligent linker will link in only the portions of the functions that are referenced by the user program. C18 provides a C library file called clib.lib in the C:\mcc18\lib\ folder. It also has a library file with many PIC18 specific I/O functions called p18f458.lib in the same folder.

8.3 Memory allocation
This portion of the linker script tells linker whe re to put the linked program in memory. A special memory allocation scheme of 18f458b.lkr is used for the output to work with the bootloader program.

Page 3 of 12

© S. Chen 2005

MPLAB IDE/C18 Tutorial for C Programming

9.

Set paths

Before building the project, you need to specify several paths for the MPLAB IDE to follow to find the files. Click Project>Build Options…>Project to open the Build Options dialog box. Select General tab if it is not on the top already. Fill up the include path and library path as specified below (assuming C18 was installed at the default location C:\mcc18).

Figure 5:

Build Options paths

Click OK button to close the Build Options dialog box.

10. Make or Build the Project
Select Project>Make to make your project. Select Project>Build All to build your project. Alternatively or more conveniently, you may use the make or the build all buttons.

Page 4 of 12

© S. Chen 2005

MPLAB IDE/C18 Tutorial for C Programming

Figure 6:

The left button is Make and the right one is Build All

The difference between Make and Build All is that Make performs the minimum required steps and Build All deletes everything except the source files and rebuilds the whole project. Normally, Make is sufficient to update the product after you make changes to the source files. You should always use Build All if you make changes in the project windows or build options. If your file is compiled successfully, the messages will read like:

Figure 7:

Build output window of a successful complete build

If your file did not compile successfully, error messages will appear in the output window. Always scroll back to the beginning of the output window to be sure that you did not miss any messages.

Figure 8:

Build output window with a syntax error

Page 5 of 12

© S. Chen 2005

MPLAB IDE/C18 Tutorial for C Programming Double click on the error message in the Output window will bring you to the error in the source file. A green arrow in the gutter on the left of the source file window points to the line where the error was found (It may not be the location where error occurs). If the errors were found after compilation, it may not be able to link the error to a specific location in the source. Correct all the syntax errors and rebuild the project. Warnings are errors that were deemed not critical to produce a product. It is advised that you always read the warning messages and attempt to clean them up.

Figure 9:

Double click the error message will bring to the location of the error which is indicated by a green arrow in the left gutter

11. Compiler Output Files
Upon a successful build, the compiler and the IDE create a list of output files. The following are the ones that might interest you.

11.1 The .LST File
The listing file shows the source file that the compiler sees along with the assembly code produced by the compiler.

11.2 The Memory Image Files
The linker produces three different formats of memory image files: the .COD file, the .COF file, and the .HEX file. The .COD file contains symbol table and is used by MPLAB IDE to support debugging tools. The .HEX file conforms to Intel Hex format. It is usually used to “burn” the chip. Unfortunately, the format of the hex file generated by C18 is not acceptable by the bootloader that we will use for the rest of the semester. We will cover the procedure to regenerate a hex file that is acceptable by the bootloader later.

12. Simulate the Execution of Your Program 12.1 Set Up the Simulator
Now that your project is built, you will want to check whether it is functioning properly. To do this, you will need to select a debugging tool. For this tutorial, we will use the simulator, MPLAB SIM.

Page 6 of 12

© S. Chen 2005

MPLAB IDE/C18 Tutorial for C Programming Select the MPLAB SIM simulator as the debugger by Debugger>Select Tool>MPLAB SIM. The following changes should appear in MPLAB: 1. “MPLAB SIM" appears in the first field of the status bar at the bottom of the MPLAB IDE window. 2. Additional menu items now appear in the Debugger menu. 3. Additional toolbar buttons should appear.

Figure 10:

The simulation toolbar with the buttons starting from left: Run, Halt (gray), Animate, Step In, Step Over, Step Out, Reset

Rest the mouse cursor over a toolbar button to see the tool tip of the buttons’ function.

12.2 Trace Your Code
Click the Reset button will reset the processor and point the program counter to the reset vector. If you are programming in assembly language, there will be an arrow in the gutter of your source code window indicating the first source code line to be executed. But in a C program, the linker adds a startup code at the reset vector that is invisible in your source code window. Therefore, you won’t see the green arrow. Click Run button to run your application. You will see "Running…" appear in the status bar. To halt program execution, click on the Halt button. The green arrow will indicate the line of code where the program halted. (To be exact, the green arrow is pointing to the next line of code to be executed.) You may single step through the program by clicking on the Step Into button. This will execute the line pointed by the green arrow and move the arrow to the next line. Most likely, your program is stuck in the delay loop. To bail out of the delay loop, click on the Step Out button. Step Out brings the program out of a level of function call and return to the caller. If you keep clicking on Step Into button, you will get back to the delay loop again. To avoid that, use Step Over button. Step Over executes the subroutine without stepping into it. You may use the appropriate Debugger menu items or the hotkey shown next to the menu item instead of clicking on the buttons.

12.3 View Variables
You can see the values of variables when the simulation is halted by putting the mouse cursor over the name of the variable in the source file. A tool tip like display will show the current value of the variable (this is called mouse over).

Page 7 of 12

© S. Chen 2005

MPLAB IDE/C18 Tutorial for C Programming Rather than mouse over the name each time you want to see the value of a variable, you can open a watch window. The watch window will remain on the screen and show the current variable values when the program execution halts. Watch windows may be found under the View menu.

Figure 11:

The Watch window. The value of counter was changed and indicated in red

Add variables: i, counter and PORTB in the watch window. You may click in the blank area just under the last “Symbol Name” and type in the name of the variable, or you may use the pull-down menu selection on the top of the window to choose the variable then click “Add” button. Both i and counter are variables in C program and you will find them to the right of Add Symbol button. PORTB is a special function register; you have to find it next to Add SFR button. After the variable is added, the display format may be modified by right click on the line and select “Properties…”. Here, you may change the displayed format to decimal from hexadecimal. The values in the watch window do not get updated when the program is running. Only when the program execution halts will they get refreshed. The values are displayed in red when its content changed. Since i is an autovariable in function delay, you need to step into delay before the value becomes valid. Otherwise, “Out of Scope” is shown as its value.

12.4 Breakpoint
By double clicking on a line of code, a stop sign with a ‘B’ appears in the gutter to indicate the breakpoint. If you run the program, the execution halts when encountering a breakpoint. The green arrow will rest on the stop sign. (When the execution halts, the line with the stop sign is NOT executed yet.)

Figure 12:

The source file window during simulation. The stop sign with ‘B’ in the gutter indicates a breakpoint; the green arrow indicates the next statement to be executed.

Page 8 of 12

© S. Chen 2005

MPLAB IDE/C18 Tutorial for C Programming

13. “Burn” a Device
In the bygone era, the one time programmable (OTP) devices were actually consisted of minute fuses and programming a device incurred applying a high voltage to burn off the fuses. Nothing gets burned in the modern erasable programmable devices during programming. But the term “burn” is still used to avoid the confusion created by the polymorphism of the word “program”. Simulation is a good way to debug a program. Once you have done all the simulations you want to do, you will then program an actual device to test it. 1. Power up the PICSTART Plus Development Programmer 2. Connect the DB9 cable from the Programmer to the COM1 port of the PC 3. Select Programmer>Select Programmer, and click on PICSTART Plus. If the connection is established, the output window will be silent. The Programmer menu items and toolbar items will be added but in gray. 4. Establish communications with the programmer by selecting Programmer>Enable Programmer. If the connection is established, the Programmer menu items and toolbar items will change to active colors.

Figure 13:

The Programmer toolbar with buttons starting from the left: Blank Check, Read, Program, Verify, Erase

The output window may contain the following messages but you may ignore them.

Figure 14:

The PICSTART output window. The PICSTART Plus Units in the lab can not be upgraded and will always show these messages.

5. If proper connection between programmer and PC cannot be established, the output window will have the message “Cannot Transmit. Please verify connection and retry the previous operation.” Check the cable connection and retry enabling the PICSTART.

Page 9 of 12

© S. Chen 2005

MPLAB IDE/C18 Tutorial for C Programming 6. Insert the device to be programmed in the ZIF socket and lock the device. Make sure the device is in the socket with proper orientation. Reversing the device orientation is known to be a sure way to destroy it. 7. Rebuild the project after the connection between the programmer and PC is properly established. 8. Click Erase button to erase the device 9. Click Program button to program the information currently loaded in the MPLAB IDE into the device. The operation progress is indicated at the left corner of the status bar. Results will be displayed in the Output window. 10. While programming and verification are going on, the orange ACTIVE LED of PICSTART will stay on. Do not remove the device when the orange LED is on. 11. When programming is complete, the orange ACTIVE LED goes off and you may remove the device from the programmer and insert it in the circuit for testing. 12. Always check the output window for possible errors in programming before proceed with your testing.

14. Modify Program Source Code – Avoid the Traps!!!
One of the common problem often causes numerous hours of time wasted is to modify a source file that is not in the project. For example, you use a copy of the project directory in your H: drive or in your USB pen drive. The project was copied to C: drive and the built off files in C: drive while you opened and edited the files in H: drive. You pounded your head for hours wondering why changes did not make a difference. To avoid this trap, close all the source file windows in MPLAB IDE but leave the project window (the one with .mcw) open. Double click the file name in the project window to open and edit the file.

15. Burn a Device at a Different PC
In the lab, we will not have enough Device Programmers for each PC. Rather than moving the programmer around, it will be easier to connect the programmer to a fixed PC and bring the program image file and the device over for programming. At your lab station: 1. Build your project without errors 2. Insert the USB pen drive or a floppy disk in the drive 3. Copy the .HEX file to the pen drive or the floppy disk At the programmer station: 1. Make sure the proper device type is selected. The current device selection is displayed at the bottom status bar of the MPLAB window. 2. Select Debugger>Clear Memory>All Memory 3. Insert pen drive in USB connector or floppy disk in the drive 4. Select File>Import… to open the Open dialog box 5. Browse to the folder with the hex file

Page 10 of 12

© S. Chen 2005

MPLAB IDE/C18 Tutorial for C Programming 6. Change file type to .HEX 7. Select the file you are going to use to program the device 8. Click Open button 9. You may use View>Program Memory to verify the file content 10. Proceed to program the device To avoid the second trap, use Build All instead of Make after you change the content of the project window or the Build Options.

16. Create Hex File for Bootloader
Microchip C18 creates fragmented hex file, which conforms to the Intel Hex format but is not readable by the bootloader program (which came from Microchip Application Note AN851). One of these days, I will modify the bootloader program to read C18 output. But until then, you have to take an extra step to create a bootloader friendly hex file.

16.1 Find the Memory Range Required
MPLAB IDE allows you to dump the selected program memory into a hex file using Export menu. There are two ways (at least) to find out the range of program memory needed for your program. One is to change the Build Options to generate map file by the linker. An easier way is to use auto-range of PICSTART programmer available in MPLAB IDE version 7 or later.

Figure 15:

The PICSTART Plus auto select of memory range in MPLAB IDE can be used to determine the program memory usage

Page 11 of 12

© S. Chen 2005

MPLAB IDE/C18 Tutorial for C Programming Follow the procedure before to select PICSTART Plus as the programmer. (You do not need to enable the programmer.) Select Programmer>Settings… in the menu to get the following dialog box. When “Auto select memory areas and range” is selected, the program memory range is indicated in gray below. Write down the start address and end address. The program memory range changes as you change the program source. It would be a good idea to use a much higher end address in case you forgot to look for the new value. The start address shall always be 200.

16.2 Export to a Hex File
Select File>Export… menu to open the Export dialog box. Fill in the start and end address then uncheck all other selections. Click OK button and browse to the project directory. You may choose the same file name as the one created by C18 and overwrite it since you have no use of the original one.

Figure 16:

The Export dialog box where the memory range is specified

17. Keep This Tutorial for Future Reference

Page 12 of 12

© S. Chen 2005

Sign up to vote on this title
UsefulNot useful