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
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

eBook

$50.99  $59.95 Save 15% Current price is $50.99, Original price is $59.95. You Save 15%.

Available on Compatible NOOK Devices and the free NOOK Apps.
WANT A NOOK?  Explore Now

Related collections and offers


Overview

• A Microchip insider tells all on the newest, most powerful PICs ever! • FREE CD-ROM includes source code in C, the Microchip C30 compiler, and MPLAB SIM software• Includes handy checklists to help readers perform the most common programming and debugging tasksThe new 16-bit PIC24 chip provides embedded programmers with more speed, more memory, and more peripherals than ever before, creating the potential for more powerful cutting-edge PIC designs. This book teaches readers everything they need to know about these chips: how to program them, how to test them, and how to debug them, in order to take full advantage of the capabilities of the new PIC24 microcontroller architecture.Author Lucio Di Jasio, a PIC expert at Microchip, offers unique insight into this revolutionary technology, guiding the reader step-by-step from 16-bit architecture basics, through even the most sophisticated programming scenarios. This book’s common-sense, practical, hands-on approach begins simply and builds up to more challenging exercises, using proven C programming techniques. Experienced PIC users and newcomers to the field alike will benefit from the text’s many thorough examples, which demonstrate how to nimbly side-step common obstacles, solve real-world design problems efficiently, and optimize code for all the new PIC24 features. You will learn about:• basic timing and I/O operations, • multitasking using the PIC24 interrupts, • all the new hardware peripherals • how to control LCD displays, • generating audio and video signals, • accessing mass-storage media, • how to share files on a mass-storage device with a PC, • experimenting with the Explorer 16 demo board, debugging methods with MPLAB-SIM and ICD2 tools, and more!

Product Details

ISBN-13: 9781856178716
Publisher: Elsevier Science
Publication date: 11/07/2011
Series: Embedded Technology
Sold by: Barnes & Noble
Format: eBook
Pages: 416
File size: 7 MB

About the Author

Lucio Di Jasio is now Sales Manager in Europe for Microchip Inc. He was previously Application Segments Manager at Microchip in Chandler AZ. He has been intimately involved in the development of Microchip PIC products for over 10 years and is a well known writer and expert on the use of PIC products both via his Newnes books and his work at events such as the Microchip Masters.

Read an Excerpt

Programming 16-Bit PIC Microcontrollers in C

Learning to Fly the PIC 24
By Lucio Di Jasio

Newnes

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 microchip.com/mplab)

• 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.

(Continues...)



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.

Table of Contents

Contents

Preface....................xv
Introduction to the Second Edition....................xvii
Introduction....................xix
Chapter 1: The First Flight....................3
Chapter 2: A Loop in the Pattern....................23
Chapter 3: More Pattern Work, More Loops....................37
Chapter 4: Numb3rs....................53
Chapter 5: Interrupts....................67
Chapter 6: Taking a Look Under the Hood....................87
Chapter 7: Synchronous Communication....................105
Chapter 8: Asynchronous Communication....................141
Chapter 9: Glass = Bliss....................159
Chapter 10: It's An Analog World....................175
Chapter 11: Capturing Inputs....................193
Chapter 12: The Dark Screen....................225
Chapter 13: Mass Storage....................283
Chapter 14: File I/O....................305
Chapter 15: Volare....................351
Index....................381

What People are Saying About This

From the Publisher

The first and only book on the newest, most powerful PIC family ever- the 16-bit PIC24!

From the B&N Reads Blog

Customer Reviews