Tải bản đầy đủ (.pdf) (401 trang)

programming 16 bit mucrocontrollers in c - Lucio di jasio

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (6.46 MB, 401 trang )

Programming 16-Bit PIC Microcontrollers in C

AMSTERDAM • BOSTON • HEIDELBERG • LONDON
NEW YORK • OXFORD • PARIS • SAN DIEGO
SAN FRANCISCO • SINGAPORE • SYDNEY • TOKYO
Newnes is an imprint of Elsevier
Programming 16-Bit PIC Microcontrollers in C
Learning to Fly the PIC24
By
Lucio Di Jasio
Newnes is an imprint of Elsevier
30 Corporate Drive, Suite 400, Burlington, MA 01803, USA
Linacre House, Jordan Hill, Oxford OX2 8DP, UK
Copyright © 2007, Elsevier Inc. All rights reserved.
No part of this publication may be reproduced, stored in a retrieval system, or
transmitted in any form or by any means, electronic, mechanical, photocopying,
recording, or otherwise, without the prior written permission of the publisher.
Permissions may be sought directly from Elsevier’s Science & Technology Rights
Department in Oxford, UK: phone: (+44) 1865 843830, fax: (+44) 1865 853333,
e-mail: You may also complete your request online via
the Elsevier homepage (), by selecting “Customer Support” and
then “Obtaining Permissions.”
Recognizing the importance of preserving what has been written,
Elsevier prints its books on acid-free paper whenever possible.
Library of Congress Cataloging-in-Publication Data
(Application submitted.)
British Library Cataloguing-in-Publication Data
A catalogue record for this book is available from the British Library.
ISBN-13: 978-0-7506-8292-3
ISBN-10: 0-7506-8292-2


For information on all Newnes publications
visit our Web site at www.books.elsevier.com
07 08 09 10 10 9 8 7 6 5 4 3 2 1
Printed in the United States of America
Dedication
To Sara

vii
Contents
Preface xv
Introduction xvii
Who should read this book? xvii
Structure of the book xviii
What this book is not xix
Checklists xix
PART I
CHAPTER 1: THE FIRST FLIGHT 3
Flight plan 3
Prefl ight checklist 4
The fl ight 4
Compiling and linking 6
Building the fi rst project 7
PORT initialization 9
Retesting PORTA 10
Testing PORTB 10
Post-fl ight briefi ng 12
Notes for assembly experts 13
Notes for PIC MCU experts 14
Notes for C experts 14
Tips and tricks 14

Exercises 15
Books 15
Links 15
CHAPTER 2: A LOOP IN THE PATTERN 17
Flight plan 17
Prefl ight checklist 17
The fl ight 18
An animated simulation 21
Using the Logic Analyzer 24
Post-fl ight briefi ng 26
Notes for assembly experts 27
Contents
viii
Notes for PIC microcontroller experts 27
Notes for C experts 27
Tips and tricks 27
Exercises 28
Books 28
Links 28
CHAPTER 3: MORE PATTERN WORK, MORE LOOPS 29
Flight plan 29
Prefl ight checklist 30
The fl ight 30
Do Loops 30
Variable declarations 31
for loops 31
More loop examples 32
Arrays 33
A new demo 34
Testing with the Logic Analyzer 36

Using the Explorer16 demonstration board 37
Post-fl ight briefi ng 37
Notes for assembly experts 37
Notes for PIC microcontroller experts 38
Notes for C experts 38
Tips and tricks 38
Exercises 40
Books 40
Links 40
CHAPTER 4: NUMB3RS 41
Flight plan 41
Prefl ight checklist 42
The fl ight 42
On optimization (or lack thereof) 43
Testing 44
Going long 44
Note on the multiplication of long integers 45
Long long multiplication 45
Floating point 46
Notes for C experts 46
Measuring performance 47
Post-fl ight briefi ng 49
Notes for assembly experts 50
Notes for PIC microcontroller experts 51
Tips and tricks 51
Contents
ix
Math libraries 51
Complex data types 51
Exercises 52

Books 52
Links 52
CHAPTER 5: INTERRUPTS 53
Flight plan 53
Prefl ight checklist 53
The fl ight 54
Nesting of interrupts 57
Traps 57
A template and an example for Timer1 interrupt 58
A real example with Timer1 59
Testing the Timer1 interrupt 61
The secondary oscillator 63
The real-time clock calendar (RTCC) 64
Managing multiple interrupts 64
Post-fl ight briefi ng 65
Notes for C experts 65
Notes for assembly experts 65
Notes for PIC microcontroller experts 66
Tips and tricks 66
Exercises 68
Books 68
Links 68
CHAPTER 6: TAKING A LOOK UNDER THE HOOD 69
Flight plan 69
Prefl ight checklist 69
The fl ight 70
Memory space allocation 71
Program space visibility 72
Investigating memory allocation 73
Looking at the MAP 77

Pointers 79
The heap 80
MPLAB C30 Memory Models 81
Post-fl ight briefi ng 81
Notes for C experts 81
Notes for assembly experts 82
Notes for PIC microcontroller experts 82
Tips and tricks 82
Exercises 83
Contents
x
Books 83
Links 83
PART II – FLYING “SOLO”
CHAPTER 7: COMMUNICATION 89
Flight plan 89
Prefl ight checklist 89
The fl ight 90
Synchronous serial interfaces 90
Asynchronous serial interfaces 91
Parallel interfaces 92
Synchronous communication using the SPI modules 93
Testing the Read Status Register command 95
Writing to the EEPROM 98
Reading the memory contents 99
A nonvolatile storage library 99
Testing the new NVM library 102
Post-fl ight briefi ng 104
Notes for C experts 104
Notes for the experts 104

Notes for PIC microcontroller experts 105
Tips and tricks 105
Exercises 107
Books 107
Links 107
CHAPTER 8: ASYNCHRONOUS COMMUNICATION 109
Flight plan 109
Prefl ight checklist 109
The fl ight 110
UART confi guration 111
Sending and receiving data 113
Testing the serial communication routines 114
Building a simple console library 116
Testing a VT100 terminal 118
Using the serial port as a debugging tool 120
The matrix 120
Post-fl ight briefi ng 122
Notes for C experts 123
Notes for PIC microcontroller experts 124
Tips and tricks 124
About the ICD2 and UARTs on ICE 124
Exercises 125
Contents
xi
Books 125
Links 125
CHAPTER 9: GLASS BLISS 127
Flight plan 128
Pre-fl ight checklist 128
The fl ight 128

HD44780 controller compatibility 129
The Parallel Master Port 131
Confi guring the PMP for LCD module control 132
A small library of functions to access an LCD display 133
Advanced LCD control 136
Post-fl ight briefi ng 138
Notes for C experts 138
Tips and tricks 139
Exercises 140
Books 140
Links 140
CHAPTER 10: IT’S AN ANALOG WORLD 141
Flight plan 141
Prefl ight checklist 142
The fl ight 142
The fi rst conversion 144
Automatic sampling timing 145
Developing a demo 146
Developing a game 147
Measuring temperature 149
The breath-alizer game 153
Post-fl ight briefi ng 154
Notes for C experts 154
Tips and tricks 155
Exercises 155
Books 155
Links 155
PART III – CROSS-COUNTRY FLYING
CHAPTER 11: CAPTURING INPUTS 161
Flight plan 161

The fl ight 162
The PS/2 communication protocol 163
Interfacing a PIC24 to the PS/2 163
Input Capture 163
Testing the Input Capture method using Stimulus Scripts 168
Contents
xii
Testing the PS/2 receive routines 172
The simulation 174
The Simulator Profi le 175
Another method – Change Notifi cation 176
Evaluating cost 181
A third method – I/O polling 181
Testing the I/O polling method 186
Cost and effi ciency of the solution 188
Completing the interface: adding a FIFO buffer 190
Completing the interface: performing key codes decoding 194
Post-fl ight briefi ng 197
Tips and tricks 198
Stalling transmissions from the keyboard – Open-Drain Output Control 198
Exercises 199
Books 199
Links 199
CHAPTER 12: THE DARK SCREEN 201
Flight plan 201
The fl ight 202
Generating the composite video signal 204
Using the Output Compare modules 208
Memory allocation 211
Image serialization 211

Building the video module 214
Testing the video generator 218
Measuring performance 220
The dark screen 221
A test pattern 222
Plotting 223
A starry night 224
Line drawing 226
Bresenham algorithm 228
Plotting math functions 230
Two-dimensional function visualization 232
Fractals 236
Text 242
Testing the TextOnGPage module 246
Developing a text page video 247
Testing the text page performance 256
Post-fl ight briefi ng 260
Tips and tricks 260
Exercises 261
Books 261
Links 261
Contents
xiii
CHAPTER 13: MASS STORAGE 263
Flight plan 263
The fl ight 264
The SD/MMC card physical interface 264
Interfacing to the Explorer16 board 265
Starting a new project 266
Selecting the SPI mode of operation 267

Sending commands in SPI mode 267
Completing the SD/MMC card initialization 270
Reading data from an SD/MMC card 271
Writing data to an SD/MMC card 274
Using the SD/MMC interface module 276
Post-fl ight briefi ng 280
Tips and tricks 280
Exercises 281
Books 281
Links 281
CHAPTER 14: FILE I/O 283
Flight plan 283
The fl ight 284
Sectors and Clusters 284
The File Allocation Table (FAT) 285
The Root Directory 286
The treasure hunt 288
Opening a fi le 296
Reading data from a fi le 305
Closing a fi le 308
Creating the fi leio module 308
Testing fopenM() and freadM() 311
Writing data to a fi le 313
Closing a fi le, second take 317
Accessory functions 319
Testing the complete fi leio module 323
Code Size 326
Post-fl ight briefi ng 326
Tips and tricks 327
Exercises 327

Books 328
Links 328
CHAPTER 15: VOLARE 329
Flight plan 330
The fl ight 330
Contents
xiv
Using the PIC24 OC modules in PWM mode 332
Testing the PWM as a D/A converter 334
Producing analog waveforms 335
Reproducing voice messages 338
A media player 339
The WAVE fi le format 339
The play() function 341
The low level audio routines 347
Testing the WAVE fi le player 350
Optimizing the fi le I/O 353
LED Profi ling 353
Looking under the hood for more 356
Post-fl ight briefi ng 360
Tips and tricks 360
Exercises 360
Books 361
Links 361
About the Author 363
Index 365
xv
Writing this book turned out to be much more work than I had expected and, believe me, I was already
expecting a lot. This project would never have been possible if I did not have 110% support and
understanding from my wife, Sara. Special thanks also go to Steve Bowling, a friend, a pilot and an

expert on Microchip 16-bit architecture, for reviewing the technical content of this book and providing
many helpful suggestions for the demonstration projects and hardware experiments. Many thanks go
to Eric Lawson for constantly encouraging me to write and for all the time he spent fi xing my eternally
long-running sentences and my bad use of punctuation. I owe big thanks also to Thang Nguyen, who
was fi rst to launch the idea of the book; Joe Drzewiecky and Vince Sheard for patiently listening to my
frequent laments and, always working hard on making MPLAB® IDE a better tool; Calum Wilkie and
Guy McCarthy for quickly addressing all my questions and offering so much help and insight into the
inner workings of the MPLAB C30 compiler and libraries. I would also like to extend my gratitude
to all my friends and colleagues at Microchip Technology and the many embedded-control engineers
I have been honored to work with over the years. You have so profoundly infl uenced my work and
shaped my experience in the fantastic world of embedded control.
Preface

xvii
The story goes that I badly wanted to write a book about one of the greatest passions in my life: fl ying!
I wanted to write a book that would convince other engineers like me to take the challenge and live the
dream—learn to fl y and become private pilots. However, I knew the few hours of actual fl ying experi-
ence I had did not qualify me as a credible expert on the art of fl ying. So when I had an opportunity to
write a book about Microchip’s new 16-bit PIC24 microcontrollers, I just could not resist the tempta-
tion to join the two things, programming and fl ying, in one project. After all, learning to fl y means
following a well-structured process—a journey that allows you to acquire new capabilities and push
beyond your limits. It gradually takes you through a number of both theoretical and practical subjects,
and culminates with the delivery of the private pilot license. The pilot license, though, is really just the
beginning of a whole new adventure—a license to learn, as they say. This compares very well to the
process of learning new programming skills, or learning to take advantage of the capabilities of a new
microcontroller architecture.
Throughout the book, I will make brief parallels between the two worlds and in the references for each
chapter I will add, here and there, some suggestions for reading about fl ying. I hope I will stimulate
your curiosity and, if you happen to have this dream inside you, I will give you that last fi nal push to
help make it happen.

Who should read this book?
This is the part where I am supposed to tell you that you will have a wonderful experience reading this
book, that you will have a lot of fun experimenting with the software and hardware projects, and, that
you will learn about programming a shiny new 16-bit RISC processor in C, practically from scratch.
But, in all honesty, I cannot! This is only partially true. I do hope you will have a lot of fun reading this
book and the experiments are…“playful,” and you should enjoy them. However, you will need some
preparation and hard work in order to be able to digest the material I am presenting at a pace that will
accelerate rapidly through the fi rst few chapters.
This book is meant for programmers having a basic to intermediate level of experience, but not for
“absolute” beginners. Don’t expect me to start with the basics of binary numbers, hexadecimal notation
or the fundamentals of programming. However, we will briefl y review the basics of C programming
as it relates to applications for the latest generation of general-purpose 16-bit microcontrollers, before
moving on to more challenging projects. My assumption is that you, the reader, belong to one of four
categories:
Embedded-control programmer: experienced in assembly-language microcontroller program-
ming, but with only a basic understanding of the C language.
PIC® microcontroller expert: having a basic understanding of the C language.


Introduction
xviii
Student or professional: with some knowledge of C (or C++) programming for PCs.
Other SLF (superior life forms): I know programmers don’t like to be classifi ed that easily, so
I created this special category just for you!
Depending on your level and type of experience, you should be able to fi nd something of interest in
every chapter. I worked hard to make sure that every one of them contained both C programming tech-
niques and new hardware-peripheral details. Should you already be familiar with both, feel free to skip
to the experts section at the end of the chapter, or consider the additional exercises, book references
and links for further research/reading.
These are some of the things you will learn:

The structure of an embedded-control C program: loops, loops and more loops
Basic timing and I/O operations
Basic embedded-control multitasking in C, using the PIC24 interrupts
New PIC24 peripherals, in no specifi c order:
Input Capture
Output Compare
Change Notifi cation
Parallel Master Port
Asynchronous Serial Communication
Synchronous Serial Communication
Analog-to-Digital Conversion
How to control LCD displays
How to generate video signals
How to generate audio signals
How to access mass-storage media
How to share fi les on a mass-storage device with a PC
Structure of the book
Similar to a fl ying course, the book is composed of three parts. The fi rst part contains fi ve small chap-
ters of increasing levels of complexity. In each chapter, we will review one basic hardware peripheral
of the PIC24FJ128GA010 microcontroller and one aspect of the C language, using the MPLAB C30
compiler (Student Version included on the CD-ROM). In each chapter, we will develop at least one
demonstration project. Initially, such projects will require exclusive use of the MPLAB SIM software
simulator (included on the CD-ROM), and no actual hardware will be necessary, although an Explorer
16 demonstration board might be used.



















Introduction
xix
In the second part of the book, containing fi ve more chapters, an Explorer16 demonstration board (or
third-party equivalent) will become more critical, as some of the peripherals used will require real
hardware to be properly tested.
The third part of the book contains fi ve larger chapters. Each one of them builds on the lessons learned
in multiple previous chapters, while adding new peripherals to develop projects of greater complexity.
The projects in the third part of the book require the use of the Explorer 16 demonstration board and
basic prototyping-skills, too (yes, you might need to use a soldering iron). If you don’t want to or you
don’t have access to basic hardware-prototyping tools, an ad hoc expansion board containing all the
circuitry and components necessary to complete all the demonstration projects will be made available
on the companion Web site: http://www.fl yingthepic24.com.
All the source code developed in each chapter is also available for immediate use on the companion
CD-ROM.
What this book is not
This book is not a replacement for the PIC24 datasheet, reference manual and programmer’s manual
published by Microchip Technology. It is also not a replacement for the MPLAB C30 compiler user’s
guide, and all the libraries and related software tools offered by Microchip. Copies are available on the

companion CD-ROM, but I expect you to download the most recent versions of all those documents
and tools from Microchip’s Web site (). Familiarize yourself with them
and keep them handy. I will often refer to them throughout the book, and I might present small block
diagrams and other excerpts here and there as necessary. However, my narration cannot replace the in-
formation presented in the offi cial manuals. Should you notice a confl ict between my narration and the
offi cial documentation, ALWAYS refer to the latter. Please do send me an email if a confl ict arises. I
will appreciate your help and I will publish any corrections and useful hints I receive on the companion
Web site: http://www.fl yingthepic24.com.
This book is also not a primer on the C language. Although a review of the language is given through-
out the fi rst few chapters, the reader will fi nd in the references several suggestions on more complete
introductory courses and books on the subject.
Checklists
Pilots, both professional and not, use checklists to perform every single procedure before and during
a fl ight. This is not because the procedures are too long to be memorized or because pilots suffer from
more memory problems than others. They use checklists because it is proven that the human memory
can fail and that it tends to do so more often when stress is involved. Pilots can perhaps afford fewer
mistakes than other proffessionals, and they value safety above their pride.
There is nothing really dangerous that you as a programmer can do or forget to do while developing
code for the PIC24. Nonetheless, I have prepared a number of simple checklists to help you perform
the most common programming and debugging tasks. Hopefully, they will help you in the early stages,
when learning to use the new PIC24 toolset—even later if you are, like most of us, alternating between
several projects and development environments from different vendors.
Introduction

PART
I

3
CHAPTER
1

The fi rst fl ight
In This Chapter
 Compiling and linking
 Building the fi rst project
 PORT initialization
The fi rst fl ight for every student pilot is typically a blur—a sequence of brief but very intense sensa-
tions, including:
The rush of the fi rst take-off, which is performed by the instructor.
The white-knuckled, sweaty grip on the yoke while trying to keep the plane fl ying 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-in-
ducing 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 fi rst chapter will be no different.
Flight plan
Every fl ight should have a purpose, and preparing a fl ight plan is the best way to start.
This is going to be our fi rst project with the PIC24 16-bit microcontroller and, for some of you, the fi rst
project with the MPLAB® IDE Integrated Development Environment and the MPLAB C30 language
suite. Even if you have never heard of the C language before, you might have heard of the famous
“Hello World!” programming example. If not, let me tell you about it.
Since the very fi rst book on the C language, written by Kernighan and Ritchie several decades ago, ev-
ery 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 defi nitely not the case in the embedded-




 Retesting PORTA
 Testing PORTB
Chapter 1
4
control world. For our fi rst 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!”
Prefl ight checklist
Each fl ight is preceded by a prefl ight inspection—simply a walk around the airplane in which 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 (from the attached
CD-ROM and/or the latest version available for download from Microchip’s web site at http://www.
microchip.com/mplab):
MPLAB IDE, free Integrated Development Environment
MPLAB SIM, software simulator
MPLAB C30, C compiler (free Student Version).
Then, let’s follow the “New Project Set-up” checklist to create a new project with the MPLAB IDE:
Select “Project→Project Wizard” to activate the new project wizard, which will guide us auto-
matically through the following steps…
Select the PIC24FJ128GA010 device, and click Next.
Select the MPLAB C30 Compiler Suite and click Next.
Create a new folder and name it “Hello”; name the project “Hello Embedded World” and click
Next.
Simply click Next to the following dialog box—there is no need to copy any source fi les from
any previous projects or directories.
Click on Finish to complete the Wizard set-up.
For this fi rst time, let’s continue with the following additional steps:
Open a new editor window.

Type the following three comment lines:
//
// Hello Embedded World!
//
Select “File→Save As”, to save the fi le as: “Hello.c”.
Select “Project→Save” to save the project.
The fl ight
It is time to start writing some code. I can see your trepidation, especially if you have never written any
C code for an embedded-control application before. Our fi rst line of code is going to be:
#include <p24fj128ga010.h>



1.
2.
3.
4.
5.
6.
7.
8.
9.
10.

×