Instant Access to (Ebook) Pic Projects and Applications Using C. A Project-based Approach by David W. Smith (Auth.) ISBN 9780080971513, 0080971512 ebook Full Chapters
Instant Access to (Ebook) Pic Projects and Applications Using C. A Project-based Approach by David W. Smith (Auth.) ISBN 9780080971513, 0080971512 ebook Full Chapters
ebooknice.com
https://ebooknice.com/product/batik-gems-29-dazzling-quilt-
projects-4447316
ebooknice.com
https://ebooknice.com/product/vagabond-vol-29-29-37511002
ebooknice.com
ebooknice.com
(Ebook) Classical Hopf Algebras and Their Applications
(Algebra and Applications, 29) by Pierre Cartier, Frédéric
Patras ISBN 9783030778446, 3030778444
https://ebooknice.com/product/classical-hopf-algebras-and-their-
applications-algebra-and-applications-29-34794516
ebooknice.com
ebooknice.com
ebooknice.com
ebooknice.com
ebooknice.com
Pic Projects and Applications Using C A Project based
Approach 3rd ed Edition David W. Smith (Auth.) Digital
Instant Download
Author(s): David W. Smith (Auth.)
ISBN(s): 9780080971513, 0080971512
Edition: 3rd ed
File Details: PDF, 20.36 MB
Year: 2013
Language: english
PIC Projects and
Applications using C
PIC Projects and
Applications using C
A Project-based Approach
Third edition
David W. Smith
13 14 15 16 10 9 8 7 6 5 4 3 2 1
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.
B4 10
470R
18F1220 LED1
0v
5v
14
V+
5 0.1 µ
0v
0v
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
RA0/AN0 1 18 RB3/CCP1/P1A
RA1/AN1/LVDIN 2 17 RB2/P1B/INT2
RA4/T0CK1 3 16 OSC1/CLKI/RA7
PIC18F1X20
MCLR/VPP/RA5 OSC2/CLKO/RA6
4 15
VSS/AVss 5 14 VDD/AVDD
RA2/AN2/VREF- RB7/PGD/T1OSI/
6 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/ 9 10 RB4/AN6/RX/
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.
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
8 PIC Projects and Applications using C
Delay100TCYx(78); // wait 1 s
PORTBbits.RB4 = 0; // turn off PORTB bit4
Delay100TCYx(78); // wait 1 s
}
The function while (1) means while 1 is true! But 1 is always 1, so the loop is
always executing. Note the function while (1) does not end with a ;
The // code means ignore what follows on the line; it is for our reference
not for the compiler.
A useful while loop involves just 1 line of code, i.e.,
while (PORTBbits.RB4==1);
This means continue the loop (just 1 line) until PORTBbits.RB4==1 is
no longer true, i.e., wait until PORTBbits.RB4==0 before moving on in the
program.
Note: == means is equal to,=means equals. One is a question and the other
a statement.
aid of a programmer. The project also contains the workspace which is the
user screen that would show the registers and the watch window. We will use
these later when we look at the simulator.
To make the project, select Project/Project Wizard as shown in Figure 2.7.
Click Next on the dialogue box of Figure 2.8.
Step 1: select the microcontroller you require, the PIC18F1220, from the
Project Wizard as shown in Figure 2.9.
Step 2: select the language toolsuite to use, i.e., the C18 compiler.
If not already selected choose Microchip C18 Toolsuite as your Active
Toolsuite as shown in Figure 2.10.
Then click, Next.
10 PIC Projects and Applications using C
Step 3: create the project, browse for the directory you have created, i.e.,
PICProgs, and create a new project file, flash, or open it if it is already created,
as shown in Figure 2.11.
Click Save, then.
Click Next.
Step 4: add existing files to your project (Figure 2.12).
At the moment we do not have any existing files. If you have a copy of
flash.c you can add it now. If not just click Next.
That’s the project made.
Chapter | 2 First C Program 15
Click Finish (Figure 2.13) to finish making the project and return to the
workspace.
We now have a project called flash saved in the PICProgs folder. Now we
can write our C program called flash.c.
We have already discussed the steps involved in the program.
16 PIC Projects and Applications using C
Your screen should look like Figure 2.15 with the code entered.
PORTA, TRISB, and PORTB. Make sure you use the correct register and
pin names in your code. You can view p18f1220.h to see what the registers
and pins are called.
l Line 2. Pragma describes a task which is performed before the code is
run. Here in the configuration register we are turning the watch dog timer
(WDT) off. The WDT is a timer which will cause the program to reset if
the WDT is not reset. We will not be using this, so do not worry about it,
but turn it off. The oscillator is configured to run internally with OSC =
INT02. The power up timer, PWRT, is turned on by PWRT = ON. This
waits 20 ms after the power is applied before running the program, to give
the voltages time to settle. The low voltage programming, LVP, is turned
off, LVP = OFF because it conflicts with RB5 and the Master Clear is
disabled, MCLRE = OFF because a low on RA5 would clear the program.
We will be adding other pragmas in future programs.
If any of these pragma configs need changing then the codes can be
found in the MPLAB HELP menu under Topics/ PIC18 Config Settings.
l Line 3. We are adding the delays.h file which of course has the delay code
as described earlier.
The header files can be viewed by right clicking on the name in the pro-
gram. To view the delays.h file right click on the #include line and Open
File “delays.h” as shown in Figure 2.15.
l Line 4. It is blank, blank lines make the program easier to read.
l Line 5. Void main (void) is a function or method in C. Void means the
function does not return anything. A function Sum (answer) would return
the answer to an addition. The main function is the point at which the
C code starts running. The main function executes the code between the
brackets { } on lines 6 and 23. Of course more about functions later.
l Line 7. It is a comment explaining that the following code paragraph pro-
vides the initial configuration for our micro.
l Line 8. Another comment explaining the register OSCCON, oscillator con-
trol register, defaults to 31 kHz. This is what we require for this program.
l Line 9. The 18f1220 has seven of its pins that can be used as analogue
inputs when performing an A–D conversion. If we are not using the A–D
then we need to configure the inputs as digital. The default is they are ana-
logue. A 1 in ADCON1, Analogue to digital conversion register 1, sets the
input as digital, a 0 sets the input as analogue.
l Line 10. Sets up the PORTA pins as inputs, a 1 in a TRISA bit sets the cor-
responding pin as an input, a 0 sets the pin as an output.
l Line 11. Sets the PORTA output pins to 0. Not required since the pins are
all inputs.
l Line 12. Configures PORTB pins as all outputs.
l Line 13. Sets all PORTB outputs to 0. A good starting point, all outputs off.
l Line 16. Calls the ‘while function’ which runs continually. The code exe-
cuted by the while function is between the brackets { } line 17 and line 22.
l Line 18. Turns PORTB bit 4 on.
Chapter | 2 First C Program 19
Fixing Errors
In my code, line 18, I have introduced a syntax error. I have changed
PORTBbits.RB4 to PORTBbits.4
The error is shown in the output box (Figure 2.19) which ends with the
statement in red, BUILD FAILED.
Clicking on the error in the output box will highlight the error in the code
as indicated.
Fix all of the errors and save your changed code and Build All again. You
should then see BUILD SUCCEEDED in the output box. Once the build has
been successful you have automatically created the HEX file to program in the
microcontroller—in this case flash.hex.
TYPES OF ERRORS
When your program compiles the errors indicated are syntax errors. The com-
piler will not tell you if your program is going to work correctly.
The types of mistakes you could make are:
l Not spelling the Register name correctly.
l Not spelling the Bit name correctly.
l Adding a ; when it is not required.
l Missing a ; when it is required.
l Misspelling a C command.
20 PIC Projects and Applications using C
(A)
(B)
FIGURE 2.20 (A) The Microchip ICD3 and (B) The PICkit3.
NOTE
In the remainder of this book we will be writing C files and putting them
into projects. You can choose to do this with MPLAB or MPLABX.
24 PIC Projects and Applications using C
Install MPLABX IDE and the C compiler XC8 available from Microchip.
com.
While following this section please also refer to MPLABX IDE User
Guide available from Microchip.
In order to program our code into the microcontroller we will need to build
a project.
Every embedded project contains the following items.
1. Group of files to build a final embedded image.
2. Device the resultant image will be built for, e.g., 18F1220.
3. Compiler to use to build the image; we will be using the XC8.
4. Hardware Tool to be used for debugging/programming the target device.
2. Select the device you want to use in your project, PIC18F1220. Click Next
(Figure 2.28).
3. Select the Hardware Tool you want to use to either debug your
application or program your target device, e.g., PICkit3. Click Next
(Figure 2.29).
4. Select the compiler toolchain (toolsuite) you want to use to build the output
image of your project, e.g., XC8, Click Next (Figure 2.30).
5. Provide a project name and directory where you want the project to
reside. Click Finish. I have used the Flash program to produce the project
(Figure 2.31).
Your project should now be visible in the “Project” window (Figure
2.32).
You have now created a new embedded project. The next step is to add
your code (C file) to the project.
The line numbers can be turned on and off by right clicking the line num-
bers column.
The project is now ready to build, i.e., to convert the C code to hex code
for the chip.
Chapter | 2 First C Program 31
The program should have built successfully. If not double click the error
statement and correct the errors.
The project hex file is now ready to be programmed into the chip.
Connect the PICkit3 (or any other programmer) to the chip following the
manufacturer’s instructions. Click the program icon as shown in Figure 2.40.
The output box (Figure 2.41) should indicate that the Programming has
been verified and is complete.
Connect the microcontroller to your circuit and observe the LED flashing.
Now that we have written our first program let us consider switching all 8
outputs on PORTB.
34 PIC Projects and Applications using C
FLASHING 8 LEDs.
For this program we are going to flash all eight outputs on PORTB.
Consider the circuit as shown in Figure 3.1.
In order to achieve our objective we will be using the following steps:
l Open MPLAB.
l Create the C file (see Figure 2.3). Call it flash8.c.
13 8680 R
B7
12
B6
11 0V
B5
10 0V
B4
0V
0V
18
B3
17
B2
9 0V
B1
0V
8
B0
0V
0V
5V
V+ 14
0.1 µ
0V 5
0V
l Create a project called flash8, using the Project Wizard (see Figures
2.7–2.13).
l Add flash8.c to your project (see Figure 2.16).
l Compile your project (see Figure 2.18).
l Program your target device (see Figure 2.23).
To create the C file flash8.c copy and paste lines 1–13 of flash.c onto the
file editor screen (see Figure 2.15) and add the following lines of code shown
in Figure 3.2.
NB. The line numbers are not required in the program; they are only
included as a guide.
1. #include <p18f1220.h>
2. #pragma config WDT=OFF , OSC=INTIO2 , PWRT = ON, LVP=OFF, MCLRE = OFF
3. #include <delays.h>
4.
5. void main (void)
6. {
7. //SET UP
8. // OSCCON defaults to 31kHz. So no need to alter it.
9. ADCON1 = 0x7F; //all IO are digital or 0b01111111 in binary
10. TRISA = 0b11111111; //sets PORTA as all inputs
11. PORTA = 0b00000000; //turns off PORTA outputs, not required, no outputs
12. TRISB = 0b00000000; //sets PORTB as all outputs
13. PORTB = 0b00000000; //turns off PORTB outputs, good start position
14.
15. while (1)
16. {
17. PORTB = 0b11111111; // all outputs on
18. Delay100TCYx(78); // wait 1s
19. PORTB = 0b00000000; // all outputs off
20. Delay100TCYx(78); // wait 1s
21.
22. PORTB = 0b10101010; // alternate outputs on
23. Delay100TCYx(78); // wait 1s
24. PORTB = 0b01010101; // alternate outputs on
25. Delay100TCYx(78); // wait 1s
26. }
27. }
FIGURE 3.2 Flash8.c code.
Chapter | 3 Using Eight Outputs 37
If you are confident with what you are doing then you can use the short cut
instead of using the Project Wizard, as follows:
l Select Project—New as shown in Figure 3.3.
l In the New Project box that opens up enter the project name, flash8, and
the directory location, PIC Progs.
l Now add your file to the project with Project—Add files to project as
shown in Figure 3.4.
In the Add files project box enter the file name flash8 and the directory PIC
Progs in the Look in box and click Open.
l Now build your project (see Figure 2.17)
l Program the target device (see Figure 2.23)
l Try out your Microcontroller in your circuit
Updated editions will replace the previous one—the old editions will
be renamed.
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the terms
of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.
• You pay a royalty fee of 20% of the gross profits you derive from
the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
1.F.4. Except for the limited right of replacement or refund set forth in
paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.
Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebooknice.com