Programming 16-Bit PIC Microcontrollers in C Programming 16-Bit PIC Microcontrollers in C Learning to Fly the PIC 24 Second edition Lucio Di Jasio AMSTERDAM • BOSTON • HEIDELBERG • LONDON NEW YORK • OXFORD • PARIS • SAN DIEGO SAN FRANCISCO • SINGAPORE • SYDNEY • TOKYO Newnes is an imprint of Elsevier Newnes is an imprint of Elsevier The Boulevard, Langford Lane, Kidlington, Oxford, OX5 1GB, UK 225 Wyman Street, Waltham, MA 02451, USA Copyright © 2012 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) (0) 1865 843830; fax (44) (0) 1865 853333; email: [email protected]. Alternatively, visit the Science and Technology Books website at www.elsevierdirect.com/rights for further information Notice No responsibility is assumed by the publisher for any injury and/or damage to persons or property as a matter of products liability, negligence or otherwise, or from any use or operation of any methods, products, instructions or ideas contained in the material herein. Because of rapid advances in the medical sciences, in particular, independent verification of diagnoses and drug dosages should be made British Library Cataloguing-in-Publication Data A catalogue record for this book is available from the British Library Library of Congress Cataloging-in-Publication Data A catalog record for this book is available from the Library of Congress ISBN: 978-1-85617-870-9 For information on all Newnes publications visit our website at www.newnespress.com Typeset by MPS Limited, a Macmillan Company, Chennai, India www.macmillansolutions.com Printed and bound in the United States of America 11 12 13 14 15 10 9 8 7 6 5 4 3 2 1 This book is dedicated— To Sara and Luca Preface 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 have never been possible if I did not have 110% support and understanding from my wife. Special thanks also go to Steve Bowling, a friend, a pilot and an expert of 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 to fix my eternally long running sentences and my bad use of punctuation. I owe big thanks also to Thang Nguyen, who was first to launch the idea of the book; Joe Drzewiecky and Vince Sheard for patiently listening to my frequent laments, always working hard on making MPLAB a better tool; Calum Wilkie and Guy McCarthy for addressing quickly all my questions and offering so much help and insight into the inner workings of the MPLAB C compiler and libraries. Among the technical reviewers of the second edition, I would like to add special thanks to Stewart Cording, Tom Mignone, and Wayne Duquaine who helped me adapt the code to the many new families of PIC24 devices. But I would like to extend my gratitude to all my friends, ex-colleagues at Microchip Technology and the many embedded control engineers I have been honored to work with over the years. You have so profoundly influenced my work and shaped my experience in the fantastic world of embedded control. xv Introduction to the Second Edition In the six years since I completed the first manuscript of this book, there has been a tremendous evolution of the PIC24 architecture and all the supporting set of tools and documentation. What seemed like a promising, if only embryonic, new product line has become one of the main driving forces in Microchip Technology’s portfolio. The number of different models available has long passed the 100 mark. It's been growing up toward larger and larger memory sizes and more complex devices as well as down to smaller, simpler devices in tiny packages and with minuscule power consumption figures where, once upon a time, it used to be the undisputed sole domain of the smallest of the 8-bit PIC® architectures. Back then, when looking for evaluation boards, there was only one choice: the Explorer16 and that is what I had to use for the first edition of this book. Today the choice has been expanded to hundreds of new options offered by numerous and creative third parties worldwide. Interestingly, after much consideration, my final choice for this second edition has been to remain focused mainly on the Explorer16 demonstration board although the reader will be able to reproduces most/all examples and exercises on many other equivalent tools. This choice can be considered a testament to the success of the board in itself and the huge portfolio of expansion boards – known today as the PICTail Plus boards – that complete it. The Explorer16 today can be used to evaluate all 16-bit and 32-bit devices (dsPIC® digital signal controllers included) available in packages of 64 pin or higher, with clock frequencies that have reached 80 MHz at the time of this writing and will certainly pass that mark in the coming years. The same could be said for the programming and debugging tools. When once upon a time the ICD2 used to be the one and only choice, today there is a range of tools, from the simple and inexpensive PICKit3 to the fast and sophisticated REAL ICE, that can cover with agility the entire portfolio of 600 models of 8-bit, 16-bit and 32-bit microcontrollers offered by Microchip. So for this second edition my tool of choice has shifted (only slightly) to the generic PICKit3, for its cost, or the ICD3, for its speed, preferring them to more PIC24-specific tools of even lower cost (PIC24F Starter kit, PIC24H Stick…) considering that the work done in this book will represent only a starting point and the PICKit3 and ICD3 in circuit debuggers will have xvii xviii Introduction to the Second Edition the ability to continue to support you well beyond these 15 chapters and into the real world of embedded control. As per the MPLAB Integrated Development Environment, the evolution in these years has been relentless but incremental for the most part. In the last few months, I had the opportunity to test drive the new MPLAB X platform, an almost complete redesign of the tool around an open source platform known as NetBeans. MPLAB X offers tons of new features but also runs on a wider range of operating systems (including MAC OS X, and Linux at last). Most importantly it brings the promise of a greater stability and robustness. Every chapter in this book has been revised to accommodate for the new MPLAB X interface. In most cases, this has resulted in a simplification of what used to be long sequences of operations, previously detailed in extensive checklists, and now reduced to single mouse clicks. Finally let me add a word about the MPLAB C compiler, the PIC24F peripheral libraries and the Microchip Application Library. Here the evolution has been steady but nothing short of spectacular. The work on the compiler (now based on the open source GNU GCC v4 project) has been relentless and the real proof of quality of the results today can be quickly summarized in two bullets: l None of the examples in this book required a single line of assembly code! This is in stark contrast to the first edition, when in several chapters I had to augment the examples with numerous and, at times, cryptic assembly code workarounds. l Both performance and code size figures had to be corrected in most/all chapters as the compiler produced much tighter code (up to 30% smaller) and faster code (removing the need for extensive hand optimizations) while utilizing only optimization levels 0 and 1 available on all the evaluation (as in free) copies of the compiler. The PIC24 peripheral libraries have remained an interesting but mixed bag from my point of view. So I have been picking and choosing, very selectively, chapter by chapter when, why and what to take from them. The Microchip Application Libraries (MAL), a large collection of modules that used to be offered as separate application notes (USB, Ethernet, Graphic displays…) deserve a separate mention. Unfortunately the size of the library and the complexity of the subjects covered made it impossible for me to add in this book more than a few hints here and there, and links at the end of related chapters. Each library in the MAL would have perhaps required an entire book dedicated to each subject. So in the end, far from a definitive work, as too many books claim to be nowadays, this second edition of the “Flying PIC24” is more than ever similar to a private pilot license, a true license to learn, merely the beginning of an adventure that never ends. Introduction The story goes that I badly wanted to write a book about one of the greatest passions in my life: flying! I wanted to write a book that would convince other engineers like me to take the challenge and live the dream – learn to fly and become private pilots. The thing is that I knew the few hours of actual flying experience I had did not qualify me as a credible expert on the art of flying. So when I had an opportunity to write a book about Microchip’s new 16-bit PIC24 microcontrollers, I just could not resist the temptation to join the two things, programming and flying, in one project. After all, learning to fly means following a well structured process – a journey that allows you to acquire new capabilities and push beyond your limits. It takes you gradually 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 so 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 flying. I hope I will stimulate your curiosity and, if you had this dream inside you, I will give you that last final 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 you will learn about C programming a shiny new 16-bit RISC processor, practically from scratch. But, in all honesty I cannot! This is only partially true – I really hope you will have a lot of fun reading it and the experiments are ... “playful” and you should enjoy them. However you will need quite 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 first few chapters. This book is meant for programmers of a basic to intermediate level of experience, but not for “absolute” beginners; so don’t expect me to start with the basics of the binary numbers, the hexadecimal notation or the fundamentals of programming. Although, we will briefly review xix xx Introduction the basics of C programming as it relates to the 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: l Embedded Control programmer: experienced in assembly-language microcontrollers programming, but with only a basic understanding of the C language. l PIC® microcontroller expert: with a basic understanding of the C language. l Student or professional: with some knowledge of C (or C) programming for PCs. l Other SLF (superior life forms): I know programmers don’t like to be classified that easily so I created this special category just for you! Depending your level and type of experience, you should be able to find something of interest in every chapter. I worked hard to make sure that every one of them contained both C programming techniques and new hardware peripherals 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: l The structure of an embedded-control C program: loops, loops and more loops l Basic timing and I/O operations l Basic embedded control multitasking in C, using the PIC24 interrupts l new PIC24 peripherals, in no specific order: l Input Capture l Output Compare l Change Notification l Parallel Master Port l Asynchronous Serial Communication l Synchronous Serial Communication l Analog-to-Digital conversion l How to control LCD displays l How to generate video signals l How to generate audio signals l How to access mass-storage media l How to share files on a mass-storage device with a PC Structure of the Book Similar to a flying course, the book is composed of three parts. The first part contains five small chapters of increasing levels of complexity. In each chapter, we will review one basic Introduction xxi hardware peripheral of the PIC24FJ128GA010 microcontroller and one aspect of the C language, using the MPLAB C30 compiler (Student Version included in 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 in the CD-ROM), and no actual hardware will be necessary; although, an Explorer 16 demonstration board might be used. In the second part of the book, containing five 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. In the third part of the book, there are five 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.flyingpic24.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 (http://www .microchip.com). 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. But, my narration cannot replace the information presented in the official manuals. Should you notice a conflict between my narration and the official documentation, ALWAYS refer to the latter. However please send me an email if a conflict arises, I will appreciate your help and I will publish any correction and useful hint I will receive on the companion Web site: http://www.flyingpic24.com This book is also not a primer on the C language. Although a review of the language is performed throughout the first few chapters, the reader will find in the references several suggestions on more complete introductory courses and books on the subject.