Getting Started with Development Tools
Development Tools Home
Getting Started Development Tools Home
Step 1 An Overview of Embedded Systems
Step 2 Start Now with Microchip Development Tools
Step 3 Implementing an Embedded System Design with MPLAB® IDE
Step 4 The Development Cycle
Step 5 MPLAB® Project Manager
Step 6 Language Tools
Step 7 Target Debugging
Step 8 Programming
Step 9 MPLAB® IDE: For More Information
Getting Started with MPLAB Editor
Getting Started with MPASM/MPLINK
Getting Started with MPLAB SIM
Getting Started with MPLAB ICD
Getting Started with MPLAB C18 1
Getting Started with MPLAB C18 2
Getting Started with MPLAB C18 3
Introduction to Microchip’s Development Tools
Introduction to MPLAB® IDE
Tips and Tricks Using MPLAB® IDE v6.61
Introduction to MPLAB® SIM Software Simulator
Basic dsPIC Development Tools
Introduction to the Signal Analysis PICtail daughterboard
Choosing a Debug Tool
MPLAB® IDE User's Guide
MPLAB® IDE Quick Chart
MPLAB® Download Page
Online Discussion Groups
Development Tools Selector Guide
Available Books
Third Party Tools
  Featured Products
 

Pick your MCU
 
 
     

Start Now with MPLAB C Compiler for PIC18 MCUs Part 2: Examples

Example 1 : Hello, world!
The typical “Hello, world!” function contains this C statement to print out a message:

printf ("Hello, world!\n")

For this to compile using MPLAB C, the code is

The first line includes the header file, stdio.h, which has prototypes for the printf() function. The #pragma statement controls the watchdog timer of the target microcontroller, disabling it so it won’t interfere with these programs.
Note: Often, the final “
while (1)” statement is not used for the “Hello, world!” program because the example compiles on a PC, executes, then returns back to the operating system and to other tasks. In the case of an embedded controller, however, the target microcontroller continues running and must do something, so in this example, an infinite loop keeps the microcontroller busy after doing its single task of printing out “Hello, world!”
For these examples, MPLAB editor screen shots will be used. The full source for each of these examples is included at the end of this section. The text can be cut and pasted into an MPLAB editor window.

Create a new project named gs1 in a new folder named first project. Create a new file, type or copy and paste the above code into it, and save it as a file named main.c. Then add the file main.c as the source file in this folder and add the 18F452.lkr linker script from the mcc18\lkr folder..

The final project should look like this:

Set the current device to PIC18F452 with Configure>Select Device

Make sure that the simulator is selected with Debugger>Select Tool>MPLAB SIM.
Use Project>Build All or the equivalent icon to build the project.
After a successful build, the Run icon becomes blue, indicating that the program is halted and ready to run. Select the Run icon and it turns gray. The Halt icon turns blue, indicating the program is running and can be halted. In addition, on the status bar at the bottom is a “Running...” indicator. Select the Halt icon and open the Output Window if it is not already open.

The text “Hello, world!” should appear in the SIM Uart1 tab of the Output Window.

Select the Reset icon to reset the program, and then select the Run icon again to print the message a second time in the Output Window.

Resolve Problems

If this did not work, see if you have an error as listed in the 7 items below:

1. If a mistype caused an error when building the project, the last lines in the Output Window may show:
Output Window Syntax Error

Double click on the line with “syntax error” to bring up the MPLAB editor window with the cursor on the line with the syntax error.

2. An error that reads “could not find stdio.h” usually means that the include path is not set up. Refer to the MPLAB IDE’s Project>Build Options Dialog to set the include path.

3. A warning that reads “type qualifier mismatch in assignment” may mean that the large memory model is not selected when using standard I/O (libraries are built with the large memory model).

4. An error that “c018i.o is not found” could mean that the library path is not set up correctly. Check MPLAB IDE’s Project>Build Options Dialog.

5. If a message says it can not find a definition of “main” in c018i.o, make sure “main” is spelled all lower case, since C is case sensitive.

6. An error that reads “could not find definition of symbol...” is usually caused by using the wrong linker script:
Make sure that the 18F452.lkr file in the MCC18\LKR directory is used. MPLAB IDE also has a linker script for assembler-only projects in one of its subdirectories. Always use the MCC18\LKR linker scripts for all projects using the MPLAB C compiler.

7. If “Hello, world!” does not appear in the Output Window, try these steps:

Make sure that the simulator is selected (Debugger>Select Tool>MPLAB SIM).

Make sure the UART1 is enabled to send printf() text to the MPLAB IDE Output Window.

Select the Halt icon.

Build All again. There should be no errors in the Output Window, and the message “Build Succeeded” should appear as the last line.

Select the Reset icon on the Debug Toolbar.

Select the Run icon on the Debug Toolbar.

(To clear the Output Window, right click the mouse button and select the Clear Page option.)

Example 2 : Lighting an LED
The first example demonstrated the basics of creating, building and testing a project using MPLAB C with the MPLAB IDE. It did not go into the details of what the target processor would do with that code. In this next program, code will be generated to simulate turning on a Light Emitting Diode (LED) connected to a pin of the PIC18F452.

Create a New Project
Create a new project named “GS2” in a new folder named “Second Project.”
Make sure the language tools are set up and the Build Options properly configured.

Write the Source Code
Create a new file and, type in the code (or copy it from the listing at the bottom of this document) Save it with the name
main.c in the “Second Project” folder:

The first line in this code includes the generic processor header file for all PIC18XXX devices, named p18cxxx.h. There is also one for the PIC18F452 named p18f542.h which could have been used instead. This file contains the definitions for the special function registers in these devices. This example will use four pins on the eight bit I/O port with the register name PORTB.
#pragma config WDT = OFF” is the same as in the first program.
TRISB = 0” sets the PIC18F452 register named TRISB to a value of zero. The TRIS registers control the direction of the I/O pins on the ports. Port pins can be either inputs or outputs. Setting them all to zero will make all eight pins function as outputs
PORTB = 0” sets all eight pins of the PORTB register to zero, or to a low voltage.
PORTB = 0x5A” sets four pins on PORTB to one, or to a high voltage (5Ah = 01011010b).

When this program is executed on a PIC18F452, an LED properly connected to one of the pins that went high will turn on.

Add main.c as a source file to the project. Select the 18F452.LKR file as the linker script for the project. The project window should look like this:

Build the project with Project>Build All.

Like in the first program, the simulator in MPLAB IDE will be used to test this code. Make sure that the simulator is enabled. The project may need to be built again if the simulator was not already selected.
To test the code the state of the pins on PORTB must be monitored. In MPLAB IDE there are a two ways to do this.

Test with Mouse Over Variable

After the project is successfully built, use the mouse to place the text editor cursor over a variable name in the editor window to show the current value of that variable. Before this program is run, a mouse over PORTB should show its value of zero:

Click the Run icon (or select Debug>Run) and then click the Halt icon, and do the mouse over again. The value should now be 0x5A:

Test with Watch Window

The second way to check the value of a variable is to put it into a Watch window. Select View>Watch to bring up a new Watch window

Now drag this Watch window away from the source file window so that it is not on top of any part of it. Highlight the word PORTB in main.c. When the word is highlighted, drag it to the empty area of the Watch Window. The Watch Window now looks like this:

Select the Run icon, then the Halt icon, and the Watch window should now show a value of 0x5A in PORTB

Double click on the 0x5A value of PORTB in the Watch window to highlight it and type any other 8-bit value. Then select Reset, Run and then Halt to see the value return to 0x5A.

Example 3 : Basic Data Types

Variables in MPLAB C can be added to watch windows. MPLAB IDE can correctly show the values with the formatting appropriate for each data type.

This demonstration can be done using a new project. Select Project>New Project and set the project name to “Data Types,” and set the project directory to the same directory used in the previous demonstration

This sample code uses the basic data types of MPLAB C. Use File>New to make the file, save it with the name “basic_type.c” and add it along with the 18F452.lnk linker script to the project (type it in or copy the text from the listings at the end of this document and paste into an MPLAB editor window).

Change to the PIC18F452 device with Configure>Select Device.

Select View>Watch to display the watch window, and add the variables from the source code by highlighting them and dragging them to the watch window .

Build the project, select Run, then Halt. The variables will show the values as set in basic_types.c. Those that changed will be highlighted in red as shown:

Example 4 : Arrays

Arrays are displayed in MPLAB watch windows as collapsible items, allowing them to be expanded to be examined, then collapsed to make more room when watching other variables. To demonstrate, use the following code to make a new source file named arrays.c and a new project, also named “Arrays.”

Put the file named array.c into a project with the 18F452.lkr linker script

Select View>Watch to open up a watch window, and drag the arrays named “x” and “i” into the watch window (Figure  Default ¶ Font).

Make sure the simulator is selected as the debugger, Build the project and Run it. After clicking Halt, the arrays can be examined. The “+” sign next to each array was expanded. Note the values in the arrays after the program was executed

Example 5 : Structures

Like arrays, structures in MPLAB C show up on watch windows as expandable/ collapsible elements.
Demonstration code will be used to show how structures appear in MPLAB watch windows.

Make a project with this source file, add the 18F452.lkr linker script, set up the simulator as debugger and build it.
Before running, the watch window should look like this when every element is fully expanded:

After clicking Run, then Halt, the watch window should show the values stored into the structure:

Example 6 : Pointers

Pointers in MPLAB C can be used to point to data in ROM or RAM. This demonstration uses three pointers, showing how they are used in the PIC18 architecture.

The source code is adjacent: Enter this in a a new file in MPLAB IDE and save it as “pointers.c” in the “More Projects” folder.

Create a new project called “Pointers,” add the pointers.c file to the project as the source file and add the 18F452.lkr linker script. The project should look like this:

Select Project>Build All to build the project. Do not Run the project yet.
Select View>Watch to display an empty watch window, then highlight the names of the three pointers and the two arrays in the source code window and drag them to the watch window as shown:

Source code for the examples above

Example 1 : “Hello, world!”

Example 2 : Light LED

#include <stdio.h>

#pragma config WDT = OFF

void main (void)
{
printf ("Hello, world!\n");

while (1)
;
}

#include <p18cxxx.h>

#pragma config WDT = OFF

void main (void)
{
TRISB = 0;

/* Reset the LEDs */
PORTB = 0;

/* Light the LEDs */
PORTB = 0x5A;

while (1)
;
}

Example 3 : Basic Data Types

Example 4 : Arrays

char gC;
unsigned char guC;
signed char gsC;

int gI;
unsigned int guI;

short int gSI;
unsigned short int guSI;

short long int gSLI;
unsigned short long int guSLI;

long int gLI;
unsigned long int guLI;

float gF;
unsigned float guF;

void main (void)
{
gC = 'a';
guC = 'b';
gsC = 'c';

gI = 10;
guI = 0xA;

gSI = 0b1010;
guSI = 10u;

gLI = 0x1234;
guLI = 0xFA5A;

gF = -1.395;
guF = 3.14;

while (1)
;
}

char x[] = "abc";
int i[] = { 1, 2, 3, 4, 5};

void main (void)
{
while (1);
;
}

Example 5 : Structures

struct {
int x;
char y[4];
} s1 = { 0x5A, "abc" };

struct {
int x[5];
int y;
} s2 = { { 10, 22, 30, 40, 50 }, 0xA5 };

void main (void)
{
while (1)
;
}

Example 6 : Pointers

ram char * ram_ptr;
near rom char * near_rom_ptr;
far rom char * far_rom_ptr;

char ram_array[] = "this is RAM";
rom char rom_array[] = "this is ROM";

void main (void)
{
ram_ptr = &ram_array[0];
near_rom_ptr = &rom_array[0];
far_rom_ptr = (far rom char *)&rom_array[0];

while (1)
;
}

Start Now with MPLAB C for PIC18 MCUs : Part 1 - Introduction

Start Now with MPLAB C for PIC18 MCUs : Part 3 - References