0 ratings0% found this document useful (0 votes) 389 views162 pagesPIC C - An Introduction To Programming The Microchip PIC in C
PIC C - An Introduction to Programming the Microchip PIC in C_ Nigel Gardner (Bluebird Electronic
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
- An introduction to programming
i the Microchip PIC in C
by Nigel GardnerBluebid Electronics Pic Cc
PIC C
An introduction to programming
the Microchip PIC in C
by Nigel GardnerPic CG Bluebird Electronics
he information contained in this publication regarding device
applications and the like is intended by way of suggestion only and
may be superseded by updates. No representation or warranty Is given
and no liability is assumed by Bluebird Electronics, Microchip
Technology Inc., CCS, Hitech or Inprise Corporation with respect to the
accuracy or use of such information, or infringement of patents arising
from such use or their compliance to EMC standards or otherwise. Use
of Bluebird Electronics, Microchip Technology Inc., CCS, Hitech or
Inprise Corporation products as critical components in life support
systems 1s not authorised except with express written approval by
Bluebird Electronics, Microchip Technology Inc., CCS, Hitech or Inprise
Corporation. No licenses are conveyed, implicitly or otherwise, under
intellectual property rights.
Copyright © Bluebird Electronics 1998. All rights reserved. Except as
permitted under the Copyright Act of 1976, no part of this publication
may be reproduced or distributed in any form or by any means, or stored
in a database or retrieval system, without the prior written permission of
Bluebird Electronics, with the exception of the program listings which
may be entered, stored, and executed in a computer system, but may
not be reproduced for publication.
Typeset and printed in the UK by: Character Press Limited, Tel: 01462
896500. First printed in 1998.
Circuit diagrams produced with Labcentre Isis Illustrator. Flowcharts
produced with Corel Flow.Preface Pic Cc
B® Preface
hanks go to Rodger Richey of Microchip Technology Inc. for the use
of his notes on C for the PICmicro, Clyde at Hi Tech for the copy of
their C compiler, Nan Borreson of Inprise Corporation for TurboC++ Lite
and Val Bellamy for proof reading this book.
This book is dedicated to my wife June and daughter Emma.J ‘Pic G _ : __ Contents
> Contents
Introduction
History
Why use C ?
PC Based versus PIC Based Program Development
Product Development
Terminology
Trying and Testing Code
C Coding Standards
Basics
1 C Fundamentals
Structure of C programs
Components of a C program
#pragma
main()
#include
printf Function
Variables
Constants
Comments
Functions
C Keywords
2 Variables
Data Types
Variable Declaration
Variable Assignment
Enumeration
typedef
type Conversions
3 Functions
Functions
Function Prototypes
Se Fl aeUsing Function Arguments.
Using Functions to return values
Classic and Modern Function Declarations
4 Operators
Arithmetic
Relational
Logical
Bitwise
Increment and Decrement
Precedence of
5 Program Control Statements
if
if-else
2
for Loop
while Loop
do-while Loop
Nesting Program Control Statements
break
continue
switch
null
return
6 Arrays / Strings
One Dimentional Arrays
Strings
Multidimensional Arrays
Initialising Arrays
Arrays of Strings
7 Pointers
Pointer basics
Pointers and arrays
Passing pointers to functionsPic Cc
8 Structures / Unions
Structure basics
Pointers to Structures
Nested Structures
Union basics
Pointers to Unions
9 PIC Specific C
Inputs and Outputs
Mixing C and Assembler
A/D Conversion
Data Communications
PWM
LCD Driving
Interrupts
Where next and other informationIntroduction Pic CG
Be Introduction
Why use C?
The C lananage was developed at the Bell Labs in the late 60’s by
Dennis Ritchie and Brian Kernighan. One of the first platforms for
implementation was the PDP-11 running under a UNIX environment.
Since its introduction, it has evolved and been standardised throughout
the computing industry as an established development language. The
PC has become a cost effective development platform using C++ or
other favoured versions of the ANSII standard.
C is a portable language intended to have minimal modification when
transferring programs from one computer to another. This is fine when
working with PC’s and mainframes, but Microcontrollers and
Microprocessors are a different breed. The main program flow will
basically remain unchanged, but the various setup and port / peripheral
control will be micro specific. An example of this is that the port
direction registers on a PIC are set 1=Input 0=Output, whereas the H8
is O=Input and 1=Output.
The use of C in Microcontroller applications has been brought about by
manufacturers providing larger program and ram memory areas in
addition to faster operating speeds.
An example quoted to me - as a non believer - was: to create a
stopclock function would take 2/3 days in C or 2 weeks in assembler.
‘Ah’ | hear you say as you rush to buy a C compiler - why do we bother
to write in assembler? It comes down to code efficiency - a program
written in assembler is typically 80% the size of a C version. Fine on the
larger program memory sized devices but not so efficient on smaller
devices. You pay the money and take your PIC!!
es eePC Based versus PIC Based Program
Development
Engineers starting development on PC based products have the luxuary
of basic hardware pre-wired i.e. keyboard, processor, memory, |/O,
printer and visual display (screen). The product development then
comes down to writing the software and debugging the errrrrrus.
Those embarking on a PIC based design have to create all the interface
to the outside world in the form of input and output hardware. A PC
programmer could write the message “Hello world” and after
compiling, have the message displayed on the screen. The PIC
programmer would have to build an RS232 interface, set up the comm
port within the PIC and attach the development board to a comm port
on a PC to enable the message to be viewed.
‘Why bother’ | hear you say (and so did 1) - it comes down to portability
of the end product. If we could get the whole of a PC in a 40 pin DIL
package (including monitor and keyboard) we would use it, but as
today’s miniaturisation does not reach these limits. we will continue to
use microcontrollers like the PIC for low cost and portable applications.
The development tools for PIC based designs offer the developer
basically the same facilities as the PC based development with the
exception of the graphics libraries.
PRODUCT DEVELOPMENT
Product development is a combination of luck and experience. Some of
the simplest tasks can take a long time to develop and perfect in
proportion to the overall product - so be warned where tight timescales
are involved.
To design a product one needs: time - peace and quiet - a logical mind
and most important of all a full understanding of the requirements.
| find the easiest way to begin any development ts to start with a clean
sheet of paper together with the specification or idea.Introduction Pic Cc
Start by drawing out a number of possible solutions and examine each
to try to find the simplest and most reliable option. Don’t discard the
other ideas at this stage as there are possibly some good thoughts
there.
Draw out a flow chart, block diagram, I/O connection plan or any
suitable drawing to get started.
Build up a prototype board or hardware mimic board with all the /O
configured. Don’t forget i/o pins can be swapped to make board layout
easier at a later date - usually with minimal modification to the software.
Then start writing the code - in testable blocks - and gradually build up
your program. This saves trying to debug 2000 lines of code in one go!
If this is your first project - THEN KEEP IT SIMPLE - try out just
switching a LED or two on and off from push buttons to get familiar with
the instructions, assembly technique and debugging before attempting
a mammoth project.
Build up the program in simple stages - testing as you go. Rework your
flowchart to keep it up to date.
THE IDEA
An idea is born - maybe by yourself in true EUREKA style or by
someone else having a need for a product - the basic concept is the
same.
Before the design process starts, the basic terminology needs to be
understood - like learning a new language. So in the case of
Microcontroller designs based on the PIC, the PIC language
(instruction set, terms and development kit) needs to be thoroughly
understood before the design can commence.
Now let's get started with the general terms, some facts about the PIC
and the difference between Microprocessor and Microcontroller based
systems.Introduction
Terminology
Let's start with some basic terminology used.
Microcontroller A lump of plastic, metal and purified sand which,
without any software, does nothing When software controls a
microcontroller, it has almost unlimited applications.
VO Aconnection pin to the outside world which can be configured as
input or output. I/O is needed in most cases to allow the microcontroller
to communicate, control or read information.
Software The information that the Microcontroller needs to operate or
tun. This needs to be free of bugs and errors for a successful application
or product. Software can be written in a variety of languages such as
C, Pascal or Assembler (one level up from writing your software in
binary).
Hardware The Microcontroller, memory, interlace components,
power supplies, signal conditioning circuits and all the components -
connected to it to make it work and interface to the outside world.
Another way of looking at (especially when it does not work) is that you
can kick hardware.
Simulator The MPLAB development environment has its own inbuilt
simulator which allows access to some of the internal operation of the
microcontroller. This is a good way of testing your designs if you know
when events occur. If an event occurs ‘somewhere about there’, you
might find the simulator restrictive. Full trace, step and debug facilities
are, however, available. Another product for 16C5x development is the
SIM ICE - a hardware simulator offering some of the ICE features but at
a fraction of the cost.
In Circuit Emulator (ICEPIC or PIC MASTER) - a very useful piece of
equipment connected between your PC and the socket where the
Microcontroller will reside. It enables the software to be run on the PC
but looks like a Microcontroller at the circuit board end. The ICE allows
you to step through a program, watch what happens within the micro
and how it communicates with the outside world.
a esrrr
Introduction PIC Gees
Programmer A unit to enable the program to be loaded into the
microcontrollers memory which allows it to run without the aid of an
ICE. They come in all shapes and sizes and costs vary. Both the
PICSTART PLUS and PROMATE II from Microchip connect to the serial
port.
Source File A program written in a language the assembler and you
understand. The source file has to be processed before the
Microcontroller will understand it.
Assembler / Compiler A software package which converts the Source
file into an Object file. Error checking is built in, a heavily used feature
in debugging a program as errors are flagged up during the assembly
process. MPASIM is the latest assembler from Microchip handling all the
PIC family. C Compilers covered in this book are the CCS and HI
TECH.
Object File This is a file produced by the Assembler / Compiler and
is in a form which the programmer, simulator or ICE understands to
enable it to perform its function. File extension is .OBJ or .HEX
depending on the assembler directive.
List File This is a file created by the Assembler /Compiler and contains
all the instructions from the Source file together with their hexadecimal
values alongside and comments you have written. This is the most
useful file to examine when trying to debug the program as you have a
greater chance of following what is happening within the software than
the Source file listing. The file extension is .LST
Other Files The error file (ERR) contains a list of errors but does not
give any indication as to their origin. The .COD file is used by the
emulator.
Bugs Errors created free of charge by you. These range from
simpel typin errus to incorrect use of the software language syntax
errors. Most of these bugs will be found by the compiler and shown up
in a .LST file, others will have to be sought and corrected by trial and
error.Pic Cc Introduction
Microprocessor
A microprocessor or digital computer is made up of three basic sections:
CPU, I/O and Memory - with the addition of some support circuitry.
Each section can vary in complexity from the basic to all bells and
whistles.
fesieeeceeeees - h
‘DATA
vo N ES Pere eevee ene eS
pigraL |! a ") Memory |
1 PWM | RAM
} ANALOG i) \ EPROM
S232 Se | EEPROM
| C /"appREss | ADDRESS)
one! eee
| aE : | cpu a ont
f { 4,8, 16 BIT |
|
i |
pL |
fa lnetiy Coeur
WATCHDOG |
TIMER OSCILLATOR
TYPICAL MICROPROCESSOR SYSTEM
Taking each one in turn:-
Input/output (I/O) can comprise digital, analogue and special functions
and is the section which communicates with the outside world.
The central processor unit (CPU) is the heart of the system and can
work in 4, 8 or 16 bit data formats to perform the calculations and data
manipulation.
The memory can be RAM, ROM, EPROM, EEPROM or any
combination of these and is used to store the program and data.rr
Introd Pic Cc
An oscillator is required to drive the microprocessor. Its function is to
clock data and instructions into the CPU, compute the results and then
output the information. The oscillator can be made from discrete
components or be a ready made module.
Other circuitry found associated with the microprocessor are the watch
dog timer - to help prevent system latchup, buffering for address and
data busses to allow a number of chips to be connected together
without deteriorating the logic levels and decode logic for address and
1/0 to select one of a number of circuits connected on the same bus.
Itis normal to refer to a Microprocessor as a product which is mainly the
CPU area of the system. The I/O and memory would be formed from
separate chips and require a Data Bus, Address Bus and Address
Decoding to enable correct operation.
Microcontrollers
The PIC, on the other hand, is a Microcontroller and has all the CPU,
memory, oscillator, watchdog and I/O incorporated within the same chip.
This saves space, design time and external peripheral timing and
compatibility problems, but in some circumstances can limit the design
to a set memory size and I/O capabilities.
The PIC family of microcontrollers offers a wide range of I/O, memory
and special functions to meet most requirements of the development
engineer.
You will find many general books on library shelves exploring the design
of microcontrollers, microprocessors and computers, so the subject will
not be expanded or duplicated here other than to explain the basic
differences.
Why use the PIC?
Code Efficiency The PIC is an 8 bit Microcontroller based on the
Harvard architecture - which means there are separate internal busses
for memory and data. The throughput rate is therefore increased due to
simultaneous access to both data and program memory. Conventional
microcontrollers tend to have one internal bus handling both data andIntroduction
program. This slows operation down by at least a factor of 2 when
compared to the PIC.
Safety All the instructions fit into a 12 or 14 bit program memory
word. There is no likelihood of the software jumping into the DATA section
of a program and trying to execute DATA as instructions. This can occur
in a non Harvard architecture microcontroller using 8-bit busses.
Instruction Set —_ There are 33 instructions you have to learn in order
to write software for the 16C5x family and 35 for the 16Cxx devices. All
the instructions used by the PIC are based on registers and are 12 bits
in length for the 16C5x family and 14 bits wide for the I6Cxx family. Each
instruction, with the exception of CALL, GOTO or bit testing instructions
(BTFSS, INCFSZ), executes in one cycle.
Speed The PIC has an internal divide by 4 connected between
the oscillator and the internal clock bus. This makes instruction time
easy to calculate, especially if you use a 4 MHz crystal. Each instruction
cycle then works out at 1 uS. The PIC is a very fast micro to work with
e.g. a 20MHz crystal steps through a program at 5 million instructions
per second! - almost twice the speed of a 386SX 33!
Static Operation The PIC is a fully static microprocessor; in other
words, if you stop the clock, all the register contents are maintained. In
practice you would not actually do this, you would place the PIC into a
Sleep mode - this stops the clock and sets up various flags within the
PIC to allow you to know what state it was in before the Sleep. In Sleep,
the PIC takes only its standby current which can be less the 1 uA.
Drive Capability The PIC has a high output drive capability and can
directly drive LEDs and triacs etc. Any I/O pin can sink 25mA, or 100mA
for the whole device.
Options A range of speed, temperature, package, I/O lines, timer
functions, serial comms, A/D and memory sizes is available from the
PIC family to suit virtually all your requirements.
Versatility The PIC is a versatile micro and in volume is a low
cost solution to replace even a few logic gates; especially where space
is at a premiumIntroduction
(syrereydueg
suod
sod O/|
IDOL
Xo
1a1un09/49019,
aneea sO aH
Sey SNivis
usd
spy
yeupuy
appy WIVES
uonzieue9
Sulu
yno-umoa
jonueD
B 8poseg
uononnsul
z080
19s0
¥TOW
spy 10811
sueisibou 2)l4
wv
sng Beg
UyOVLS
3
HHOVLS
felunog WeIBoig
Gey uowonysuy
sng
wesBod
AowoW
weiboid
WOudsa
BASIC PIC BLOCK DIAGRAMPic G _ Introduction
Security The PIC has a code protection facility which Is one of the
best in the industry. Once the protection bit has been programmed, the
contents of the program memory cannot be read out in a way that the
program code can be reconstructed.
Development The PIC is available in windowed form for development
and OTP (one time programmable) for production. The tools for
development are readily available and are very affordable even for the
home enthusiast
Trying and Testing Code
Getting to grips with C can be a daunting task and the initial outlay for a
C compiler, In Circuit Emulator and necessary hardware for the PIC can
be prohibitive at the evaluation stage of a project. The C compiler
supplied on this disk was obtained from the Internet and is included as
a test bed for code learning. Basic code examples and functions can be
tried, tested and viewed before delving into PIC specific C compilers
which handle I/O etc.
C Coding Standards
Program writing is like building a house - if the foundations are firm, the rest
of the code will stack up. If the foundations are weak, the code will fall over
at some point or other. The following recommendations were taken from
a C++ Standards document and have been adapted for the PIC.
Names - make them fit their function
Names are the heart of programming so make a name appropriate to its
function and what it’s used for in the program.
Use mixed case names to improve the readability
ErrorCheck is easier than ERRORCHECK
Prefix names with a lowercase letter of their type, again to improve
readability:-
g Global gLog;
t Reference rStatus();
s Static sValueIn;Introduction PIc
Braces
Braces or curly brackets can be used in the traditional UNIX way
if (condition) {
or the preferred method
if (condition)
Tabs and Indentation
Use spaces in place of tabs as the normal tab setting of 8 soon uses up
the page width. Indent text only as needed to make the software
readable. Also, tabs set in one editor may not be the same settings in
another - make the code portable.
Line Length
Keep line lengths to 78 characters for compatibility between monitors
and printers.
Else If Formatting
Include an extra Else statement to catch any conditions not covered by
the preceding if's
if (condition)
{
,
else if (condition)
{
,
else
{
seeees+ /* catches anything else not covered above
+Introduction
Condition Format
Where the compiller allows it, always put the constant on the left hand
side of an equality / inequality comparison. If one = is omitted, the
compiler will find the error for you. The value is also placed in a
prominent place.
if (6== ErrorNum)
Initialise All Variables
Set all variables to a known values to prevent ‘floating or random
conditions’
Comments
Comments create the other half of the story you are writing. You know
how your program operates today but in two weeks or two years will you
remember, or could someone else follow your program as it stands
today?
Use comments to mark areas where further work needs to be done,
errors to be debugged or future enhancements to the product.
Basics
All computer programs have a start. The start point in Microcontrollers
is the reset vector. The 14 bit core (PIC16Cxx family) reset at 00h, the
12 bit core (PIC1GC5x and 12C50x) reset at the highest point in
memory - 1FFh, 3FFh, 7FFh.
The finish point would be where the program stops if run only once e.g.
a routine to set up a baud rate for communications. Other programs will
loop back towards the start point such as traffic light control. One of the
most widely used first programming examples in high level languages
like Basic or C ts printing ‘Hello World’ on the computer screen.
Using C and a PC is straightforward as the screen, keyboard and
processor are all interconnected. The basic hooks need to be placed in
the program to link the program to the peripherals. When developing a
program for the PIC or any microprocessor / microcontroller system, you
need not only the software hooks but also the physical hardware to
connect the micro to the outside world. Such a system is shown below.Introduction Pic Cc
COMMS TARGET BOARD t—vo—
Using such a layout enables basic I/O and comms to be evaluated,
tested and debugged. The use of the ICE, though not essential, speeds
up the development process many fold and so reduces the overall
development costs and engineer’s headaches. The initial investment
may appear excessive when facing the start of a project, but time saved
in developing and debugging is soon outstripped.
The hardware needed to evaluate a design can be a custom made PCB,
protoboard or an off the shelf development board such as our PIC
Millennium Board (someone had to do one!) The Millennium board
contains all the basic hardware to enable commencement of most
designs while keeping the initial outlay to a minimum.
Assemble the following hardware in whichever format you prefer. You
WILL need a PIC programmer such as the PICSTART Plus as a minimal
outlay in addition to the C compiler.
A simple program | use when teaching engineers about the PIC ts the
‘Press button - turn on LED’. Start with a simple code example - not
2000 lines of code!
In Assembler this would be :-
main btfss porta,switch; test for switch closure
goto main + loop until pressed
a eeeRR
Pic Cc
bsf porthb, led 7 turn
btfsc porta, switch; test
goto pl ; loop
bef portb,led ; turn
goto main : loop
pt
In C this converts to
main()
{
set_tris_b(0x00);
while(true)
{
if (input (PIN_A0))
output_high(PIN_BO);
else
output_low(PIN_BO);
Introduction
on led
for switch open
until released
off led
back to start
// set port b as outputs
// test for switch closure
// if closed turn on led
// if open turn off led
When assembled, the code looks like this:-
main()
if
set_tris_b(0x00);
0007
0008
while(true)
{
if (input (PIN_AO))
0009
000A
output_high(PIN_BO);
000B
else
o00c
output_low(PIN_BO);
000D
y
000E
>
MOVLW 00
TRIS 6
BIFSS 05,0
GOTO 00D
BSF 06,0
GOTO 00
BCF 06,0
GOTO 009
See ee 9 eee eeIntroduction
As you can see, the compiled version takes more words in memory - 14
in C as opposed to 9 in Assembler. This is not a fair example on code
but as programs get larger, the more efficient C becomes in code usage.Pic Cc
NOTES
Bluebird ElectronicsC Fundamentals
Pic:
- C Fundamentals
his chapter presents some of the key aspects of the C programming
language. A quick overview of each of these aspects will be given.
The goal is to give you a basic knowledge of C so that you can
understand the examples in the following chapters.
The topics discussed are:
Program structure
Components of a C program
#pragma
Main
#include directive
printf statement
Variables
Constants
Comments
Functions
C keywords1.1 The Structure of C Programs
All C programs contain preprocessor directives, declarations,
definitions, expressions, statements and functions.
Preprocessor directive
A preprocessor directive is a command to the C preprocessor (which is
automatically invoked as the first step in compiling a program). The two
most common preprocessor directives are the #define directive, which
substitutes text for the specified identifier, and the #include directive,
which includes the text of an external file into a program.
Declaration
A declaration establishes the names and attributes of variables,
functions and types used in the program. Global variables are declared
outside functions and are visible from the end of the declaration to the
end of the file. A local variable is declared inside a function and 's visible
from the end of the declaration to the end of the function.
Definition
A definition establishes the contents of a variable or function. A
definition also allocates the storage needed for variables and functions.
Expression
An expression is a combination of operators and operands that yields a
single value.
Statement
Statements control the flow or order of program execution in a C
program.Fundamentals Pic c
Function
A function 1s a collection of declarations, definitions, expressions and
statements that performs a specific task. Braces enclose the body of a
function. Functions may not be nested in C.
Main Function
All C programs must contain a function named main where program
execution begins. The braces that enclose the main function define the
begining and ending point of the program.
Example: General C program structure
#include /* preprocessor directive */
/* include standard C header file
*/
#define PI 3.142 /* define symbolic constant */
float area; /* global declaration */
main()
{ /* beginning of main function */
/* and program */
int radius_squared; /* local declaration */
int radius = 3; /* declaration and initialisation */
radius_squared = square(radius); /* pass a value
to a function */
area = PI * radius_squared; /* assignment statment */
printf(“Area is %6.4£ square units\n”,area) ;
} /* end of main function & program */
square (r) /* function head */
{
int r_squared; /* declarations here are known */
/* only to square */
a 9 aePic Cc C Fundamentals
r_squared = r * x;
return(r_squared) ; /* return value to calling */
/* statement */
}
1.2 | Components of a C program
All C programs contain certain essential components such as
statements and functions. Statements are the parts of the program that
actually perform operations. All C programs contain one or more
functions. Functions are subroutines, each of which contains one or
more statements and can be called by other parts of the program.
When writing programs, indentations, blank lines and comments
Improve the readability - not only for yourself at a later date, but also for
those who bravely follow on. The following example shows some of the
required parts of a C program.
#include
/* My 1st C program */
main()
{
printf (“Hello world!”);
+
The statement #include tells the compiler to include the
source code from the file ‘stdio.h’ into the program.
The extension .h stands for header file. A header file contains
information about standard functions that are used in the program. The
header file stdio.h which Is called the STandarD Input and Output
header file, contains most of the input and output functions. It is
necessary to use only the include files that pertain to the standard
library functions in your program.
/* My first C program */ is a comment in C. All comments are
preceded by a /* and end with a */. Comments are ignored by the
compiler and therefore do not affect the speed or length of the compiled
code.rr
C Fundamentals _ Pic Cc :
All C programs must have a main() function. This is the entry point into
the program. All functions have the same format which ts:
Funct ionName ()
{
code
+
Statements within a function are executed sequentially, beginning with
the open curly brace and ending with the closed curly brace.
The curly braces { and } show the beginning and end of blocks of code
inc.
Finally, the statement print£(”Hello world!”); represents a typical
C statement. Almost all C statements end with a semicolon (;). The
end-of-line character is not recognised by C as a line terminator.
Therefore, there are no constraints on the position of statements within
a line or the number of statements on a line.
All lines of code have a semi-colon (;) at the end to inform the compiler
it has reached the end of the statement. Failure to include this will flag
an error in the NEXT line. The exception to this is the ig command
where the ; needs to be at the end of the next line e.g.
if (ThisIsTrue)
DoThisFunction ;
1.3 #pragma
The pragma command instructs the compiler to perform a particular
action at the compile time such as specifying the PIC being used
#pragma device PIC16c54
1.4 main()
Every program must have a main function which can appear only once.
No parameters can be placed in the (_) brackets which follow. As main
SsC Fundamentals
is classed as a function, all code which follows must be placed within a
pair of braces ¢ } or curly brackets.
main()
{
body of program
}
1.5 #include
The header file, (denoted by a .h extension) contains information about
library functions such as what argument(s) the function accepts and
what argument(s) the function returns or the location of PIC registers for
a specific PIC.
#include <16C54.h>
This information is used by the compiler to link all the hardware specifics
and source programs together. In the above include, the register for
portb would be assigned 06h and the trisb register 86h. In assembler
sysntax, this would be:-
portb equ 06h } port register
trisb equ 86h i port direction register
An example of including header files using an #include In a C program
Is:
#include // standard input and output routines
#include // console input and output routines
main()
{
printf(“Microchip is “);
while( !kbhit());
printf (“#11”);C Fundamentals Piao:
The function printf () is found in the header file stdio.h while the
function kbhit() is found in the header file conio.h. Both these
header files must be used in this program so the compiler has essential
information about the functions you are using.
Angled brackets
#include
tell the preprocessor to look in another directory for the file while the
quote marks
#include “thatfile.h”
tell the preprocessor to look in the current directory.
You have probably noticed that the #include directive does not have a
semicolon at the end. The reason for this 1s that the #include directive
is not a C keyword, but instead is an instruction to the compiler.
The whole of the include file is inserted into the source file at the
compile stage.
1.6 printf Function
The print¢é function is a standard library function that is contained in
the header file ‘stdio.h’. print£ allows the programmer to print
information to the screen. The general format for a print £() statement
is:
printf(“control_string”, argument_list);
control_string is a string with double quotes at each end. Inside this
string any combination of letters, numbers and symbols can be used.
Special symbols called format specifiers are denoted with a %. The
control_string must always be present in the print£() function.
argument_list may not be required if there are no format specifiers in
the format string. The argument_1ist can be composed of constants
and variables. The following two examples show print£() statementsoe FIC &
using a constant and then a variable.
printf(“Hello world!”);
print£(“Microchip is #%d!",1);
The format specifier (sd) is dependent on the type of data being
displayed. The table below shows all of the format specifiers in C and
the data types they affect.
Format Specifiers printf ()
%c single character
uc unsigned character
%s string
%d signed decimal integer
%£ floating point (decimal notation ~ must include
decimal point)
%e floating point (exponential or scientific notation)
%g floating point (%f or %e, whichever is shorter -
general format)
%u unsigned decimal integer
%x unsigned hexadecimal integer
%p pointer
%0 unsigned octal integer
1 prefix used with %d, %u, %x, %o to specify long
integer
NOTE a 0 (zero) following a % character within a format string forces
leading zeros to be printed out. The number following specifies the
width of the printed field.
print£("The Hex of decimal 12 is %02x\n",12);
would print out
The Hex of decimal 12 is 0c
Escape Sequences
\n newline \a audible bell
2 eeFundamentals : Pic'c
\t horizontal tab \b backspace
\r carriage return \O null character
\f formfeed \v vertical tab
\' single quote \xhhh insert HEX code hhh
\" double quote
\\ backslash
%% percent sign
\? question mark
The format specification can also be shown as
%[flags][width][.precision] so in a previous example the line:-
printf(“Area is %6.4f square units\n”,area) ;
will print out the value area in a field width of 6 with a precision of 4
decimal places.
1.7.‘ Variables
A variable is a name for a specific memory location. This memory
location can hold various values depending on how the variable was
declared. In C, all variables must be declared before they are used. A
variables declaration tells the compiler what type of variable is being
used. All variable declarations are statements in C and-therefore must
be terminated with a semicolon.
The five basic data types that C supports are char, int, float,
double, void. The general format for declaring a variable Is:
type variable_name;
An example of declaring a variable is char ch;. The compiler would
interpret this statement as the variable ch is declared as a char (8-bit
unsigned integer).
1.8 Constants
A constant is a fixed value which cannot be changed by the program.
For example, 25 is a constant. Integer constants are specified without
[as ee“pic Cc ¢ Fundamentals
any fractional components, such as -100 or 40. Floating point constants
require the decimal point followed by the number's fractional
component. The number 456.75 is a floating point constant. Character
constants are enclosed between single quotes such as ‘A’ or ‘&’.
When the compiler encounters a constant in your program, it must
decide what type of constant it is. The C compiler will, by default, fit the
constant into the smallest compatible data type that will hold it. So 15
is an int, 64000 is an unsigned and 105020 is a long.
A constant is declared using the #define statement.
#define