You are on page 1of 260

©2007 Microchip Technology Incorporated. All Rights Reserved.

4079 EPC Slide 1
4079 EPC
Embedded Programming in C –
General Overview
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 2
Class Objective
When you finish this module you will know:
− A little bit of the “History of C”
− Where C fits in the programming
landscape
− What to expect from C
− What not to expect from C
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 3
Once Upon a Time ...
1969 Ken Thomson (Bell Laboratories)
createdthe first versionof UNIX in
Assembler => not portable!!!
1970 Ken Thomson developedB on a
PDP/7 asa successor to BCP; B isa
typeless language, there are only machine
words
1974 Dennis M. Ritchie developedC from
B, first implementationon a PDP 11
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 4
And Today?
Meanwhile“C“ evolvedintoan operating
system independant language
“C“ is virtual availableon all existing
platforms, fromPCs to Mainframes, on
UNIX and evenon Windows
During thetime many dialects emerged,
which made it necessary to standardize
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 5
Standardization
In 1988 theANSI-CommiteeX3J 11
publishedthisstandardfor “C“, today
calledANSI C
Modern compilersshouldbeANSI
compliant
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 6
Standardization
TheBiblefor C programmersis:
Brian W. KernighanandDennis M.
Ritchie
“TheC ProgrammingLanguage“
PrenticeHall Software Series
ISBN 0-13-110362-8
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 7
Standardization
Question:
“Arethereanygood books
about C?“
Answer:
Yes, one!
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 8
Standardization
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 9
General Remarks on “ C”
C isnot reallya High Level Language, it
shouldbeconsideredsomewherebetween
assembler and anHLL likePascal
C combinestwo uniquefeatures:
− Goodadaptationto a processor architecture
− Highportability
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 10
The End of a Gossip !!!
C compiler generatesvery efficient code
− Thanks to an optimizer
Most problemscanbe solved withC insteadof
assembler
C isa simpler programming language
− Development time and time to market are
reduced
C canbe portedtoa different processor
Program readabilityisincreased
− Done right, the program is self documenting
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 11
“ C” is First Choice
In computing, there isa strong tendency
towards HLLsor even further, Object
Oriented Languages likeJ AVA
On µControllers, the trend is away from
assembler towardsa HLL with hardware
related features
C, bynature, is very hardware friendly
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 12
Features of “ C”
C isa comparableprimitive language, and
becauseof that, not so user friendly
C only knows four datatypes:
char, int, float anddouble
These basic datatypes can bemodified
using qualifiers like signed, double, long
etc.
Complex datatypes may be created by
combining basic datatypesto vectors like
strings, arrays or structuresand unions
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 13
Features of “ C”
C knowsall necessary control structuresto
modify the program flow accordingto the needs
The program flow control structures are quite
simple:
a simple decision(if-else), a multiway decision
(switch-case), a loop(for), a pre-test loop(while)
and a post-test loop(do-while)
Functions may be usedto specify user defined
necessitiesor to group statements
Input/Output is not part of C, I/O will be realized
through(standard) librariesor user specified
functions
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 14
Features of “ C”
Parameters are forwardedto functions asa copy;
a function can not modify theoriginal value
If the forwarded parameter isan address, the
funtion can easilymodify the value the address is
pointingto
Pointers are quite powerful and if you have
become familiar withC youwill learnto love
them
Converting data from one type into another is
nearly unlimited, which providesa lot of
flexibility, but also may lead into problemsand
traps
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 15
Uses of C
C is popular and isstill gaining popularity,
especially when it comesto hardware
related programming, C is asflexible as
assembler but offers HLL features
C isbest suitedto write OperatingSystems
(it was designed for that)
If you writeC programsfor a PIC
®
MCU,
you are writingan OperatingSystem !!!
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 16
Uses of C
Today we hear about “embedded UNIX”,
RTOS and Digital Signal Processing
C belongsto UNIX and UNIX cannot exist
without C
“Numerical Recipesin C” is a good tool to
solve problems likeFFT, FIR etc#
FREE RTOS is writtenin C
Plain readingof documentation makes it
necessaryto have someC knowledge
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 17
Uses of C
C should always be used if the requirements
include high portability
No other language provides flexible
portability
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 18
Summary
Very good adaptability to processor
architectures
Highly portable code
Efficient code
Simple programming
Very well suitedto programming
µControllers
Maintainingtoday‘sinvestment for
tomorrow!!!
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 19
4079 EPC
Embedded Programming in C
Introduction
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 20
Class Objective
When you finish this module you will:
− Generate your first program
− Gain knowledge of our next module
− Handle your project source code with
MPLAB
®
IDE
− Debug your source code with MPLAB IDE
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 21
THE Example !!!
/* Example 001 */
#include <stdio.h>
main()
{
printf ("hello, world\n");
}
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 22
Explanations About the
Program
A C program consistsof functionsand
usesvariables to store values used
during computation
Functions syntax is as follows:
− MyFunction()
Anyfunction name can be used, but
there must always bea main()
main() usuallycalls other user
createdfunctions or libraries
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 23
Explanations
The statementsof a function are enclosedin
braces{}
#include <stdio.h>
tells the compiler to include information
about the standard input/output library; the
“included” file may be treated as if its
content is present in this place
Compilersbrowselinearlythroughall files
main()
is definedto bea function that expectsno
argument, indicated by the emptylist () or
(void)
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 24
Explanations
printf ("hello, world\n");
This function is called with itsnameand a
character string asan argument
\n
is theC notation for the newline character
printf ("hello, world
");
If you tryto insert a new linethisway, the
compiler will producean error message
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 25
Explanations
printf ("hello, ");
printf ("world");
printf ("\n");
This groupof statementswill produce the
same output as the single statement version
C doesn't knowa row structure like
assembler, except in stringsand#defines
Statements must be terminated witha ';'
\n
isan escape sequence representinga single
character only, not then but LF (0x0A)
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 26
Explanations
The are more combinations as
\t for tab,
\b for backspace,
\" for thedouble quoteand
\\ for the backslash.
More about escape sequences later
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 27
Remark
Usuallya µController, asa standalone
application does not communicate with the
world using printf()
printf() requiresan implementationof a
low level function putc(), whichcontrols
thereal hardware, likean USART
If youdo not usea terminal hookedto an
USART, bad luck
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 28
Remark
But MPLAB
®
IDE providesa feature,
where we may emulatean USART routing
the output to an output windowin MPLAB
IDE
It is worthwhileto know the featuresof
printf(), because you may use it asan
additional debugging possibility
Please be patient, moreto come later
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 29
A More Complex Example
/*Example 002 */
/*conversion table Fahrenheit-Celsius
for fahr = 0, 20, ..., 300 */
#include <stdio.h>
main()
{
int lower,upper,step;
float fahr,celsius;
lower = 0; /* lower limit of temperature table */
upper = 300; /* upper limit */
step = 20; /* Sstep size */
fahr = lower;
while (fahr <= upper) {
celsius = (5.0/9.0) * (fahr-32.0);
printf ("%4.0f %6.1f\n",fahr,celsius);
fahr = fahr + step;
}
}
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 30
Explanations About the
Program
fahr = lower;
assigns theright sideof "=" to the left
side. In addition the int is convertedto
float before the operation is performed
while(fahr <= upper)
{
}
Thetest will be done after the
conversionand the body between"{"
and "}" will be repeated as long as the
condition is true
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 31
Explanations
/* Example 002 */
Text between/* and */ is ignored by the
compiler, this can be usedto insert
commentsin your source code; comments
may appear anywherea blank or tab or
newline can(white space)
The compiler browseslinearlythrough the
program; thecompiler needsvariables to be
declared before they are used
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 32
Explanations
A declaration announces the propertiesof
variables; it consistsof a type nameand a list of
variables, such as
int lower,upper,step;
float fahr,celsius;
printf ("%4.0f %6.1f\n",fahr,celsius);
printf uses three arguments, first a string.
In the string the% indicatesto use the next
argument, fahr, andformat it followed bya
spaceand another indicator requiring
another argument, celsius
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 33
More about printf()
%d print as decimal integer
%6dprint as decimal integer,
at least 6 characters wide
%f print as floatingpoint
%6f print as floatingpoint,
at least 6 characters wide
%.2fprint as floatingpoint,
2 characters after decimal point
%6.2f print as floatingpoint,
at least 6 wideand 2 after decimal point
Among others, printf also recognizes%o for
octal, %x for hexadecimal, %c for character, %s
for character string, and %% for % itself
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 34
Same Result – Different Approach
/* Example 003 */
/* print table Fahrenheit-Celsius
for fahr = 0, 20, ..., 300 */
#include <stdio.h>
main()
{
int fahr;
for(fahr = 0; fahr <= 300; fahr = fahr +20)
{
printf("%4.0f
%6.1f\n",fahr,((5.0/9.0)*(fahr-32.0)));
}
}
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 35
Explanations About the
Program
This produces the same answers, but it
looksdifferent
Most of thevariables have been
eliminated, onlyfahr remains, and isan
int.
The lower and upper limits and the step
size appear only as constantsin the for
statement, a new construction
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 36
Explanations
The expression that computes the
Celsius temperature appears as the third
argument of printf insteadof asa
separate assignment statement
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 37
Remark
Even though the program became quite
short, if you intendto do this witha
µController, you should havein mind, that
you may want to step through your program,
to verify what is goingon
If you don't have thevariable "celsius"
anymore, you cannot observe the calculation
in a watch window!
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 38
Same Result – Another Approach
/* Example 004 */
/* print table Fahrenheit-Celsius /*
#include <stdio.h>
#define LOWER 0
#define UPPER 300
#define STEP 20
main()
{
int fahr;
for(fahr = LOWER; fahr <= UPPER;
fahr = fahr + STEP)
{
printf("%4.0f %6.1f\n"
,fahr,((5.0/9.0)*(fahr-32.0)));
}
}
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 39
Explanations About the
Program
Using constant values like300 and 20 (or 0x5A
and 0b11110000) is not best practice because they
are hardto changein a systematicway
One better way isto give them“sounding“ names
We can achieve that by using the preprocessor
#define construction
A #define line definesa symbolic name or
symbolic constant to bea particular stringof
characters:
#define name replacement_text
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 40
Explanations About the
Program
The quantitiesLOWER, UPPER and STEP
are symbolic constants, not variables, so
theydo not appear in declarations
Symbolic constant names are conventionally
writtenin UPPER_CASE so they can be
readily distinguished from lower or mixed
casevariable names
Notice that there isno semicolonat theend
of a #define line
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 41
Coding Conventions
The disciplined programmer followsa
coupleof rules, called coding
conventions
− Usea structured approach
− Don't overestimate your own genius
− KeepIt Simple, Stupid
− If you are killedin an accident, your company
may suffer
− If you are promoted, think about your
successor, be generous
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 42
uglyform.c
/* 01 */ #include <stdio.h>
/* 02 */ int main() /* Main program starts
/* 03 */ here */{printf("Good form
");printf("can aid in ");
/* 04 */ printf("understanding a program.\n")
/* 05 */ ;printf("And bad form ");printf("can
make a program ");
/* 06 */ printf("unreadable.\n");return 0;}
/* 07 */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 43
goodform.c
/*01*/ #include <stdio.h>
/*02*/
/*03*/ int main() /* Main program starts here */
/*04*/ {
/*05*/ printf("Good form ");
/*06*/ printf ("can aid in ");
/*07*/ printf ("understanding a program.\n");
/*08*/ printf("And bad form ");
/*09*/ printf ("can make a program ");
/*10*/ printf ("unreadable.\n");
/*11*/
/*12*/ return 0;
/*13*/
/*14*/ } /* end main() */
/*15*/
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 44
style01.c
...
for (index = 0 ; index < 7 ; index = index + 1) {
printf("The value of ");
printf("index is %d\n", index);
if (count < 5) {
printf("The value of count is %d ", count);
printf(" this is less than 5\n");
} else {
loop_count = 0;
do {
printf("The value of loop_count is %d\n", loop_count);
loop_count = loop_count + 1;
} while (loop_count < 3);
printf("The value of count is %d ", count);
printf(" this is not less than 5\n");
}
}
...
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 45
style02.c
...
for (index = 0 ; index < 7 ; index = index + 1)
{
printf("The value of ");
printf("index is %d\n", index);
if (count < 5)
{
printf("The value of count is %d ", count);
printf(" this is less than 5\n");
}
else
{
loop_count = 0;
do
{
printf("The value of loop_count is %d\n", loop_count);
loop_count = loop_count + 1;
} while (loop_count < 3);
printf("The value of count is %d ", count);
printf(" this is not less than 5\n");
}
}
...
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 46
Self Organization
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 47
Self Organization
How to organize your project and
yourself
− Scope rules
− Preprocessor Facilities
Guidelines
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 48
Scope Rules
Functions and variables need not all be
compiled at the same time
Source text may be kept in several files
Pre-compiledfiles may be loaded from
existing libraries or subdirectories
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 49
Scope Rules
Which raises some questions
− How to declare variables properly for
compilation?
− How to arrange declarations that all
pieces will be properly connected when
the program is loaded?
− How to organize declarationsso there is
only one copy?
− How to initialize external variables?
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 50
Scope Rules
Even though our examples usually are
toosmall to split intoseveral files, we
will do that for educational reasons
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 51
Scope Rules
The scope of a name is the part of a program
within which the name can be used
For an automatic variable declared at the
beginningof the function body, it is the
function body
The variable is function local!
Local variables with the same name in
different functions are unrelated
This also applies to function parameters
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 52
Scope Rules
The scope of an external, or global, variable
lastsfrom the point at which it was declared
to the end of the file
For example:
int varSystemState;
void initialize(void)
{ ... varSytemState = IDLE; ... };
void mainfunction(void) { ... };
void main(void)
{
initialize();
while(1)
{
mainfunction();
}
}
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 53
Scope Rules
If we place all codein a certain order in the
same file the compiler needs to know each
name before using it
The previous example may compile with no
errors
Nothing else is necessary to be declared
Typical for "assembler like" programming
May be suitable for very small programs
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 54
Scope Rules
Now let's rearrange our program:
void main(void)
{
initialize();
while(1)
{
mainfunction();
}
}
void initialize(void)
{ ... varSytemState = IDLE; ... };
void mainfunction(void)
{int varSystemState; ... };
Putting the rows in this order will cause
compiler errors
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 55
Scope Rules
When the compiler finds the name "main", it
is satisfied, because it wantsit that way
But when it finds "initialize" and
"mainfunction", it assumes these to return
integers (the default)
When it reaches the point of declaration, it
sees the return type "void" and complains,
that the function type has been redeclared!
A similar error messageoccurs whenthe
unknown variable "varSystemState", is
encountered
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 56
Scope Rules
Now let's split our programintoseveral
files:
/* file : main.c */
#include "initialize.h"
#include "mainfunction.h"
void main(void)
{
initialize();
while(1)
{
mainfunction();
}
}
/* file: initialize.h */
void initialize(void);
/* file: initialize.c */
#include "initialize.h"
extern int varSystemState;
void initialize(void)
{ ...
varSytemState = IDLE;
...
};
/* file: mainfunction.h */
void mainfunction(void);
/* file: mainfunction.c */
int varSystemState; /* global */
void mainfunction(void)
{ ... };
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 57
Scope Rules
Noweverythingshouldcompile
Because the C preprocessor is
"replacing" the "includes" and finds
them in proper order
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 58
The C preprocessor ?
The C preprocessor !
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 59
The C Preprocessor
A C program is translated in several
steps to become an executable
− The Preprocessor Step
− The Compilation Step
− The Linker Step
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 60
The C Preprocessor
The preprocessor analyzes everything starting
with "#"
The compiler translates the readable code text file
into an intermediate relocatable object code
The linker combines all the object code files to an
executable file
On "Windows" these file do have ".exe" as the
extension
For a µC, we use a "cross compiler" which
creates a ".hex" file to be programmed intothe µC
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 61
The C Preprocessor
The preprocesor knows a coupleof
instructions:
#include
#define
#undef
#if !defined or #ifndef
#elif (short for else if)
#endif
#error
#pragma
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 62
The C Preprocessor
#include "filename" or
#include <filename> includes the
content of a file as if it werethere
If filename is in quotations, the search
starts where the source program was
found
If filename is in "< >", search goes to
the "standard include path"
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 63
The C Preprocessor
C:\project
+-\common
| +-systemconstants.h
+-\libs
| +-adc.h
+-\myfiles
+--main.c
( #include <pic24xxx.h>
#include "initialize.h"
#include "mainfunction.h"
...)
+-initialize.h
+-initialize.c
( #include <pic24xxx.h>
#include "initialize.h"
#include "c:\project\common\systemconstants.h"
...)
+-mainfunction.h
+-mainfunction.c
( #include <pic24xxx.h>
#include "mainfunction.h"
#include "..\libs\adc.h"
..)
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 64
The C Preprocessor
A definition has the form:
#define name replacement_text
This is the simplest form of a macro
substitution; whenever the token
"name" is found it will be replaced by
"replacement_text"
The scope of #define is from thefirst
point of definition to the end of the file
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 65
The C Preprocessor
Someexamples:
#define forever while(1)
#define forever_too for(;;)
#define NOT_ACTIVE_LOW 1
#define ACTIVE_LOW 0
#define MICRO_SECONDS 1
#define THOUSEND_ 1000
#define MILLI_SECOND (THOUSEND * MICRO_SECONDS)
#define NOT_KEY PORTAbits.bit0
#define TEMPERATURE_SENSOR AD_CHNL_0
#define ON_OFF_LED LATBbits.bit1
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 66
The C Preprocessor
Macrosmaybedefinedwitharguments
In thiscasethereplacement text maybe
different fromcall to call
An example:
#define max(A,B)((A) > (B) ? (A) : (B))
It looks like a function, but the code
expands in-line for every usage
This may save calls in some cases, but may
require more code if used toooften
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 67
The C Preprocessor
Somemacro examples:
#define trigger() ((TRIGGER_PIN=1),(TRIGGER_PIN=0))
#define BIT(x)(1 << (x)) /*used by bit op macros */
#define BIT0 0x01 /*used by bit op macros */
#define BIT1 0x02
...
#define BIT6 0x40
#define BIT7 0x80
#define SETBIT(reg,bit) reg|=bit
#define CLRBIT(reg,bit) reg&=(~bit)
#define TGLBIT(reg,bit) reg^=bit
#define TSTBIT(reg,bit) (reg&bit)
/* to be used like
SETBIT(LATB, BIT(BIT0)); */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 68
The C Preprocessor
Conditional inclusions usethe "#if -
#endif" construction
This provides the possibility to include
code selectively
The expression after #if is evaluated, if
non-zero everything until #endif or
#elif or #else is included
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 69
The C Preprocessor
Conditional inclusions examples:
#if !defined HEADER_FIRST
#define HEADER_FIRST
/* content of header.h goes here */
#endif"
The first inclusion of "header.h" defines
HEADER_FIRST
Following inclusions will find HEADER_FIRST
defined ignoring everything down to #endif
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 70
The C Preprocessor
This avoids an error message from the
compiler that something may be
redefined, if we include the same
header filein several files and compile
them in any order
MPLAB
®
IDE for instance compiles
the files in alphabetic order ?!
Not in a logical order
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 71
The C Preprocessor
More conditional inclusions examples:
#define SOFT_SIM
/* simulation may take a while */
#ifdef SOFT_SIM
DelayUs(5);
#else
DelayMs(20);
#endif
#define LOWER_NIBBLE
#ifdef LOWER_NIBBLE
use_lower_bits_for_lcd();
#else
use_upper_bits_for_lcd();
#endif
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 72
Conclusion Remarks
“C” is somehow“primitive” (not as
primitiveasAssembler); thecomplexity
arises by combiningall featuresand
possibilties
“C” is somehow“sloppy”; it allows things
which may not makesense, even worse may
cause real trouble
“C” requires“selfresponsibility” (!!!)
programmers with selfdiscipline(!!!!!!!!!!).
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 73
Conclusion Remarks
Don't tryto be“Einstein”
Unfortunately today‘s genius is
tomorrows donkey
(remember KISS:
Keep It Simple Stupid).
Time to market has highest priority!!!
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 74
4079 EPC
Embedded Programming in C
Types, Operators and Expressions
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 75
Class Objective
When you finish this module you will know:
− How to name variables
− Which keywords are reserved
− Which data types are available
What value range they cover
− How to use the operators
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 76
Elements of the Source Code
C programs are made from“words”:
− Identifiers(variable names)
− Keywords
− Constants
− String literals
They are combined with operatorsto
specify their functionality
Separators areBLANK, TAB andline-end;
commentsact as delimiter; together they are
called“whitespace“
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 77
Elements of the Source Code
In C programs theASCII (128) character set is
used; it consistsof lower and upper case letters:
a-z, A-Z
the digits: 0-9
and the special characters: +-*/\=,.; ?"#
%&_' <>()[]{}
|^~@:
The diacritical letters from other languages are
not allowed
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 78
Elements of the Source Code
Upper caseand lower case letters are distinct
C is casesensitive !!!
The keywords like if, else, int, float, etc., are
reserved; theymust bein lower case
Some coding conventions:
− Variable name: MixedCaseWords
− Symbolic constants: UPPER_CASE_WORDS
Statements are terminated with';'
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 79
Keywords
C knows32 (-1) keywords!!!
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 80
Variable Names
Namesof variables or functions may use
letters, digitsand the underscore_ .
However, names are not allowedto start
witha digit, and they should not start with
an underscore, because library routinesuse
such names
It is wiseto choose relevant names, that are
relatedto the purposeof that variable
− InputTemperature, OutputTemperature
− not t1, t2
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 81
Variable Names
Dependingonthe compiler, the maximum
lengthof names may vary; please, check the
documentation
Some examplesof validand invalid names:
InputTemperature /* OK */
1_value /* wrong */
Caution /* OK */
_caution /* sub optimal */
SystemState /* OK */
if /* wrong */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 82
Variable Names
Anywhere“whitespace” is allowed,
comments may be placed
Comments are enclosed between/* and */
and maycover several rows
The single row comment from// to theend
of line is not ANSI compliant, however most
compilers accept it
Only add comments which clarifya
situation, don't comment what istrivial
− c = a + b; /* we add a and b */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 83
Data Types and Sizes
AnywhereC knows onlya few basic data
types
− char := a single byte, a single character
− int := an integer, reflecting the natural
sizeof the host
− float := single precision floatingpoint
− double := double precision floatingpoint
In addition the data types may be modified
with qualifiers
− short, long, signed and unsigned
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 84
Data Types and Sizes
#ifndef _LIMITS_H
#define _LIMITS_H
#define MB_LEN_MAX 1
/* char properties */
#define CHAR_BIT 8
#define SCHAR_MAX 0x7f
#define SCHAR_MIN (-SCHAR_MAX -1)
#define UCHAR_MAX 0xff
#define CHAR_MIN SCHAR_MIN
#define CHAR_MAX SCHAR_MAX
/* int properties */
#define SHRT_MAX 0x7fff
#define SHRT_MIN (-SHRT_MAX -1)
#define USHRT_MAX 0xffff
#define INT_MAX SHRT_MAX
#define INT_MIN SHRT_MIN
#define UINT_MAX USHRT_MAX
/* long properties */
#define LONG_MAX 0x7fffffff
#define LONG_MIN (-LONG_MAX -1)
#define ULONG_MAX 0xffffffffU
/* long long properties */
#define LLONG_MAX
0x7fffffffffffffffLL
#define LLONG_MIN (-LLONG_MAX -1)
#define ULLONG_MAX
0xffffffffffffffffUL
#endif
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 85
Data Types and Sizes
unsigned char : 0 – 255
signed char : -128 + 127
unsigned int : 0 – 65535
signed int : -32768 – 32767
unsigned long : 0 – 4294967295
signed long : -2147483648 - 2147483647
unsigned long long : 0 - 18446744073709551615
signed long long : -9223372036854775808 - 9223372036854775807
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 86
Constants
Four kindsof constants
− Integer constants
− Floating-point constants
− Character constants
− String constants
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 87
Integer Constants
Integer constants consist of digits withno
leading zeroand are usually interpreted asa
decimal value
1234 isan int; a long constant is written with
a trailingl or L
An integer toobigto fit an int will also be
taken asa long
Unsigned constants may use the suffixesu
and U or ul and UL
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 88
Integer Constants
Integer constants canalso be specified as
octal or hexadecimal values
01234 isan octal value, because there isa
leading zero
0x1f, 0X1F are hexadecimal values
Octal and hexadecimal values mayalso be
turned into long or unsigned long by using
the appropriate suffixes
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 89
Integer Constants
The following examples are row-wise equal:
1 01 0x1
10 012 0xA
4368 010420 0x1110
35000 0104270 0x8868 /* implizit
long */
35000l 0104270l 0x8868l
10L 012L 0xAL
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 90
Floating Point Constants
Floating-point constants containa decimal
point or an exponent (1e-2) or both
Floating-point constants aredouble unless
suffixes are used
Suffixes f or F indicatefloat
Some examples
123.4
1e-2
3.14L
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 91
Character Constants
Character constants areof data type char
and are enclosedin single quotes
The valueof character constants dependson
the machine‘scharacter set; wewill limit our
knowledge to theASCII character set
The character '0' has the value48, because
the hexa-decimal valueof '0' is0x30
The data type char mayalso be treated asan
8 bit integer, which makes it possibleto add
'0' and 9, to the ASCII representationof the
integer 9 !!!
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 92
Character Constants
Character constants mayalso be built using escape
sequences like\n for newline.
\n looks like two characters, but is treated as one
\ooo is representinga bit patternin octal notation
o = {0..7} (octal isout of date ?!)
\xhh is another bit patternin hexadecimal
presentation, allowinginsertion of any unprintable
ASCII character in an output stream
#define VTAB '\xB' /* ASCII vertical tab */
#define BELL '\x7' /* ASCII bell character */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 93
Character Constants
The complete set of predefined escape
sequences
\a alert (bell) \\ backslash
\b backspace \? question mark
\f formfeed \' single quote
\n newline \" double quote
\r carriage return \ooo octal number
\t horizontal tab \xhh hexadecimal number
\v vertical tab '\0' null character
Thenull character has the value zeroand is
often usedto emphasize this
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 94
String Constants
String constants or a literal string isa
sequenceof zero or more characaters
surrounded bydouble quotes like:
"Hello, world !\n"
"I am a string"
"" /* this is an empty string */
"Hello," "world !\n" /* concatenation */
This is useful for splitting long strings across
several rows
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 95
String Constants
Technicallya string constants isan arrayof
characters
The internal representationhas a null
character '\0' at theend (null terminated)
Physical storage is one character more than
characters between the""
strlen(s) returns the lengthof a string
excluding'\0'
Millionsof years ago, theTeletype simply
stopped printing when there wereno more
holesin the paper tape!!!
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 96
Variables and Their Declarations
All variables must be declared before use
Certain declarations can be made implicitly
by context (be careful !!!)
A declaration specifiesa typeand contains
one or morevariables of that type
int lower, upper, step;
char c, line[55], buffer[80];
int InputVoltage; /* any comment */
int OutputVoltage;
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 97
Variables and Their Declarations
A variable mayalso be initializedin its
declaration: char esc = '\\';
int i = 1;
int limit = MAXLINE + 1;
float eps = 1.0e-5;
If thevariable is not automatic, the
initialization is done once only, before the
program starts execution (busswordstart up
code)
An explicitly initializedvariable will be
initialized, eachtime the function or block is
called
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 98
Variables and Their Declarations
External and staticvariables are initializedto
zero by default
The qualifier const may be usedto indicate
the valueof thisvariable and will never be
changed
const double e = 2.718288182845905;
const char msg[] = "warning: ";
The latter createsa stringin ROM on a PIC
®
MCU
The better approach may beto usea constant
expressions:#define MAXLINE 1000
#define e 2.718288182845905
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 99
Variables and Their Declarations
We usethe words automatic, external and
static without having explainedthem
These are modifiers describing storage
classes
There are four storage classes:
auto
register
static
extern
(typedef)
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 100
Auto Variables
Declaringan auto variable also defines the
variables and causes storageto be reserved
If the auto variable is declared local in
function, it materializes with each function
call and disappears if the function is left
The auto variable does not retain the
content, it must be explicitly set upon each
call
Two auto variables with same name defined
local in two functions are not identical. =>
scope!!!
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 101
External Variables
As an alternative to auto variables, you may
declarean extern variable extern to all
functions
An extern variable may be accessed from
any functionin a program
An extern variable is globallyknownand
can be used insteadof parameter lists
Theextern variable remainspermanent and
retains itscontent
An extern variable must be defined, exactly
onceas global
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 102
Static Variables
A static variable isa variable which retains
itscontent between function calls
A static variable can be used inside or
outsideof a function
As an example, thinkof a counter, counting
how often this functionwas called
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 103
Register Variables
A register variable isan equivalent to an
auto variable, but tells the compiler it will
heavily be used, so tryto keep it in internal
registers
This is dependent on the underlying
hardware(processor) and the compiler may
ignore this
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 104
typedef
The typedef specifier does not reserve
storage spaceand is only called storage class
specifier for syntactic convenience
The same may be achieved when using
#define
More later
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 105
Variables and Their Scope
Variables definedin a function areprivate or
local to this function
No other function can access them direct
Two different functions may have local
variables with the same name
The local variable materializes when the
function is enteredand disappears when
leaving the function
These variables are auto by default, it is not
necessaryto specify auto (default)
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 106
Variables and Their Scope
An extern variable can be accessed by name
from any function
An extern variable must be defined outside
of any function only once(global, no
keywordextern)
An extern variable must be declaredin
every function that wantsto accessit
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 107
Variables and Their Scope
/* code snipped */
int max; /* global definition */
function_1()
{
int i; /* local declaration */
extern int max;/* use max from global definition */
}
function_2()
{
int i; /* different than i from function_1*/
}
...
/* different file */
extern int max;
function_3()
{...
max = a + b; /* uses global max */
}
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 108
Operators
Arithmetic operators
Relational and logical operators
Bitwise operators
Expressionsand assignments
Conditional expressions
Precedenceand order of evaluation
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 109
Arithmetic Operators
6 Arithmetic operators
unary sign -
add +
minus -
multiply *
divide /
modulo %
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 110
Arithmetic Operators
Examples
int i=3, j=5, k=10;
int m;
float r=3., s=5.;
float u;
m = i+j+k; / * 18 */
m = k-j-i; / * 2 */
m = i-k; / * -7 */
m = k/ i; / * 3 */
m = k/ i+j; / * 8 */
m = k/ (i+j); / * 1 */
m = k*i+j; / * 35 */
m = k*(i+j); / * 80 */
m = k%i; / * 1 */
u = s+r; / * 8. */
u = s/ r; / * 1.666... */
u = s*r; / *15. */
u = k/ r; / * 3.333... */
u = k/ r +s/ r; / * 5. */
u = k/ i + s/ i; / * 4.666... */
u = k%r; / * nicht erlaubt */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 111
“ Unusual” Operators
− Increment ++ /* adds 1 */
− Decrement -- /* subtracts 1 */
Both may be used as pre- or postfix operators:
n=5;
x = n++; /* x == 5, n == 6 */
x = ++n; /* x == 7, n == 7 */
x = n--; /* x == 7, n == 6 */
x = --n; /* x == 5, n == 5 */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 112
“ Unusual” Operators
int i;
int k;
i=1;
if (++i > 1)
k = 5; /* will be performed */
if (i++ > 2)
k = 10; /* will not be performed */
printf ("\nk equals: %d\n",k); /* output: 5 */
int i,k;
int j;
i=2;
k=3;
j = i+++k; /* i+ (++k); i=2,k=4,j=6 */
j = (i++)+k; /* i=3,k=4,j=6 */
j = i++ +k; /* i=4,k=4,j=7 */
j = (i+k)++; /* forbidden !!! */
j = i+k+1;
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 113
Relational Operators
greater >
greater or equal >=
less <
less or equal <=
identical ==
not identical !=
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 114
Relational Operators
Examples
int a=5;
int b=12;
int c=7;
a < b /* true */
b < c /* false */
a+c <= b /* true */
b-a >= c /* true */
a == b /* false */
a+c == b /* true */
a != b /* true */
a = b<c; /* may be: a=0 */
a = c<b; /* -"- a=1 */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 115
Bitwise Operators
bitwiseAND &
bitwiseinclusiveOR |
bitwise exclusive OR ^
left shift <<
right shift >>
one's complement ~
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 116
Bitwise Operators
char i=7; /* 0b00000111 */
char j=9; /* 0b00001001 */
char k;
k = i & j; /* k=1 */
k = i | j; /* k=15 */
k = i ^ j; /* k=14 */
k = ~0 /* k=max(unsigned int) */
k = ~i; /* k=max(unsigned int) -7 */
k = i << 3; /* k=56 */
k = i >> 3; /* k=0 */
k = i & 0x03; /* k=3; mask of all bits, but the
lower two */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 117
Expressions and Assignments
Assignment Expression:
left side– operator – right side;
x = x + 1;
New x becomesold x + 1 !!!
Here= is the assignment operator left side
must bea variable right side may bea
constant or any expression
Short form
x += 1; (confused? Well, don't do it )
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 118
Conditional Expressions
Using conditional Expressions:
if(a >b)
z = a; /* executed
if condition true */
else
z = b; /* executed
if condition false */
May be writtenin short using the ternary
operator " ? : ". Like:
z = (a > b) ? a : b; /* z becomes max(a,b) */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 119
Precedence and Associativity of
Operators
Operators Associativity
()() [] -> . left to right
! ~ ++ -- - (type) * & sizeof right to left
* / % left to right
+ - left to right
<< >> left to right
< <= > >= left to right
== != left to right
& left to right
^ left to right
| left to right
&& left to right
|| left to right
?: right to left
= += -= += /= (etc.) right to left
, left to right
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 120
“ void”
"void" describesan empty domain, value or
answer
void main(void) ... /* get's no parameter,*/
void init(void) ... /* does not return a
value */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 121
4079 EPC
Embedded Programming in
C Control Flow
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 122
Class Objective
When you finish this module you will:
− Know how to control your program flow with
Statements and blocks
Decisions: if-else, else – if, switch
Loops: while, for, do – while
Exit from loops: break, continue
The "infinitly-abusable" goto and labels
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 123
Statements and Blocks
An expression like
x = 0 or i++ or printf( … )
becomes a statement when followed by a
semicolon; the semicolon is the statement
terminator
x = 0;
i++;
printf( … );
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 124
Statements and Blocks
Braces { } may be used to group
declarations and statements into compound
statements or blocks; a compound statement
is syntactically equivalent to a single
statement
− Examples
Function bodies
Multiple statements after if, else, while, for …
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 125
if - else
The if – else statement is used for simple
decisions; the formal syntax is:
if(expression)
statement_1 /* expression is true */
else /* optional */
statement_2 /* expression is false */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 126
true - false
TRUE is NOT 1 !!!
false: expression == 0
true: expression != 0
ANY non-zero value is true !!!
if(expression) /* is short for */
if(expression != 0) /* more readable */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 127
Nested if
if(n > 0)
if(a>b)
z = a;
else /* belongs to the second if */
z = b;
if(n > 0)
{
if(a > b)
z = b;
}
else /* belongs to the first if */
z = b;
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 128
else - if
The most general construction of a multi-way
decision uses an if – else if chain
if(expression)
statement_1
else if(expression)
statement_2
else if(expression)
statement_3
else if(expression)
statement_4
else
statement_5
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 129
else - if
The expressions are evaluated in order; if any
expression is true the associated statement
will be executed and this terminates the chain
if(TMR0IE && TMR0IF)
TMR0_isr();
else if(INTE && INTF)
INT_isr();
else if(RBIE && RBIF)
PB_CHANGE_isr();
else
Error_isr();
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 130
switch
The switch statement is a multi-way decision
that tests whether an expression matches a
constant integer value; the formal syntax is:
switch(expression)
{
case const_expression: statements
case const_expression: statements
default: statements
}
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 131
switch
character = getchar(); /* case blind */
switch(character) /* commands */
{
case 'a':
case 'A': a_statements
break;
case 'b':
case 'B': b_statements
break;
case 'c':
case 'c': c_statements
break;
default: statements
break;
}
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 132
break
The break statement causes an immediate
exit from the switch
The cases serve as labels; all following
statements will be executed if not
abandoned with break or return
A break can also be used to exit while,
for and do loops
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 133
while
The while statement is one of the loop
constructions you may use most; there is no
initialization or re-initialization
The formal syntax is:
while(expression)
statement /* expression is true */
The expression is evaluated, if it is true (non-
zero) statement is executed and expression re-
evaluated
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 134
while
character = getchar();
while( character == ' '
|| character == '\n'
|| character == '\t')
; /* do nothing,
skip white space
characters */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 135
for
The for statement may be used if simple
initialization and increment or decrement should
be executed; the formal syntax is:
for(expression_1;expression_2;expression_3)
statement
This is equivalent to:
expression_1;
while(expression_2)
{
statement;
expression_3;
}
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 136
for
for(expression_1;expression_2;expression_3)
statement
/* expression_1 does the initialization
expression_2 will be evaluated always
at the beginning of the loop,
If true, statement will be executed.
expression_3 does the re-initialization
*/
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 137
for
for(i=0;i<n;i++)
statement
for(i=MAX;i>0;i--)
statement
void delay(int time)
{
for(;time > 0;time--)
NOP();
}
delay(20);
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 138
forever
for(;;) /* loops forever */
statement
while(1) /* loops forever, too */
statement
void main(void)
{
initialization();
while(1) /* the sad and boring */
mainfunction(); /* life of an µC */
}
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 139
do - while
The do-while loop is the post-test loop in C; the
test is done after each pass of the body; the while
and the for loop test at the beginning
The formal syntax is:
do
statement
while(expression) /* leave if
expression is false */
The statement is executed, expression is evaluated,
if it is true (non-zero) statement is executed again
and expression re-evaluated; false terminates the
loop
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 140
do - while
/* itoa: convert integer to characters */
void itoa(int n, char string[])
{ int i, sign;
if((sign=n)<0) /* record sign*/
n=-n; /* make n positive */
i=0;
/* generate digits in reverse order */
do {
string[i++] = n % 10 + '0'; /* get next */
} while((n /= 10) > 0); /* delete it */
if(sign < 0)
string[i++] = '-';
string[i] = '\0';
reverse(string); /*foreign function used */
}
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 141
break - continue
The break statement causes an immediate
exit from a loop
The continue statement causes the next
iteration of the enclosing while, for and
do loops
The continue statement only applies to
loops, not to switch; if the switch is part
of a loop, the loop will be iterated !!!
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 142
break - continue
for(time = value;time > 0;time--)
NOP();
for(time = value;time > 0;time--)
; /* some optimizers do nothing */
for(time = value;time > 0;time--)
continue;
time = value;
while(time-- > 0)
continue;
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 143
goto and Labels
The goto statement is defined in C, but is
NEVER necessary
(refer to Djikstras: "goto statement
considered harmful")
In practice you should write code without
goto's
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 144
4079 EPC
Embedded Programming in C
Functions and Program Structure
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 145
Class Objective
When you finish this module you will know:
− How to organize your program, sothat it becomes
readable
− How to make your life easier by re-using written
code
− How to make friends by writing functions they can
use
− Here we talk about
Functions
Files
Preprocessor facilities
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 146
Functions
Functions break large computing tasks into
smaller ones
Programs can be built on functions already
written
Functions may hide details, thus clarifying
the WHOLE
Functions make changes less painful
(especially if they are in separate files)
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 147
Functions
Functions assist a "Top Down" analysis
strategy of problems
Existing functions can be used in a "Bottom
Up" approach to build a program
We will use the whole cycle when
"putting it all together"
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 148
Functions
C programs generally consist of many small
functions rather than a few big ones
A program may be made up of one or more
source files
Source files may be compiled separately
and loaded together, along with previously
compiled functions from libraries
(we will use MPLAB
®
IDE to do this)
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 149
Basics of Functions
Each function definition has the form:
returntype functionname (argument declarations)
{
declarations and statements
}
Various parts may be absent:
dummy(){}
does nothing and returns nothing
(placeholder ???, debugging ???)
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 150
Basics of Functions
A program is just a set of definitions of
variables and functions
Communication between functions is
realized by
− Arguments forwarded to
− Values returned from the function
Functions can occur in any order
Source program can be split into multiple
files
Functions can not be split
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 151
Basics of Functions
If the return type is omitted, int is assumed
The return statement is the mechanism for
returning a value from the called function to its
caller
Any expression can follow return:
return expression;
Expression will be converted to the return type of
the function if necessary
Parentheses are often used around the expression,
but they are optional
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 152
Basics of Functions
The calling function may ignore the return
value
The return statement may return no value
return;
Control will also be returned to the calling
function when reaching the end of the
called function; this makes grouping if
statements very handy
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 153
Functions Example
#include <stdio.h>
#define MAXLINE 100
main()
{
char line[MAXLINE];
while(getline(line, MAXLINE) > 0)
if(index(line,"the")
printf("%s",line);
}
/* to be continued ... */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 154
Functions Example
int getline(char s[], int limit)
{ int c, i;
i = 0;
while(--limit>0 && (c=getchar()) != EOF && c != '\n')
s[i++] = c;
if(c == '\n')
s[i++] = c;
s[i] = '\0';
return(i);
}
}
/* to be continued ... */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 155
Functions Example
index(char s[], char t[])
/* return the position of t in s, -1 if not found */
{ int i, j, k;
for(i = 0; s[i] != '\0';i++)
{
for(j=1, k=0; t[k] != '\0' && s[j] == t[k]; j++, k++)
;
if(t[k] == '\0'
return(i);
}
return(-1);
}
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 156
A More Practical Example
#include <p24fxxxx.h>
#define PORTB_IO_MASK 0xFF00
/* we need to tell the compiler, that the two functions are of
type void, because it assumes int */
void initialize(void); /* prototypes */
void mainfunction(void);
int main(void)
{ initialize();
while(1)
{
mainfunction();
}
}
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 157
A More Practical Example
void initialize(void)
{
TRISB = PORTB_IO_MASK;
}
void mainfunction(void)
{
NOP(); /* breakpoint possible for timing control ??*/
LATBbits.LATB0 = ~LATBbits.LATB0;
}
/* see the bit toggle in MPLABs watch window ☺ */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 158
Splitting Programs in Files
For better handling it seems to be wise to split
large programs in smaller portions
The UNIX command
$ cc main.c file1.c file2.c
will create one executable from all named files
The UNIX command
$ cc main.c file1.o file2.o
will create one executable from all named files,
but re-compiles only main.c
For the mouse clicking generation:
The same can be achieved with MPLAB
®
IDE by
clicking compile all or make
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 159
Splitting Programs in Files
We will use our tiny bit toggle program to
start splitting
We get the opportunityto discuss some
related issues like:
− Header files (1 or more?)
− Prototypes
− Saving compile time
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 160
Splitting Programs in Files
The three functions main, initialize and
mainfunctionshould go into separate files
− main.c
− initialize.c
− mainfunction.c
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 161
Splitting Programs in Files
/* content of file main.c */
#include <p24fxxxx.h>
/* we need to tell the compiler, that the two functions are of
type void, because it assumes int */
#include "initialize.h"
#include "mainfunction.h"
int main(void)
{ initialize();
while(1)
{
mainfunction();
}
}
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 162
Splitting Programs in Files
/* content of file initialize.c */
#include <p24fxxxx.h>
#include "initialize.h"
void initialize(void)
{
TRISB = TRISB_MASK;
}
/* content of file initialize.h */
#ifndef INIT_FIRST
#define INIT_FIRST
#define TRISB_MASK 0xFF00
void initialize(void);
#endif
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 163
Splitting Programs in Files
/* content of file mainfunction.c */
#include <p24fxxxx.h>
#include "mainfunction.h"
void mainfunction(void)
{
NOP(); /* breakpoint possible for timing control ??*/
LATBbits.LATB0 = ~LATBbits.LATB0;
}
/* content of file mainfunction.h */
#ifndef MAIN_FNCTN_FIRST
#define MAIN_FNCTN_FIRST
void mainfunction(void);
#endif
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 164
4079 EPC
Embedded Programming in
C Arrays and Pointers
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 165
Class Objective
When you finish this module you will know:
− How to group objects with arrays
− How to use pointers to your advantage
− How pointers enable functions to modify their outer
space
− How to use pointers without confusing anybody,
especially yourself
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 166
Arrays
An array is grouping objects of the same data
type
Arrays may have
− One dimension
string
− Many dimensions
The objects are linearly stored in memory
An array is identified by "[]" following the
name
The name of an array is the address of the
first element in the memory !!!
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 167
Arrays
The size of the array is specified in the
"[]"
Some examples
char s; /* 1 character */
char sf[20]; /* 20 characters */
int i; /* 1 integer */
int iff[100]; /* 100 integers
=> 200 bytes ! */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 168
Arrays
To access an element of the array, use the
name followed by the index (the address of
that element) in brackets:
int j, k;
j = 5;
sf[8] = 'a';
sf[j] = sf[19];
k = iff[j];
Indexes count from 0 to MAX
(address of first element is array name + 0)
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 169
Arrays
The first element always has the index 0
(zero)
Elements may be of any data type
− char
− int
− long
− (long long)
− Float
But always the same data type
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 170
Arrays
C programmer at the airport:
»0,1,2 – Where is my third suitcase ??? «
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 171
Arrays
Arrays of storage class auto cannot be
initialized; only if static or extern (global)
Arrays cannot be of storage class register,
because they may be too big
Elements of uninitialized arrays will be
initialized to zero
Initial values may be given after the array in
"{}"
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 172
Arrays
Some examples on initializing arrays
int iff[10] = {1,2,3,4,5,6,7,8,9,10};
int jf[5] = {0,1,3};
/* only the first three initialized
explicitly, all others = 0*/
int kf[] = {1,3,5,7,11,13};
/* size of array specified through
number of values */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 173
Arrays
/* filling an array with the sum of natural
numbers up to this field */
#define MAX 100;
int sum[MAX], i, j;
for (i=0, j=0; i < MAX; i++)
{
j = j + i + 1;
sum[i] = j;
}
/* doing the same without using the first
element */
#define MAX 101;
for (i=1,j=0; i < MAX; i++)
{
j = j + i + 1;
sum[i] = j;
}
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 174
strings
Strings are a special type of one
dimensioned arrays
Strings are grouping values of char data
type
Even in the register class auto, they may be
initialized
They are always terminated by '\0'
So add one to the visible size
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 175
strings
Initialization can be easily done :
char s[] =
{'s','t','r','i','n','g','\0'};
char s[] = "string";
/* '\0' appended automaticly;
size of array is 7 !!! */
char s[10] = "string";
/* rest of array filled with zeros */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 176
strings
Beyond these specialties, they may be
treated as ordinary arrays
The elements of strings may be accessed as
below:
s[0] has the value 's'
s[3] has the value 'i'
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 177
Arrays
/* two versions filling an array with square
numbers */
#define MAX 100;
int mul[MAX], i;
for (i=0; i<MAX; i++)
mul[i] = (i + 1) * (i + 1);
/*
*/
#define MAX 100;
int mul[MAX], i, j;
for (i=0,j=0; i < MAX; i++, j++ )
mul[i] = j * j;
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 178
Multidimensional Arrays
A multidimensional array may have several
pairs of "[]" following the name
(not separated by ',')
A multidimensional array is an array of
arrays
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 179
Multidimensional Arrays
/* declaration may be extern or in the
calling function */
int md[5] [10]; /* extern (global) */
funct(md,5);
/* in the function */
void funct(int mdf[][10], int howmany)
{
int i, z;
for (i=0; i<howmany; i++)
for (j=0; j<10; j++)
mdf[i][j] = i + j;
}
/* with howmany, we forward the actual size
of the first array */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 180
Multidimensional Arrays
The same, as with the previous program,
may be achieved by initialization:
static int md[][] =
{
{0,1,2,3,4,5, 6, 7, 8, 9}
,{1,2,3,4,5,6, 7, 8, 9,10}
,{2,3,4,5,6,7, 8, 9,10,11}
,{3,4,5,6,7,8, 9,10,11,12}
,{4,5,6,7,8,9,10,11,12,13}
};
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 181
Multidimensional Arrays
A more practical example:
const char multistring[][40] =
{
{"Error !!!"}
,{"Well done !"}
,{"Temperature too high"}
,{"The time is: "}
,{"… and the winner is: "}
};
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 182
Multidimensional Arrays
The init values may be placed in separate
curly brackets such as ','-separated list
In between the brackets the non initialized
values will be set to zero
The inner brackets may be omitted
However, it may become quite confusing
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 183
Multidimensional Arrays
More examples:
static int day_tab[2][13]=
{{0,31,28,31,30,31,30,31,31,30,31,30,31}
,{0,31,29,31,30,31,30,31,31,30,31,30,31}
};
/* calculate the day of the year from month
and day */
day_of_year(int year, int month, int day)
{ int i, leap;
leap = year%4 == 0 && year%100 != 0
|| year%400 == 0;
for(i=1; i<month; i++)
day = day + day_tab[leap][i];
return(day);
}
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 184
Multidimensional Arrays
An example using pointers !?:
/* calculate month and day from the day of
the year */
month_day(int year, int yearday, int
*pmonth, int *pday)
{ int i, leap;
leap = year%4 == 0 && year%100 != 0
|| year%400 == 0;
for(i=1; yearday > day_tab[leap][i]; i++)
yearday = yearday - day_tab[leap][i];
*pmonth = i;
*pday = yearday;
}
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 185
What Are Pointers ???
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 186
Pointers and Arrays
A pointer is a variable that contains the
address of a variable !!!
Pointers are closely related to arrays and
similar structures
Pointers together with goto statements are a
“marvelous“ way to createimpossible-to-
understandprograms
(from"TheC Programming Language")
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 187
Pointers and Arrays
Pointers and addresses
Pointer arithmetic
Pointers and arrays
Pointers to functions
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 188
Pointers and Addresses
To get the address of a variable you use the
unary oparator "&"
pVar = &anyVar
pVar contains now the address of anyVar
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 189
Pointers and Addresses
The unary operator "*" is the indirection or
dereferencing operator
If the indirection operator is applied to a
pointer variable, it manipulates the object to
which the pointer variable points
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 190
Pointers and Addresses
Some examples:
pV= &anyVar; /* pV points to anyVar */
anyVar = 1; /* anyVar becomes 1 */
W = *pV; /* W becomes 1 */
*pV = 0; /* anyVar becomes 0 */
(If using a PIC
®
MCU you may think about
the FSR register)
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 191
Pointers and Addresses
Declaring a pointer variable is useful
int *pVar1; /* this pointer points to
an integer Variable */
char *pVar2; /* this pointer points to
a char */
long *pVar3; /* this pointer points to
a long integer */
pVar1, pVar2, pVar3 are integers;
they represent Variables containing addresses.
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 192
Pointers and Addresses
Pointers point to a certain data type
This must be declared using the "*"
operator
Pointer arithmetic knows how to deal
with these data types
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 193
Pointers Arithmetic
If p is a pointer and n is an integer,
p+n points to n-thelement after the
element p points to
n is not added direct to p, n is
multiplied by the type length of the
data type to which p points
The type is known from the declaration
of p
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 194
Pointers Arithmetic
Because a pointer variable contains an
address, and an address is an integer, only
certain integer operations are allowed
Only integers may be added or subtracted
to/from a pointer
Pointers can be inc or dec - remented
Pointers may be subtracted from each other
(this only makes sense if they point to the
same group of objects)
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 195
Pointers Arithmetic
Pointers can be compared using
“>, >0, <, <=, !=, =="
Again, this only makes sense if they
point to the same target
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 196
Pointers Arithmetic
Anything else, like adding two
pointers, multiplication, division, shifts,
logical operations, adding or
subtracting floating point values are not
allowed !!!
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 197
Pointers and Addresses
A pointer (*pVar) can be used anywhere,
where the variable it points to may be used,
too ( not clear what this means??)
y = *px + 10;
y = *px + *px;
printf("%d\n", *px);
*px = 0;
py = px;
/* given py is a pointer, too */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 198
Pointers !
and …???
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 199
Pointers and Arrays
An array groups objects of the same
data type
Arrays will be used based on their start
address
The name of an array is the start
address
The start address is fixed- a constant
=> the name is constant
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 200
Pointers and Arrays
A pointer is a variable, which may hold
the address of any object
The object may be accessed indirectly
via the pointer !!!
Watch for precedence and associativity
!!!
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 201
Pointers and Addresses
Precedence and Associativity
y = *px + 1; /* y =(content of px) + 1 */
y = *(px+1); /* y = cntnt of Address px+1 */
*px += 1; /* cntnt of px = cntnt of px + 1*/
(*px)++; /* increment content of px */
*px++; /* *(px++); px = px + 1; */
*++px; /* pre-increment; px = px + 1;
content of address px + 1;
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 202
Pointers and Addresses
Combined examples
int a[10]; /* array of integer, 10 elements */
int *pa, y, i; /* pointer to an integer object */
pa = &a[0]; /* pa = address of first element */
pa = a; /* same as above,
because a is address of array */
y = *pa; /* y = first element */
y = *(pa + 1); /* y = second element */
y = *px++; /* y = content of px; px = px + 1; */
i = 0;
y = a[0]; /* y = first element */
y = a[i]; /* dito */
Y = a[++i]; /* ??? */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 203
Pointers and Addresses
More examples
a[i] is equivalent to *(a+i)
&a[i] " (a+i)
pa[i ] " *(pa+i)
If you don’t want to use pointers,
you don’t have to !!!
(but sometimes they make your life easier ;-))
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 204
Pointers and Addresses
Allowed / Not Allowed
pa = a; /* left side becomes constant */
pa++; /* increment pointer variable */
a = pa; /* ??? Address = variable ??? */
a++; /* ??? Increment a constant ??? */
pa = &a; /* ??? pa = address of address ??? */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 205
Pointers and Addresses
Example
strlen(char *s) /* get the length of a string */
{
int n;
for(n=0; *s != '\0'; s++)
n++;
return(n);
}
strlen(char *s) /* 2. version */
{
int n;
for(n=0; *s != '\0'; s++)
n++;
return(n);
}
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 206
Pointers and Addresses
4 ways how to copy a string
strcpy(char s[], char t[]) /* 1.: using arrays */
{
int n;
i = 0;
while((s[i] = t[i]) != '\0' )
i++;
}
strcpy(char *s, char *t) /* 2.: using pointer */
{
while((*s = *t) != '\0' )
{
s++;
t++;
}
}
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 207
Pointers and Addresses
4 ways how to copy a string
strcpy(char *s, char *t) /* 3.: using pointer */
{
while((*s++ = *t++) != '\0' )
;
}
strcpy(char *s, char *t) /* 4.: using pointer */
{
while(*s++ = *t++) /* confused ??? */
;
}
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 208
Some Specialties
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 209
Specialties
Remarks about some specialties without diving too
deep into:
− Pointers to functions
− Arrays of pointers
− Pointers to pointers
− Multidimensional arrays
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 210
Pointers to Functions
In "C" a function is not a variable; the
function name is an address constant
As with Arrays it is possible to define a
pointer to a function, which may be
used as a variable
This makes it possible to forward
functions to functions !!!
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 211
Pointers to Functions
A pointer to a function will be declared
as:
(* function_name) () /* pointer to a
function */
In contrast to:
* function_name() /* function returns
a pointer */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 212
Arrays of Pointers
Using arrays to group basic data types,
can be extended to group pointers; an
array of pointer:
* array_name)[] /* from right to left;
precedence of [];
an array of pointers */
In contrast to:
(* array_name([] /* a pointer to an array */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 213
Pointers to Pointers
Pointers to pointers are equivalent to
arrays of pointers:
int *iff[];
int **iff; /* are equivalent, because iff
contains the address of the
array */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 214
Array of Pointers
char *month_name(int n) /* returns name */
{ /* of nth month */
static char *name[] = /* array of pointers */
{ "wrong_month" /* string is an array of */
,"January" /* of char-s, */
,"February" /* characterized by the */
,"March" /* start address !!! */
,"April" /* Pointer arithmetic */
,"May" /* knows this !!! */
,"June"
,"July"
,"August"
,"September"
,"October"
,"November"
,"December"
};
return((n < 1 || n > 12) ? name[0] : name[n]);
}
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 215
Multidimensional Arrays
A multidimensional array is an array of
arrays; they can be realized using
pointers:
int md[10] [10]; /* a 2 dimensional array
with a total of 100
int objects */
int *mp[10]; /* an array with 10 pointer
to int objects */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 216
Multidimensional Arrays
The expressions
md[5][5] and mp[5][5]
are both valid and describe the same
element
md is an array with 10 elements, which are
arrays with 10 elements themselves
md has 100 elements in total, for which
memory will be allocated
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 217
Multidimensional Arrays
mp is an array with 10 elements, which
are pointers to integer objects
(addresses ? They may point to arrays
with 0 elements)
mp has been declared as an array of 10
pointers, for which memory will be
allocated, but not initialized
mp needs more memory than md and
additional efforts for initialization
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 218
Multidimensional Arrays
mp offers 2 advantages
− Because of the simpler addressing
mechanics, shorter execution times
− Pointers may point to arrays with
different length
(multidimensional arrays always have
fixed length sub arrays)
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 219
4079 EPC
Embedded Programming in C
Structures, Unions and Enumeration
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 220
Class Objective
When you finish this class you will:
− Know how to group different data types with
Structures
Unions
Enumeration
− Know how to define "bits"
− Know what "typedef" may be used for
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 221
Structures
Introduction to structures
Declaration of structures
Access to members of structures
(recursive structures)
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 222
Structures
Arrays are used to group elements of the
same data type
Structures are used to group elements of
different data types
Structures are used to organize complicated
data like database rows, TCP/IP messages,
CAN messages
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 223
Declaring Structures
Declaring a structure is done by using the
keyword struct:
struct structure_name
{
structure_member(s)
}variable_name(s) initialization
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 224
Declaring Structures
Structure name is optional and may be used
after its declaration as a special "data" type,
or a shortcut to what is in its body
Structure members will be declared as usual
Structure and member names may be
identical to other variables; the compiler
knows how to differentiate
If a variable name is given, the structure
will be created, memory will be allocated
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 225
Declaring Structures
Structures without a variable name may be
treated as a prototype of that structure
Structures can only be initialized, if
declared global (extern to a function) or
static
Structures arrange their members linearly in
the memory
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 226
Structures Examples
struct date
{ int day;
int month;
int year;
int day_of_year;
char name_of_month[4];
}; /* defines the prototype structure */
struct date
{ int day;
int month;
int year;
int day_of_year;
char name_of_month[4];
}birth_date, today;
/* creates the structures birth_date
and today of type date */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 227
Structures Examples
struct date birth_date, today;
/* also creates the structures birth_date
and today of type date */
struct date today =
{ 26
, 7
, 2006
, 0
, "jul"
};
/* creates and initializes the structures birth_date
and today of type date */
extern structure date today;
/* we should use a structure today of type date
defined somewhere else */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 228
Structures in Memory
low byte low byte
high high byte byte
low byte low byte
high high byte byte
low byte low byte
high high byte byte
low byte low byte
high high byte byte
} } integer integer
} } integer integer
} } integer integer
} } integer integer
char char
char char
char char
char char = ' = ' \ \0' 0'
start start address address
end end address address
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 229
Structures
Structures may contain structures, but not
recursive
struct customer
{ char name[NAME_LENGTH];
char address[ADDR_LENGTH];
int customer_number;
struct date delivery_date;
struct date billing_date;
struct date payment_date;
};
struct customer customer_1, customer_2, … ;
struct customer arrayCustomer[CUST_MAX];
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 230
Structures
A more µC related example:
struct message
{ int target_address;
int target_command;
int msg_data_length;
char data_buffer[BUFFER_MAX];
int crc;
};
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 231
Accessing Structures
Two operations are possible with structures
− Accessing the members
Direct
Indirect
− Retrieving the start address
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 232
Accessing Structures
Retrieving the address is achieved using the
'&' operator, as usual
Accessing a member or component of the
structure direct, uses the '.' operator
structure_variable.component
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 233
Accessing Structures
Direct access examples:
birth_date.year
today.day
today.name_of_month
customer_1.customer_number
arrayCustomers[3].name
customer_2.delivery_date.month
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 234
Accessing Structures
In order to access a member or component
of the structure indirect, the pointer variable
must hold the address of the structure; then,
the component may be accessed via the '-
>' operator.<
pointer_var_to_structure -> component
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 235
Accessing Structures
Indirect access examples:
struct date *pdat;
struct customer *pcust;
pdat = today;
pcust = arrayCustomers[4];
pdat -> day
pdat -> name_of_month[1]
pcust -> address
puts -> billing_date.month
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 236
Accessing Structures
We will not go further, because the chance
to implement DB2, Oracle or Teradata on a
µC may be quite rare
Watch out for embedded Linux !!!
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 237
(Recursive Structures)
The same -- at the moment there is no need
to implement linked lists, data trees …
Watch out for embedded Linux !!!
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 238
Unions
Introduction to unions
Declaration of unions
Access to members of unions
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 239
Introduction to Unions
Structures are grouping of variables of
different data types linearly in the memory;
they all exist at the same time
A union is a variable which may hold
objects of different data types at different
times
Sounds strange?
Let's look at the memory picture before
continuing
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 240
Unions in Memory
low byte low byte
high high byte byte
low byte low byte
high high byte byte
low byte low byte
high high byte byte
low byte low byte
high high byte byte
char char
char char
char char
char char
start start address address
end end address address
} } integer integer
} } integer integer
}
} long long integer integer
byte byte 0 0
byte byte 1 1
byte byte 2 2
byte byte 3 3
0 0 7 7
0 0 7 7 15 15 31 31
byte byte 0 0 byte byte 1 1 byte byte 2 2 byte byte 3 3
integer integer integer integer
long long integer integer
We are little endians We are little endians ! !
(and (and we are we are right !!!) right !!!)
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 241
Declaring Unions
Declaring a union is done by using the
keyword union; the syntax is similar to
structures:
union union_name
{
union_member(s)
}union_name(s)
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 242
Declaring Unions
Declaring a union:
union u_tag /* union type u_tag */
{
int ival;
float fval;
char *pval;
}uval; /* variable name uval */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 243
Declaring Unions
It would be useful to know, what kind of
data our union holds in the moment:
if(utype == INT)
printf("%d\n",uval.ival);
else if(utype == FLOAT)
printf("%f\n",uval.float);
else if(utype == STRING)
printf("%s\n",uval.pval);
else
printf("bad type %d in \
utype\n",utype);
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 244
Declaring Unions
Structures may be members of unions
Unions may be members of structures
struct
{ char *name;
int flags;
int utype;
union
{ int ival;
float fval;
char *pval;
}uval;
}symtab[NSYM];
symtab[i].uval.ival /* accessing ival */
*symtab[i].uval.pval /* 1. Character from pval */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 245
Declaring Unions
An example from early Intel days:
struct WORDREGS
{ unsigned int ax;
unsigned int bx;
unsigned int cx;
unsigned int dx;
unsigned int si;
unsigned int di;
unsigned int cflag;
};
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 246
Declaring Unions
An example from early Intel days:
struct BYTEREGS
{ unsigned char al, ah;
unsigned char bl, bh;
unsigned char cl, ch;
unsigned char dl, dh;
};
union REGS
{ struct WORDREGS x;
struct BYTEREGS h;
};
inregs.x.bx = 0x12; /* BX register becomes hex 12 */
inregs.h.ah = 0x10; /* AH register becomes hex 10 */
c = outregs.x.cx; /* CX copied to c */
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 247
Declaring Unions
An example from the 8-bit PIC18Fxxxx family:
struct twoBytes
{ char low;
char high;
};
union AD result
{ int intersect;
char byteResult[2];
struct two Bytes byte;
};
int readADC(void)
{ union ADCresult i;
i.byteResult[0] = ADRESL; /* i.byte.low = ADRESL */
i.byteResult[1] = ADRESH; /* i.byte.high = ADRESH */
return(i.intResult);
}
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 248
Enumeration
The enumeration uses the keyword enum; it
is followed by a name and a list of constant
values the enumeration variable may
contain
enum enumeration_type
{
list_of_constants
} enum_variable(s);
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 249
Enumeration
Example:
enum COLOURS
{
yellow
, green
, blue
, red
}colour;
enum COLOURS clrs, *pclrs;
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 250
Enumeration
The internal representation is an integer starting
with 0. Yellow == 0, green ==1, blue == 2, red
==3.
The constants can have direct values assigned to
them; subsequent values will be incremented
enum COLOURS
{ yellow /* == 0 */
, green = 3
, blue /* == 4 */
, red
, black = 8
, brown /* == 9 */
};
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 251
Enumeration
µC Example:
enum SYSTEM_STATES
{ IDLE
, KEY_DETECTED
, KEY_VALID
, ACTION_DONE
};
enum SYSTEM_STATES varSystemState;
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 252
Enumeration
void mainfunction(void)
{ switch(varSytemState)
{ case IDLE: if(key == ACTIVE_LOW)
varSystemState = KEY_DETECTED;
break;
case KEY_DETECTED: debounce();
if(key == ACTIVE_LOW)
varSystemState = KEY_VALID;
else
varSystemState = IDLE;
break;
case KEY_VALID: keyAction();
varSystemState = ACTION_DONE;
break;
case ACTION_DONE:
if(key != ACTIVE_LOW)
{ debounce();
if(key != ACTIVE_LOW
varSystemState = IDLE;
}
break;
default: varSystemState = IDLE;
break;
}
}
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 253
typedef
typedef allows us to define new data type
names; not new data types
typedef is similar to #define, but more
rigid than simple text replacement
typedef may be used to avoid portability
problems with incompatible data types
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 254
typedef
Unfortunately an integer is not always equal
( not clear??)
To avoid this we may define the following:
typedef uint8_t unsigned char;
typedef int8_t signed char;
typedef uint16_t unsigned int;
typedef int16_t signed int;
typedef uint32_t unsigned long;
typedef int32_t signed long;
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 255
bits
C does not know a bit data type!!!
Manipulation of single bits in a byte or
word is performed using the bit wise
operators '&', '|', '^', '~', '<<', '>>'.
However, there is a simpler method
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 256
bits
C offers an alternative by using a structure, where
each component has a length of one bit
???
struct eightbits
{ unsigned int bit0 : 1;
unsigned int bit1 : 1;
unsigned int bit2 : 1;
unsigned int bit3 : 1;
unsigned int bit4 : 1;
unsigned int bit5 : 1;
unsigned int bit6 : 1;
unsigned int bit7 : 1;
};
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 257
bits
The data type of the bit field variable is int.
If all variables do not fit into an int, the structure
will be extended to the next int.
The number after the colon is the number of bits
for that variable
struct other_eightbits
{ unsigned int bit0 : 1;
unsigned int bit1 : 1;
unsigned int unused : 4;
unsigned int bit3 : 1;
unsigned int bit7 : 1;
};
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 258
bits
A colon without a component name can be
used
If the bit length is 0, the bit field is forced to
the next int.
struct
{ unsigned int bit0 : 1;
unsigned int bit1 : 1;
: 4;
unsigned int bit3 : 1;
unsigned int bit7 : 1;
: 0;
}bits;
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 259
bits
Accessing the bits is similar to accessing
any other members of structures
struct eightbits errorFlags
, semaphores ;
errorFlags.bit0 = 0; /* {0, 1} */
#define semaphoreFifo semaphores.bit1;
if(semaphoreFifo == 1)
LATBbits.LATB0 = ~LATBbits.LATB0;
©2007 Microchip Technology Incorporated. All Rights Reserved. 4079 EPC Slide 260
The Microchip name and logo, the Microchip logo, Accuron, dsPIC, KeeLoq,
KeeLoq logo, microID, MPLAB, PIC, PICmicro, PICSTART, PRO MATE, rfPIC and
SmartShunt are registered trademarks of Microchip Technology Incorporated in the
U.S.A. and other countries.
AmpLab, FilterLab, Linear Active Thermistor, Migratable Memory, MXDEV, MXLAB,
SEEVAL, SmartSensor and The Embedded Control Solutions Company are
registered trademarks of Microchip Technology Incorporated in the U.S.A.
Analog-for-the-Digital Age, Application Maestro, CodeGuard, dsPICDEM,
dsPICDEM.net, dsPICworks, dsSPEAK, ECAN, ECONOMONITOR, FanSense,
FlexROM, fuzzyLAB, In-Circuit Serial Programming, ICSP, ICEPIC, Mindi, MiWi,
MPASM, MPLAB Certified logo, MPLIB, MPLINK, PICkit, PICDEM, PICDEM.net,
PICLAB, PICtail, PowerCal, PowerInfo, PowerMate, PowerTool, REAL ICE, rfLAB,
Select Mode, Smart Serial, SmartTel, Total Endurance, UNI/O, WiperLock and ZENA
are trademarks of Microchip Technology Incorporated in the U.S.A. and other
countries.
SQTP is a service mark of Microchip Technology Incorporated in the U.S.A.
All other trademarks mentioned herein are property of their respective companies.
Trademarks