Table Of ContentPIC Projects and
Applications using C
PIC Projects and
Applications using C
A Project-based Approach
Third edition
David W. Smith
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
First edition 2002
Second edition 2006
Third edition 2013
Copyright © 2013 Elsevier Ltd. All rights reserved
No part of this publication may be reproduced or transmitted in any form or by
any means, electronic or mechanical, including photocopying, recording, or any
information storage and retrieval system, without permission in writing from the
publisher. Details on how to seek permission, further information about the Publisher’s
permissions policies and our arrangement with organizations such as the Copyright
Clearance Center and the Copyright Licensing Agency, can be found at our website:
www.elsevier.com/permissions.
This book and the individual contributions contained in it are protected under
copyright by the Publisher (other than as may be noted herein).
Notice
Knowledge and best practice in this field are constantly changing. As new research
and experience broaden our understanding, changes in research methods, professional
practices, or medical treatment may become necessary.
Practitioners and researchers must always rely on their own experience and
knowledge in evaluating and using any information, methods, compounds, or
experiments described herein. In using such information or methods they should be
mindful of their own safety and the safety of others, including parties for whom they
have a professional responsibility.
To the fullest extent of the law, neither the Publisher nor the authors, contributors, or
editors, assume any liability 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.
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-0-08-097151-3
For information on all Newnes publications
visit our website at www.books.elsevier.com
13 14 15 16 10 9 8 7 6 5 4 3 2 1
Printed in the United States of America
Preface
The aim of this book is to enable the reader to program the 18F series of
PIC Microcontrollers in the C language using Microchip’s MPLAB C18 com-
piler. The program examples demonstrate the power of the C language, yet the
reader does not have to be a C programmer in order to benefit from this tech-
nology as the C language is added and explained as required.
The chapters show numerous applications starting with switching out-
puts on, then using digital inputs such as switches and keypads. This book
continues with making measurements from analogue inputs, writing to alpha
numeric displays, using timers and interrupts, and transmitting data via radio
links.
There is a section on fault finding using the MPLAB simulator and in-
circuit debugger. So that faults can be located easier.
All of the chapters show applications on how to use the program examples.
The programs are complete and are clearly explained.
My aim has been to show the reader how to use the Microcontroller to
develop programs for projects. I have tried to keep the technical detail down to
a minimum and have not gone into a deeper understanding of how the micro-
controller is working inside. An understanding of the electronics inside the
microcontroller is not necessary to enable the reader to program it.
The reader is encouraged to build the programs, see how they work, and
then modify the code to enable a clearer understanding of the principles
involved; a development kit is available to do this. My own students have been
ingenious in developing faults in code and I have used their efforts, hopefully,
to produce an easy-to-understand guide to programming the PIC micro in C.
The programs listed in this book and the details of the development kit
are available from the book’s companion website: http://booksite.elsevier.
com/9780080971513.
DW Smith BSc., MSc.
Lecturer in Electronics, Manchester Metropolitan University
April 2013
ix
Chapter 1
Introduction to the
Microcontroller and C
A microcontroller is an integrated circuit that has a number of memory
locations embedded inside it which are used to store instructions that are to be
executed. These locations are called registers, and instructions are written to
these registers to enable the microcontroller to perform an operation.
The memory location is 8 bits wide which means it can store 8 bits of
information (Figure 1.1). The 8 bits in the memory are identified by numbers
starting on the right with the least significant bit, bit 0, and moving to the left
to the most significant bit, bit 7.
Suppose we wish to turn on an LED connected to an output pin, as shown
in Figure 1.2. An instruction has to be written to the output port register to out-
put a logic 1 to turn the LED on or output a logic 0 to turn it off.
The microcontroller we will use in this book is a PIC18F1220 manu-
factured by Microchip, although the codes can easily be adapted for other
Microchip microcontrollers. The PIC18F1220 has 16 inputs/outputs (I/O)
which means it has 16 inputs or outputs which can be configured as inputs
or outputs by instructing the microcontroller via a register, the tristate (TRIS)
register (Figure 1.3). TRIS means the port pin can be (i) an input, or an output
which is switched (ii) high or (iii) low, three states.
The memory locations in the microcontroller are 8 bits wide so 16 I/O will
require two 8 bit registers called PORTA and PORTB.
Suppose we wish to turn on an LED which we are going to connect to bit
4 on PORTB. We first of all have to instruct the microcontroller to ensure that
PORTB bit 4 is an output. At the moment it does not matter what the rest of
Memory location
Bits 7 6 5 4 3 2 1 0
MSB LSB
FIGURE 1.1 A microcontroller memory location.
PIC Projects and Applications using C.
© 22001133 David W. Smith. Published by Elsevier Ltd. All rights reserved. 1
2 PIC Projects and Applications using C
B4 10
470R
18F1220 LED1
0v
5v
14
V+
5 0.1µ
0v
0v
FIGURE 1.2 A basic microcontroller circuit.
TRISB
1 1 1 0 1 1 1 1
Bits 7 6 5 4 3 2 1 0
FIGURE 1.3 The TRIS register.
PORTB
1
Bits 7 6 5 4 3 2 1 0
FIGURE 1.4 Writing to PORTB.
PORTB is doing, so now let’s make bit 4 an output and the other 7 bits inputs.
We do this with the following instruction:
TRISB = 0b11101111;
0b means the number is a binary one.
Note a 1 sets the pin as an input, a 0 sets the pin as an output.
Now that PORTB bit 4 is an output, we can write a logic1 to it with:
PORTBbits.RB4 = 1; (Figure 1.4).
There are several ways in which we can give the microcontroller instruc-
tions, called programming. These program languages are assembly, basic, C,
or a number of flowchart languages. The language that we are going to use in
this book is the C programming language, which is a high-level language that
Chapter | 1 Introduction to the Microcontroller and C 3
is very versatile. The previous book “PIC in Practice” written by the author,
DW Smith, used the assembly language to program the microcontroller.
C is a very comprehensive and versatile language, which usually means
there is a lot to learn. Throughout this book I will introduce the C language as
and when required and only those instructions that are needed to perform the
control. So you will not need to become a C programmer in order to program
the micro in C!
Chapter 2
First C Program
In order to program the microcontroller we are going to:
l Write the code in C.
l Convert the code to a hex file using a compiler.
l Program the hex file into the microcontroller.
The code which we are going to write in the C language can be written on
any text editor such as WORD. Any suitable C compiler can be used to convert
the code to a hex file and there are numerous programmers on the market that
will blow your hex file into the microcontroller.
Throughout this book I am going to use a dedicated piece of software
called MPLAB integrated development environment (IDE) written by the PIC
microcontroller manufacturer, Microchip. This acts as a text editor, compiler,
and driver for the Microchip programmer. MPLAB IDE is free and can be
downloaded from the Microchip Web site at Microchip.com
At the time of writing Microchip have upgraded MPLAB v8 and have
called it MPLABX. I have discussed both IDEs here and left it up to the reader
to decide which one they prefer to use.
MPLAB and MPLABX also include a simulator that help to debug your
code. I use Microchips own programmer/in-circuit debugger (ICD) called
Microchip MPLAB ICD3 and PICkit3. The ICDs allow you to connect your
circuit to the computer so that you can view the registers inside the micro
when the program is running. But we can see more of the simulator and
debugger later.
MPLAB AND MPLABX INSTALLATION
Install the latest version of MPLAB, as of 7/1/2011 that is MPLAB v8.73a.,
and the C compiler is MPLAB C v3.40 LITE. NB. MPLAB and the LITE ver-
sion of the C compiler are free from Microchip.com
Or install MPLABX IDE and the C compiler XC8.
Make a new folder to keep your programs in, say PicProgs on your
desktop.
PIC Projects and Applications using C.
© 22001133 David W. Smith. Published by Elsevier Ltd. All rights reserved. 5
6 PIC Projects and Applications using C
RA0/AN0 1 18 RB3/CCP1/P1A
RA1/AN1/LVDIN 2 17 RB2/P1B/INT2
RA4/T0CK1 3 16 OSC1/CLKI/RA7
MCLR/VPP/RA5 4 20 15 OSC2/CLKO/RA6
X
1
VSS/AVss 5 8F 14 VDD/AVDD
1
C RB7/PGD/T1OSI/
RA2/AN2/VREF- 6 PI 13 P1D/KBI3
RA3/AN3/VREF+ 7 12 RB6/PGC/T1OSO/
T13CKI/P1C/KBI2
RB0/AN4/INT0 8 11 RB5/PGM/KBI1
RB1/AN5/TX/ RB4/AN6/RX/
9 10
CK/INT1 DT/KBI0
FIGURE 2.1 The 18F1220 pin diagram.
For our first program we are going to flash an LED on and off at 1 s inter-
vals on the output pin, PORTB,4.
The pin connection for the 18F1220 is shown in Figure 2.1.
But before we program our device we need to understand a little of the C
language.
A BRIEF INTRODUCTION TO C FOR THE MICROCONTROLLER
Turning an output on/off
If we wish to turn an LED on PORTB bit4 on, the C code is:
PORTBbits.RB4 = 1;
This is called a statement. NB all C statements end in ;
If we wish to turn the LED off the code is:
PORTBbits.RB4 = 0;
Delays
In the C language suite we have installed a file called Delay.h. As its name sug-
gests there are a number of routines in this file which can create a delay in our
program. The address for this file if you want to read it is “C:\Program Files\
Microchip\mplabc18\v3.40\h” after installing MPLAB from Microchip.com
The subroutines are:
Delay1TCY()
Delay10TCYx()
Delay100TCYx()
Delay1KTCYx()
Chapter | 2 First C Program 7
Delay10KTCYx()
If you wish to call a subroutine in C you just state its name, i.e.,
Delay1KTCYx();
These delays are multiples of timing cycles, i.e., 1, 10, 100, 1000, and
10,000.
A timing cycle is the time taken to execute an instruction and it is the basis
of the timing in the microcontroller system. The timing comes from the oscil-
lator which can be an external clock source, an external crystal, or an internal
oscillator. For now we are going to use the internal oscillator set at 31.25 kHz.
The timing cycle runs at one-fourth of this frequency, i.e., at 7.8125 kHz.
This means the period of the timing cycle is 0.128 ms.
So the Delay100TCYx() subroutine will have a time of 100×0.128 ms
= 12.8 ms.
In order to achieve a delay of 1 s we would need 78 of these 12.8 ms.
78 × 12.8 ms = 0.9984 s, not quite 1 s but near enough for this application.
To do this the C code is:
Delay100TCYx(78);
Note the number of times the subroutine is executed is written in the
brackets (78) in this case. NB. 255 is the maximum value that can be entered.
Loops
In order to make the program execute some code a number of times or indefi-
nitely, we use a loop.
The WHILE LOOP as it is called looks like this:
while ( )
{
}
The code to be executed is written between the brackets { } while the con-
dition for executing the code is written between the brackets ( )
Suppose we wish to turn an alarm on if the temperature goes above 60°C,
the code would look like:
while (Temperature>60)
{
PORTBbits.RB0 = 1; // turn on PORTB bit0
}
If we wish to execute a piece of code indefinitely such as flashing our LED
on PORTB bit 4 on and off continuously, the loop is:
while (1)
{
PORTBbits.RB4 = 1; // turn on PORTB bit4