Programming 16-Bit PIC Microcontrollers in C: Learning to Fly the PIC 24

Programming 16-Bit PIC Microcontrollers in C: Learning to Fly the PIC 24

by Lucio Di Jasio

View All Available Formats & Editions

New in the second edition:

• MPLAB X support and MPLAB C for the PIC24F v3 and later libraries

• I2C™ interface

• 100% assembly free solutions

• Improved video, PAL/NTSC

• Improved audio, RIFF files decoding

• PIC24F GA1, GA2, GB1 and GB2 support

Most readers will associate Microchip's name with the

See more details below


New in the second edition:

• MPLAB X support and MPLAB C for the PIC24F v3 and later libraries

• I2C™ interface

• 100% assembly free solutions

• Improved video, PAL/NTSC

• Improved audio, RIFF files decoding

• PIC24F GA1, GA2, GB1 and GB2 support

Most readers will associate Microchip's name with the ubiquitous 8-bit PIC microcontrollers but it is the new 16-bit PIC24F family that is truly stealing the scene. Orders of magnitude increases of performance, memory size and the rich peripheral set make programming these devices in C a must. This new guide by Microchip insider Lucio Di Jasio teaches readers everything they need to know about the architecture of these new chips: How to program them, how to test them, and how to debug them. Di Jasio’s common-sense, practical, hands-on approach starts out with basic functions and guides the reader step-by-step through even the most sophisticated programming scenarios. Experienced PIC users, including embedded engineers, programmers, designers, and SW and HW engineers, and new comers alike will benefit from the text’s many thorough examples, which demonstrate how to nimbly sidestep common obstacles and take full advantage of the many new features.

Read More

Editorial Reviews

From the Publisher
"No stone is left unturned...Unless you are a C30 and PIC24 wiz already, pick up this book before beginning work with one." William Wong, Electronic Design.

Product Details

Elsevier Science
Publication date:
Embedded Technology
Sold by:
Barnes & Noble
File size:
7 MB

Read an Excerpt

Programming 16-Bit PIC Microcontrollers in C

Learning to Fly the PIC 24
By Lucio Di Jasio


Copyright © 2012 Elsevier Inc.
All right reserved.

ISBN: 978-1-85617-871-6

Chapter One

The First Flight

The first flight for every student pilot is typically a blur – a sequence of brief but very intense sensations, including:

• The rush of the first take off, which is performed by the instructor.

• The white-knuckled, sweaty grip on the yoke while trying to keep the plane flying straight for a couple of minutes, after the instructor gives the standard "anybody that can drive a car can do this" speech.

• Acute motion sickness, as the instructor returns for the landing and performs a sickness-inducing maneuver, called the "side slip", where it looks like the runway is coming through the side window.

For those who are new to the world of embedded programming, this first chapter will be no different.

Flight Plan

Every flight should have a purpose, and preparing a flight plan is the best way to start.

This is going to be our first project with the PIC24 16-bit microcontroller and, for some of you, the first project with the MPLAB® X IDE Integrated Development Environment and the MPLAB C language suite. Even if you have never heard before of the C language, you might have heard of the famous "Hello World!" programming example. If not, let me tell you about it.

Since the very first book on the C language, written by Kernighan and Ritchie several decades ago, every decent C-language book has featured an example program containing a single statement to display the words "Hello World" on the computer screen. Hundreds, if not thousands, of books have respected this tradition, and I don't want this book to be the exception. However, it will have to be just a little different. Let's be realistic, we are talking about programming microcontrollers because we want to design embedded-control applications. While the availability of a monitor screen is a perfectly safe assumption for any personal computer or workstation, this is definitely not the case in the embedded-control world. For our first embedded application we better stick to a more basic type of output – a digital I/O pin. In a later and more advanced chapter we will be able to interface to an LCD display and/or a terminal connected to a serial port. But, by then we will have better things to do than writing "Hello World!"

Preflight Checklist

Each flight is preceded by a preflight inspection – simply a walk around the airplane where we check that, among many other things, gas is in the tank and the wings are still attached to the fuselage. So, let's verify we have all the necessary pieces of equipment ready and installed/connected:

• MPLAB X IDE, free Integrated Development Environment (obtain the latest version available for download from Microchip's website at

• MPLAB C30 Lite Compiler v3.30 (or later) or MPLAB XC16 Lite Compiler

• A PIC24FJ128GA010 on a PIM (also known as a mezzanine board)

• An MPLAB X compatible programmer/debugger such as the PICkit3, ICD3 or Real ICE

• The Explorer16 board, or any demo board with a row of eight LEDs connected to PortA.

Let's follow the New Project Setup checklist to create a new project.

From the Start Page of MPLAB X, select Create New Project, or simply select File>New Project ... from the main menu to activate the new project wizard, which will guide us automatically through the following six steps:

1. Choose Project: in the Categories panel, select the Microchip Embedded option. In the Projects panel, select Stand Alone Project and click Next.

2. Select Device: in the Family drop box, select PIC24. In the Device drop box, select PIC24FJ128GA010, or other PIC24 model of your choice and click Next.

3. Select Header: simply click Next.

4. Select Tool: select the PICKit3, or other supported programmer/debugger of your choice, and click Next.

5. Select Compiler: select C30 (or XC16 if available), and click Next.

6. Select Project Name and Folder: type 1-HelloWorld as the project name, type C:\ FlyingPIC24 as the folder name or use the Browse button to navigate to an existing directory of your choice and click Finish to complete the wizard setup.

After a brief moment, you will be presented with a new projects window. This is empty at the moment except for a number of logical folders. We will learn more about those gradually through the following few lessons.

The Flight

Since this is our very first time, let's take advantage of another little wizard offered by MPLAB X to automate the steps required to create a new source file and to make it part of the project. From MPLAB X main menu, select: File>New File ... This is a very short wizard that can be completed in just two steps:

1. Choose File Type: in the Categories panel, expand the Microchip Embedded folder and click on the C30 compiler. In the File Types panel select the mainp24f.c type.

2. Name and Location: in the File Name field type Hello1.c and click Finish to accept all other default settings.

The MPLAB X built-in Editor window will pop up showing the contents of the newly created Hello1.c file. It will contain three initial elements that happen to be common to all C programs:

1. A banner, composed of a few comment lines:

/* * File: Hello1.c * Author: your name here * * Created current date here */

2. An include directive:

#include <p24Fxxxx.h>

This is not yet a C statement, but more of an instruction for the MPLAB C compiler preprocessor telling the compiler to read the content of a device-specific file before proceeding any further. The content of the device-specific .h file chosen is nothing more than a long list containing the names (and structure) of all the internal special-function registers (SFRs) of the chosen PIC24 model. If accurate, the names reflect exactly those being used in the device datasheet. If you are curious, just open the file and take a look – it is a simple text file that you can open with the MPLAB editor. Here is a segment of the p24fj128ga010.h file (MPLAB automatically replaces those four xxxx in the include directive with the actual PIC24 model spelling). This is the part where the program counter and a few other special-function registers (SFRs) are defined:

... extern volatile unsigned int PCL __attribute__((__sfr__)); extern volatile unsigned char PCH __attribute__((__sfr__)); extern volatile unsigned char TBLPAG __attribute__((__sfr__)); extern volatile unsigned char PSVPAG __attribute__((__sfr__)); extern volatile unsigned int RCOUNT __attribute__((__sfr__)); extern volatile unsigned int SR __attribute__((__sfr__)); ...

3. The main() function:

int main( void) { return 0; }

In between those two curly brackets, before the return statement, is where we will soon put the first few instructions of our embedded-control application. Independently of this function position in the file, whether in the first lines on top or the last few lines in a million-lines file, the main() function is the place where the microcontroller (program counter) will go first at power-up or after each subsequent reset. One caveat – before entering the main() function, the microcontroller will execute a short initialization code segment automatically inserted by the linker. This is known as the crt0 code (or simply c0). The c0 code will perform basic housekeeping chores, including the initialization of the microcontroller stack, among other things.

MPLAB X New File wizard has created the Hello1.c file, saved it inside the project main directory and is now listing this file among the project sources (the first and only so far). You can verify it by going back to the Projects window, selecting Window>Projects (alternatively using the keyboard shortcut CTRL+1). By expanding the Source Files logical folder (click on the little box containing a plus sign next to the little blue folder icon), you will see that Hello1.c now is in the list (Figure 1.1).

Now is the time to start adding our own code to the project. Our mission is to activate for the first time one or more of the output pins of the PIC24.

For historical reasons, and to maintain the greatest compatibility possible with the previous generations of PIC® microcontrollers, the input output (I/O) pins of the PIC24 are grouped in modules or ports, each comprising up to 16 pins, named in alphabetical order from A to H. We will start logically from the first group, known as PortA. Each port has several special-function registers assigned to control its operations. The main one, and the easiest to use, carries traditionally the same name as that of the module (PORTA).

To distinguish the control register name from the module name we will use a different notation for the two: PORTA (all upper case) will be used to indicate one of the control registers; PortA will refer to the entire peripheral module.

According to the PIC24 datasheet, assigning a value of 1 to a bit in the PORTA register turns the corresponding output pin to a logic high level (3.3V). Vice versa, assigning a value of 0 to the same bit will produce a logic level low on the output pin (0V).

Assignments are easy in C language – we can insert a first assignment statement in our project as in the following example:

PORTA = 0xff;

First, notice how each individual statement in C must be terminated with a semicolon. Then notice how they resemble a mathematical equation ... they are not!

An assignment statement has a right side, which is computed first. A resulting value is obtained (in this case it was simply a literal constant) and it is then transferred to the left side, which acts as a receiving container. In this case it was the special-function PORTA register of the microcontroller.

Compiling and Linking

Now that we have completed main(), the first and only function of our first C program, how do we transform the source into a binary executable?

Using the MPLAB X Integrated Development Environment (IDE), it is very easy! It's a matter of a single click of your mouse – this operation is called a Project Build.

The sequence of events is actually pretty long and complex but it can be summarized in two steps:

Compiling, the MPLAB C compiler is invoked and an object code file (.o) is generated. This file is not yet a complete executable. While most of the code generation is complete, all the addresses of functions and variables are still undefined. In fact, this is also called a re-locatable code object. If there are multiple source files, this step is repeated for each one of them.

Linking, the MPLAB C linker is invoked and a proper position in the memory space is found for each function and each variable. Also, any number of pre-compiler object code files and standard library functions may be added at this time as required. Among the several output files produced by the linker there is the actual binary executable file (.hex).

All this is performed in a very rapid sequence as soon as you click on the Build Project button in the main toolbar, or you right click in the Projects window and select the Build option.

In order for MPLAB to know which file(s) need to be compiled, they must be present (as is the case for our Hello1.c example) in the projects window Source Files logical folder.

Similarly, for the linker to assign the correct addresses to each variable and function, a device-specific "Linker Script" file (.gld) must be located. This is taken care of automatically by MPLAB X, so we will not have to worry about it. Just as the include (.h) file tells the compiler about the names (and structure) of device-specific special-function registers (SFRs), the linker script informs the linker about their pre-defined positions in memory (according to the device datasheet) as well as providing essential memory space information such as total amount of flash memory available, total amount of RAM memory available and their address ranges.


Excerpted from Programming 16-Bit PIC Microcontrollers in C by Lucio Di Jasio Copyright © 2012 by Elsevier Inc. . Excerpted by permission of Newnes. All rights reserved. No part of this excerpt may be reproduced or reprinted without permission in writing from the publisher.
Excerpts are provided by Dial-A-Book Inc. solely for the personal use of visitors to this web site.

Read More

Customer Reviews

Average Review:

Write a Review

and post it to your social network


Most Helpful Customer Reviews

See all customer reviews >