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 1 : - Introduction and Overview

MPLAB C Compiler for PIC18 MCUs
MPLAB C Compiler is a cross-compiler that runs on a PC and produces code that can be executed by the Microchip PIC18XXXX family of microcontrollers. Like an assembler, the compiler translates human-understandable statements into ones and zeros for the microcontroller to execute. Unlike an assembler, the compiler does not do a one-to-one translation of machine mnemonics into machine code.

This MPLAB C compiler takes standard C statements, such as “if(x==y)” and “temp=0x27” and converts them into PIC18XXXX machine code. The compiler incorporates a good deal of intelligence in this process. It can optimize code using routines that were employed on one C function to be used by other C functions. The compiler can re-arrange code, eliminate code that will never be executed, share common code fragments among multiple functions, and can identify data and registers that are used inefficiently, optimizing their access.

Code is written using standard ANSI C notation. Source text is compiled into blocks of program code and data which are then “linked” with other blocks of code and data, then placed into the various memory regions of the PIC18XXXX microcontroller. This process is called a “build,” and it is often executed many times in program development as code is written, tested and debugged. This process can be made more intelligent by using a “make” facility, which invokes the compiler only for those C source files that have changed since the last build, resulting in a faster build times.

This MPLAB C compiler and its associated tools, such as the linker and assembler, can be invoked from the command line to build a .HEX file that can be programmed into a PIC18XXXX device. MPLAB C and its other tools can also be invoked from within MPLAB IDE. The MPLAB graphical user interface serves as a single environment to write, compile and debug code for embedded applications.
MPLAB dialogs and project manager handle most of the details of the compiler, assembler and linker, allowing the task of writing and debugging the application to remain the main focus.

MPASM Cross Assembler
Often both a cross-assembler and a cross-compiler are used to write code for a project. MPASM is a component of the MPLAB IDE and it works in conjunction with MPLINK to link assembly language code sections with C code from the MPLAB C compiler.
Assembly language routines are practical for small sections of code that need to run very fast, or in a strictly defined time.
While the execution time of code created by a compiler can become nearly as fast as code created using assembly language, it is constrained by the fact that it is a translation process, ending in machine code that could have been generated from assembly language, so it can never run faster than assembly language code.

Execution Flow
An example of the flow of execution of the language tools is illustrated here:

Language Tools execution flow
In the above example two C files are compiled by MPLAB C, file1.c and file2.c, and an assembly file file1.asm is assembled by MPASM. These result in object files, named file1.o, file2.o and file3.o.
A precompiled object file, file4.0 is used with file3.o to form a library called lib1.lib. Finally the remaining object files are combined with the library file by the linker..
MPLINK also has as an input the linker script, script.lkr. MPLINK produces the output files, output.cof and output.map and the HEX file, output.hex.

PIC18XXXX Programmer’s Model
The PIC18XXXX MCUs are “Harvard architecture” microprocessors, meaning that program memory and data memory are in separate spaces. The return stack has its own dedicated memory and there is another non-volatile memory space if the particular device has on-board Data EEPROM memory.

Program Memory
The program memory space is addressed by a 21-bit program counter, allowing a 2 Mb program memory space (Figure 5-1). Typically, PIC18XXXX MCUs have on-chip program memory in the range of 16K to 128K. Some devices allow external memory expansion.
At reset, the program counter is set to zero and the first instruction is fetched. Interrupt vectors are at locations 0x000008 and 0x000018, so a GOTO instruction is usually placed at address zero to jump over the interrupt vectors.
Program memory contains 16-bit words. Most instructions are 16-bits, but some are double word 32-bit instructions. Instructions cannot be executed on odd numbered bytes.
PIC18F devices have flash program memory and PIC18C devices have OTP (one-time-programmable) memory (or in some cases, UV erasable windowed devices). Usually the OTP memory is written only when the firmware is programmed into the device. Flash memory can be erased and re-written by the running program. Both OTP and Flash devices are programmed by a few interconnections to the device, allowing them to be programmed after they are soldered on to the target PC board.

These are some important characteristics of the PIC18 architecture and MPLAB C:

MPLAB C Implementation

    Instructions are typically stored in program memory with the section attribute code.

    Data can be stored in program memory with the section attribute romdata in conjunction with the rom keyword.

    MPLAB C can be configured to generate code for two memory models, small and large. When using the small memory model, pointers to program memory use 16 bits. The large model uses 24-bit pointers.

PIC18 Architecture

    The GOTO instruction and the CALL instruction are double-word (32-bit) instructions and can jump anywhere in program memory.

    If the second word of a double word instruction is executed (by branching or jumping into the middle of the instruction with a GOTO instruction), it will always execute as a NOP.

    All instructions are aligned on even word boundaries.

    In some PIC18XXXX devices, program memory or portions of program memory can be code protected. Code will execute properly but it cannot be read out or copied.

    Program memory can be read using Table Read instructions, and can be written through a special code sequence using the Table Write instruction.

Data Memory

Data memory is called “file register” memory in the PIC18XXXX family. It consists of up to 4096 bytes of 8-bit RAM. Upon power up, the values in data memory are random. Data is organized in banks of 256 bytes. The PIC18 instructions read and write file registers using only 8-bits for the register address, requiring that a bank (the upper 4-bits of the register address) be selected with the Bank Select Register (BSR). 12-bit pointers allow indirect access to the full RAM space without banking. In addition special areas in Bank 0 and in Bank 15 can be accessed directly without concern for banking and the contents of the BSR register. These special data areas are called Access RAM. The high Access RAM area is where the Special Function Registers are located.

Uninitialized data memory variables, arrays, and structures are usually stored in memory with the section attribute “udata.”
Initialized data can be defined in MPLAB C, so that variables will have correct values when the compiler initialization executes. This means that the values are stored in program memory, then moved to data memory on startup. Depending upon how much initialized memory is required for the application, the use of initialized data (rather than simply setting the data values at run time) may adversely affect the efficient use of program memory.
Since file registers are 8-bits, when using variables, consideration should be made whether to define them as “int” or “char”. When a variable value is not expected to exceed 255, defining it as an “unsigned char” may result in smaller, faster code I some applications.

Special Function Registers

Special function registers (SFRs) are CPU core registers (such as the stack pointer, status register and program counter) and include the registers for the peripheral modules on the microprocessor. Most SFRs are located in Bank 15 and can be accessed directly without the use of the BSR unless the device has more peripheral registers than can fit in the 128 byte area of Bank 15. In that case, the BSR must be used to read and write those special function registers. Special function registers (SFRs) are CPU core registers (such as the stack pointer, status register and program counter) and include the registers for the peripheral modules on the microprocessor. Most SFRs are located in Bank 15 and can be accessed directly without the use of the BSR unless the device has more peripheral registers than can fit in the 128 byte area of Bank 15. In that case, the BSR must be used to read and write those special function registers

Return Stack
CALL and RETURN instructions push and pop the program counter on the return stack. The return stack is a separate area of memory, allowing 31 levels of subroutines.

DATA EEPROM Memory (EEDATA)
Data EEPROM is non-volatile memory in its own memory space. It can be used to store data while the chip is powered down, and it can store protected data. It is accessed through four special function registers and requires special write sequences. In many PIC18XXXX devices this area can also be protected so that data cannot be read out or copied.

Configuration Memory
Configuration bits control the various modes of the PIC18XXXX devices, including oscillator type, watch dog timers, code protection, and other features. This memory is above the 21-bit address range of program memory, but can be accessed using table read and write instructions. Most configuration bits are set to the desired state when the device is programmed (using MPLAB PM3, PICSTART Plus, MPLAB REAL ICE, MPLAB ICD 2 or other programming hardware). The MPLAB C
“#pragma config” directive is used to set these bits for initial programming, and usually applications do not need to access this area of memory.

Extended Mode
Some PIC18XXXX devices have an alternate operating mode designed for improved re-entrant code efficiency. When these devices are programmed to use the Extended Mode, Access RAM addressing is affected, some instructions act differently, and new instructions and addressing modes are available. Additionally, special linker scripts with a name ending in “_e” are required.
See the relevant PIC18XXXX data sheet for information in this mode, especially if assembly language code is used in the application. Note that the information about Access RAM in the Data Memory section above is not valid when using the Extended Mode.

SFRs, Timers SW/HW
The PIC18XXXX Special Function Registers (SFRs) are special registers in the file register area of the microcontroller. These include the core registers such as the stack pointer, status register, and program counter of the microprocessor core, as well as the registers to control the various peripherals. The peripherals include such things as input and output pins, timers, USARTs and registers to read and write the EEDATA areas of the device. MPLAB C can access these registers by name, and they can be read and written like a variable defined in the application. Use caution, though, because some of the Special Function Registers have characteristics different from variables. Some have only certain bits available, some are read only, and some may affect other registers or device operation when accessed.

I/O Registers
Input and output on the PIC18XXXX pins is accomplished by reading and writing the registers associated with the port pins on the device. Check the data sheet for available ports on the device. There are three special function registers associated with each port, one called a TRIS register defines the direction of the port pin: input or output. A second register called the PORT register is used to read and write values to the port pin, and a third, named LAT, is a latch, which allows reading and writing the values on the port without actually reading the current state of the pins on the port. This is important in the PIC18XXXX architecture because of read/modify/write considerations. The contents of I/O port registers should not be treated like variable storage --they operate quite differently. See the data sheets for more information.
Some pins are multiplexed and may need to be configured by other special function registers before they can be used as digital I/O. Specifically, PORTA on many PIC18XXXX devices also can be used as analog inputs to the A/D converter.
To configure and use PORTB as 4 input pins and 4 output pins, the following code could be written in MPLAB C compiler:

 

TRISB = 0xF0
PORTB = 0x0C /* set pins 0 and 1 low, pins 2 and 3 high */

Hardware Timers
PIC18XXXX timers are also configured and accessed through special function registers. Most PIC18XXXX devices have at least three timers For instance, Timer 0 in the 18F452 is configured through the T0CON register, and its counter/timer values can be read from and written to using the two eight-bit registers TMR0L and TMR0H. The INTCON register has bits which can be used to set Timer 0 as an interrupt, and controls whether the timer counts from the oscillator or from an external signal, thereby acting as a counter.

Software Timers
As in any C program, delays and timing loops can be created in software. Consideration of the design will affect how software and hardware timers are employed. A typical software delay loop involves setting up a counter and decrementing until it reaches zero. The disadvantages of a software timer is that if interrupts are occurring, the delays of a software timer will be extended, and possibly become unpredictable. Additionally, the program can do nothing except respond to interrupts while processing a software delay loop.

Interrupts
Interrupts are a feature of the PIC18XXXX core. Timers, I/O pins USARTs, A/Ds, and other peripherals can cause interrupts. When an interrupt occurs, the code in the application is suspended, and code in the interrupt routine executes. When the interrupt service routine finishes, it executes a “return from interrupt” instruction, and the program continues from where it left off.
There are two kinds of interrupts in the PIC18XXXX, low priority and high priority. Which kind of interrupt to use is one of the decisions that go into the design of the application. MPLAB C can be used for both types of interrupts, but the designer must be aware of the details of the particular interrupt operation in order to retain the contents of some of the critical internal registers. Careful consideration of variable usage and libraries (especially if used in the interrupt routine) is essential.
When an interrupt occurs, a low priority interrupt saves only the PC (program counter register). For high priority interrupts, the PIC18XXXX core automatically saves the PC, WREG, BSR and STATUS registers. See the
MPLAB C Compiler for PIC18 MCUs User’s Guide section on “ISR Context Saving” for information on saving application variables during interrupts.

Math and I/O Libraries
This MPLAB C compiler has libraries for control of peripherals, for software implementation of peripherals, and for general data handling and for mathematical functions. See
MPLAB C Compiler for PIC18 Libraries (DS51297) for a full description of these libraries.
The source code is provided for these libraries so they can be customized and rebuilt with modifications required by the application.
The use of the peripheral libraries usually requires an understanding of the operation of the peripherals as described in the device data sheets. But using C libraries results in reduced complexity when initializing and using the peripherals.
The MPLAB C math libraries include floating point operations, trigonometric operations and other operations. When using floating point and complex mathematical functions on 8-bit embedded controllers, care should be taken to evaluate whether the operations are an efficient choice for the particular design. Often a table, a table with an interpolation or an approximation using other methods will provide enough accuracy for the task. A 32-bit floating point operation will typically take many hundreds of cycles to execute and may consume significant portions of valuable program memory space.

Start Now With MPLAB ICD

Start Now with MPLAB C : Part 2 - Examples