programacion en c para pic mplaide

Upload: jose-hein

Post on 02-Jun-2018

230 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/10/2019 programacion en c para pic mplaide

    1/443

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 11421 CPL

    Introduction to theC Programming Language

    Au th or: Rob Os tap iu k

    Microchip Technology Inc.

  • 8/10/2019 programacion en c para pic mplaide

    2/443

    AgendaDay One - Morning

    Using C in an embedded environment

    CommentsVariables, identifiers and data types

    Literal constants

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 21421 CPL

    Symbolic constants

    printf() Library Function

    Operators

  • 8/10/2019 programacion en c para pic mplaide

    3/443

    AgendaDay One Afternoon

    Expressions and statements

    Making decisionsLoops

    Functions

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 31421 CPL

    Multi-File projects & storage class

    specifiers

  • 8/10/2019 programacion en c para pic mplaide

    4/443

    AgendaDay Two

    Arrays

    Data pointersFunction pointers

    Structures

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 41421 CPL

    Unions

    Bit fields

    EnumerationsMacros with #define

  • 8/10/2019 programacion en c para pic mplaide

    5/443

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 51421 CPL

    Using C in an Embedded

    Environment

  • 8/10/2019 programacion en c para pic mplaide

    6/443

    Just the Facts

    C was developed in 1972 in order to write

    the UNIX operating system

    C is more "low level" than other high level

    languages (good for MCU programming)

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 61421 CPL

    C is supported by compilers for a widevariety of MCU architectures

    C can do almostanything assembly

    language can do

    C is usually easier and faster for writing

    code than assembly language

  • 8/10/2019 programacion en c para pic mplaide

    7/443

    Busting the MythsThe truth shall set you free

    C is not as portable between architectures

    or compilers as everyone claims

    ANSI language features ARE portable

    Processor specific libraries are NOT portable

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 71421 CPL

    Processor specific code (peripherals, I/O,interrupts, special features) are NOT portable

    C is NOT as efficient as assembly

    A goodassembly programmer can usual lydobetter than the compiler, no matter what the

    optimization level C WILL use more memory

  • 8/10/2019 programacion en c para pic mplaide

    8/443

    Busting the MythsThe truth shall set you free

    There is NO SUCH THING as self

    documenting code despite what many C

    proponents will tell you

    C makes it possible to write very confusing

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 81421 CPL

    code contests (www.ioccc.org)

    Not every line needs to be commented, but

    most b locksof code should be

    Because of many shortcuts available, C is

    not always friendly to new users hence

    the need for comments!

  • 8/10/2019 programacion en c para pic mplaide

    9/443

    Development Tools Data Flow

    C CompilerC Source Files

    Assembly Source Files

    Assembly Source Files

    Compiler

    DriverProgram

    Assembler

    (.asm or .s)

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 91421 CPL

    .a Linker

    Archiver(Librarian)

    MPLAB IDEDebug Tool

    Object

    Files

    Object File Libraries

    (Archives)

    Linker ScriptCOFF

    Debug File

    Executable

    Memory Map

    (.asm or .s)

    (.lib or .a)

    (.lkr or .gld)

  • 8/10/2019 programacion en c para pic mplaide

    10/443

    Development Tools Data Flow

    C Compiler

    C Source File C Header FilePreprocessor .h.c

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 101421 CPL

    Compiler

    .sAssembly Source File

  • 8/10/2019 programacion en c para pic mplaide

    11/443

    C Runtime Environment

    C Compiler sets up a runtime environment

    Allocates space for stack

    Initializes stack pointer

    Allocates space for heap

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 111421 CPL

    Copies values from Flash/ROM to variables inRAM that were declared with initial values

    Clear uninitialized RAM

    Disable all interruptsCall main() function (where your code starts)

  • 8/10/2019 programacion en c para pic mplaide

    12/443

    C Runtime Environment

    Runtime environment setup code is

    automatically linked into application by

    most PICMCU compiler suites

    Usual lycomes from either:

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 121421 CPL

    C30: crt0.s / crt0.o (crt = C RunTime)C18: c018.c / c018.o

    User modifiable if absolutely necessary

    Details will be covered in compiler specific

    classes

  • 8/10/2019 programacion en c para pic mplaide

    13/443

    Example

    Fundamentals of CA Simple C Program

    #include

    #define PI 3.14159

    Header File

    Constant Declaration

    (Text Substitution Macro)

    Preprocessor

    Directives

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 131421 CPL

    int main(void){

    float radius, area;

    //Calculate area of circleradius = 12.0;area = PI * radius * radius;printf("Area = %f", area);

    }

    Function

    Variable Declarations

    Comment

  • 8/10/2019 programacion en c para pic mplaide

    14/443

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 141421 CPL

    Comments

  • 8/10/2019 programacion en c para pic mplaide

    15/443

    Definition

    Comments

    CommentsComments areare usedused toto documentdocument aa program'sprogram's functionalityfunctionality

    andand toto explainexplain whatwhat aa particularparticular blockblock oror lineline ofof codecode doesdoes..CommentsComments areare ignoredignored byby thethe compiler,compiler, soso youyou cancan typetypeanythinganything youyou wantwant intointo themthem..

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 151421 CPL

    Two kinds of comments may be used:Block Comment

    /* This is a comment */Single Line Comment

    // This is also a comment

  • 8/10/2019 programacion en c para pic mplaide

    16/443

    CommentsUsing Block Comments

    Block comments:

    Begin with /*/* and end with */*/

    May span multiple lines

    ****************************************************************************************************************

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 161421 CPL

    * Program: hello.c* Program: hello.c* Author: R. Ostapiuk* Author: R. Ostapiuk********************************************************/********************************************************/#i nc l ude#i nc l ude

    /* Function: main() *//* Function: main() */intintmainmain((voidvoid)){{printfprintf((Hello, world!Hello, world!\\nn);); /* Display Hello, world! *//* Display Hello, world! */}}

  • 8/10/2019 programacion en c para pic mplaide

    17/443

    CommentsUsing Single Line Comments

    Single line comments:

    Begin with //// and run to the end of the line

    May notspan multiple lines

    ==============================================================================================================

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 171421 CPL

    // Program: hello.c// Program: hello.c// Author: R. Ostapiuk// Author: R. Ostapiuk//=======================================================//=======================================================#i nc l ude#i nc l ude

    // Function: main()// Function: main()intintmainmain((voidvoid)){{printfprintf((Hello, world!Hello, world!\\nn);); // Display Hello, world!// Display Hello, world!}}

  • 8/10/2019 programacion en c para pic mplaide

    18/443

    CommentsNesting Comments

    Block comments may not be nested within

    other delimited comments

    Single line comments may be nested

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 181421 CPL

    /*/*c ode her ec ode her e // Comment within a comment// Comment within a comment

    */*/

    /*/*c ode her ec ode her e /* Comment within a comment *//* Comment within a comment */c ode her ec ode her e /* Comment within a oops! *//* Comment within a oops! */

    */*/

    Example: Delimited comment within a delimited comment.Example: Delimited comment within a delimited comment.

    Delimiters dont match up as intended!Delimiters dont match up as intended!

    Dangling delimiter causes compile errorDangling delimiter causes compile error

  • 8/10/2019 programacion en c para pic mplaide

    19/443

    CommentsBest Practices

    /********************************************************/********************************************************* Program: hello.c* Program: hello.c* Author: R. Ostapiuk* Author: R. Ostapiuk

    ********************************************************/********************************************************/#i nc l ude#i nc l ude

    /********************************************************/********************************************************

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 191421 CPL

    unc on: ma nunc on: ma n

    ********************************************************/********************************************************/intintmainmain((voidvoid)){{/*/*int i;int i; // Loop count variable// Loop count variable

    char *p; // Pointer to text stringchar *p; // Pointer to text string*/*/

    printfprintf((Hello, world!Hello, world!\\nn);); // Display Hello, world!// Display Hello, world!}}

  • 8/10/2019 programacion en c para pic mplaide

    20/443

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 201421 CPL

    Variables, Identifiers

    and Data Types

  • 8/10/2019 programacion en c para pic mplaide

    21/443

    Example

    Variables and Data Types

    A Simple C Program

    #include

    #define PI 3.14159

    int main(void)

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 211421 CPL

    Variable Declarations

    Types

    Variablesin use

    {float radius, area;

    //Calculate area of circleradius = 12.0;

    area = PI * radius * radius;printf("Area = %f", area);

    }

  • 8/10/2019 programacion en c para pic mplaide

    22/443

    Variables

    A variable may be thought of as a container that

    Definition

    AA variablevariable isis aa namename thatthat representsrepresents oneone or or moremore

    memorymemory locationslocations usedused toto holdhold programprogram datadata..

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 221421 CPL

    intmyVariable;

    myVariable = 5;

    55

  • 8/10/2019 programacion en c para pic mplaide

    23/443

    Variables

    015 Data Memory (RAM)

    Variables are names for

    storage locations in

    memory

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 231421 CPL

    4116

    5.74532370373175

    10-44

    n warp_ ac or;

    float length;

    char first_letter; A

  • 8/10/2019 programacion en c para pic mplaide

    24/443

    Variables

    015 Data Memory (RAM)

    Variable declarations

    consist of a unique

    identifier (name)

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 241421 CPL

    float length;

    char first_letter;

    n warp_ ac or; 4116

    5.74532370373175

    10-44

    A

  • 8/10/2019 programacion en c para pic mplaide

    25/443

    Variables

    015 Data Memory (RAM)

    and a data type

    Determines size

    Determines how valuesare interpreted

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 251421 CPL

    float length;

    char first_letter;

    n warp_ ac or; 4116

    5.74532370373175

    10-44

    A

  • 8/10/2019 programacion en c para pic mplaide

    26/443

    Example of Identifiers in a Program

    Identifiers

    Names given to program elements:

    Variables, Functions, Arrays, OtherElements

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 261421 CPL

    .

    #define PI 3.14159

    int main(void){

    float radius, area;

    //Calculate area of circleradius = 12.0;area = PI * radius * radius;printf("Area = %f", area);

    }

  • 8/10/2019 programacion en c para pic mplaide

    27/443

    Identifiers

    Valid characters in identifiers:

    I d e n t i f i e rFirst Character Remainin Characters

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 271421 CPL

    Case sensitive!Only first 31 characters significant*

    _ (underscore)A to Z

    a to z

    _ (underscore)A to Z

    a to z

    0 to 9

  • 8/10/2019 programacion en c para pic mplaide

    28/443

    ANSI C Keywords

    autobreak

    casechar

    doubleelse

    enumextern

    intlong

    registerreturn

    structswitch

    typedefunion

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 281421 CPL

    continuedefault

    do

    forgoto

    if

    signedsizeof

    static

    voidvolatile

    whileSome compiler implementations may define

    additional keywords

  • 8/10/2019 programacion en c para pic mplaide

    29/443

    Data Types

    Fundamental Types

    Type Description Bits

    charchar

    intintfloatfloatdoubledouble

    single charactersingle character

    integerinteger

    single precision floating point numbersingle precision floating point number

    double precision floating point numberdouble precision floating point number

    1616

    88

    3232

    6464

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 291421 CPL

    The size of an int varies from compiler to compiler MPLAB C30 int is 16 bits

    MPLAB C18 int is 16 bits CCS PCB, PCM & PCH int is 8 bits HI-TECH PICC Compiler int is 16 bits

  • 8/10/2019 programacion en c para pic mplaide

    30/443

    Data Type Qualifiers

    Modified Integer Types

    Qualifiers: unsigned, signed, short and long

    Qualified Type Min Max Bits

    unsignedcharchar, signedchar

    unsigned shorti nt

    0

    -128

    0

    255

    127

    65535

    8

    8

    16

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 301421 CPL

    shorti nt, signed short ntunsignedi nt

    int, signedi ntunsigned longi nt

    longi nt, signed longi ntunsigned long longi nt

    long longi nt,signed long longi nt

    -32768

    0

    -32768

    0

    -231

    0

    -263

    32767

    65535

    32767

    231-1

    263-1

    232-1

    264-1

    16

    16

    16

    32

    64

    32

    64

  • 8/10/2019 programacion en c para pic mplaide

    31/443

    Data Type Qualifiers

    Modified Floating Point Types

    Qualified Type Absolute Min Bits

    floatfloat

    doubledouble

    long doublelong double

    ~10~10--44.8544.85

    ~10~10--44.8544.85

    ~10~10--323.3323.3

    3232

    3232

    6464

    Absolute Max

    ~10~1038.5338.53

    ~10~1038.5338.53

    ~10~10308.3308.3

    (1)(1)

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 311421 CPL

    MPLAB C30: (1)double is equivalent to longdouble if fno-short-double is used

    MPLAB C30 Uses the IEEE-754 Floating Point Format

    MPLAB C18 Uses a modified IEEE-754 Format

  • 8/10/2019 programacion en c para pic mplaide

    32/443

    Variables

    How to Declare a Variable

    A variable must be declared before it can beused

    Syntax

    t y pet y pei dent i f i eri dent i f i er11, i dent i f i er, i dent i f i er22, , i dent i f i e r, , i dent i f i e rnn;;

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 321421 CPL

    allocate and how the values should be handled

    Example

    intint xx,, yy,, zz;;floatfloatwarpFactorwarpFactor;;charchar text_buffer[10]text_buffer[10];;unsignedunsignedindexindex;;

  • 8/10/2019 programacion en c para pic mplaide

    33/443

    Syntax

    Variables

    How to Declare a Variable

    Variables may be declared in a few ways:

    t y pet y pei dent i f i eri dent i f i er;;

    One declaration on a lineOne declaration on a line

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 331421 CPL

    t y pet y pei dent i f i eri dent i f i er ==I n i t i a l Val ueI n i t i al Va l ue;;

    t y pet y pei den t i f i eri den t i f i er11,, i dent i f i eri dent i f i er22,, i dent i f i eri dent i f i er33;;

    t y pet y pei den t i f i eri den t i f i er11 ==Va l ueVa l ue11,, i dent i f i eri dent i f i er22 ==Va l ueVa l ue22;;

    One declaration on a line with an initial valueOne declaration on a line with an initial value

    Multiple declarations of the same type on a lineMultiple declarations of the same type on a line

    Multiple declarations of the same type on a line with initial valuesMultiple declarations of the same type on a line with initial values

  • 8/10/2019 programacion en c para pic mplaide

    34/443

    Examples

    Variables

    How to Declare a Variable

    unsigned intunsigned int xx;;

    unsignedunsignedyy == 1212;;intint aa,,bb,, cc;;lon intlon intm Varm Var == 0x123456780x12345678;;

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 341421 CPL

    longlong zz;;charchar firstfirst == 'a''a',, secondsecond,, thirdthird == 'c''c';;floatfloatbig_numberbig_number == 6.02e+236.02e+23;;

    It is customary for variable names to be spelled using "camel case", where the initial letter

    is lower case. If the name is made up of multiple words, all words after the first will start

    with an upper case letter (e.g. myLongVarName).

  • 8/10/2019 programacion en c para pic mplaide

    35/443

    Variables

    How to Declare a Variable

    Sometimes variables (and other program

    elements) are declared in a separate file

    called a header file

    Header file names customarily end in .h

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 351421 CPL

    Header files are associated

    with a program through the

    #include directive

    MyProgram.h

    MyProgram.c

  • 8/10/2019 programacion en c para pic mplaide

    36/443

    #include Directive

    Three ways to use the #include directive:

    Syntax

    #include#includeLook for file in the compiler search pathLook for file in the compiler search path

    The com iler search ath usuall includes the com iler's directorThe com iler search ath usuall includes the com iler's director

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 361421 CPL

    and all of its subdirectories.and all of its subdirectories.

    For example: C:For example: C:\\Program FilesProgram Files\\MicrochipMicrochip\\MPLAB C30MPLAB C30\\*.**.*

    #include#include file.hfile.h

    Look for file in project directory onlyLook for file in project directory only

    #include#include c:c:\\MyProjectMyProject\\file.hfile.hUse specific path to find include fileUse specific path to find include file

  • 8/10/2019 programacion en c para pic mplaide

    37/443

    main.h main.c

    #include Directivemain.h Header File and main.c Source File

    unsigned intunsigned int a;a;unsigned intunsigned intb;b;unsigned intunsigned int c;c;

    #include#include "main.h""main.h"

    intintmain(main(voidvoid))

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 371421 CPL

    a =a = 55;;b =b = 22;;c = a+b;c = a+b;

    }}

    The contents of main.hThe contents of main.h

    areare effectivelyeffectivelypasted intopasted into

    main.c starting at themain.c starting at the#include#include directives linedirectives line

  • 8/10/2019 programacion en c para pic mplaide

    38/443

    main.c

    #include DirectiveEquivalent main.c File

    unsigned intunsigned int a;a;unsigned intunsigned intb;b;unsigned intunsigned int c;c;

    After the preprocessor

    runs, this is how the

    compiler sees themain.c file

    The contents of the

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 381421 CPL

    Equivalent main.c fileEquivalent main.c filewithoutwithout #include#include

    intintmain(main(voidvoid)){{

    a =a = 55;;b =b = 22;;

    c = a+b;c = a+b;}}

    header file arentactual lycopied to your

    main source file, but it

    will behave as iftheywere copied

  • 8/10/2019 programacion en c para pic mplaide

    39/443

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 391421 CPL

    Lab Exercise 1

    Variables and Data Types

  • 8/10/2019 programacion en c para pic mplaide

    40/443

    Lab 01Variables and Data Types

    Open the projects workspace:

    On the lab PCOn the lab PC

    C:C:\\MastersMasters\\14211421\\Lab01Lab01\\Lab01.mcwLab01.mcw

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 401421 CPL

    1Open MPLABOpen MPLAB IDE and selectIDE and select OpenOpen

    WorkspaceWorkspace from thefrom the FileFile menu.menu.Open the file listed above.Open the file listed above.

    If you already have a project openIf you already have a project open

    in MPLAB IDE, close it byin MPLAB IDE, close it byselectingselecting Close WorkspaceClose Workspace fromfrom

    thethe FileFile menu before opening amenu before opening anew one.new one.

    L b 01

  • 8/10/2019 programacion en c para pic mplaide

    41/443

    Lab 01Variables and Data Types

    Compile and run the code:

    Compile (Build All)Compile (Build All) RunRun2 3 HaltHalt4

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 411421 CPL

    2 Click on theClick on the Build AllBuild All button.button.

    3 If no errors are reported,If no errors are reported,

    click on theclick on the RunRun button.button.

    4 Click on theClick on the HaltHalt button.button.

    L b 01

  • 8/10/2019 programacion en c para pic mplaide

    42/443

    Lab 01Variables and Data Types

    Expected Results (1):

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 421421 CPL

    5 TheThe SIMSIM UartUart11 windowwindow shouldshould showshow thethe texttext thatthat

    isis outputoutput byby thethe program,program, indicatingindicating thethe sizessizes ofofCsCs datadata typestypes inin bytesbytes..

    L b 01

  • 8/10/2019 programacion en c para pic mplaide

    43/443

    Lab 01Variables and Data Types

    Expected Results (2):

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 431421 CPL

    6 TheThe watchwatch windowwindow shouldshould showshow thethe valuesvalues whichwhich

    areare storedstored inin thethe variablesvariables andand makemake itit easiereasier totovisualizevisualize howhow muchmuch spacespace eacheach oneone requiresrequires inin

    datadata memorymemory (RAM)(RAM)..

    L b 01

  • 8/10/2019 programacion en c para pic mplaide

    44/443

    0x08A80x08A80x08A90x08A9

    Lab 01Variables and Data Types

    0000

    323232

    0x08AA0x08AA

    0x08AC0x08AC

    0x08AE0x08AE

    0x08AB0x08AB

    0x08AD0x08AD

    0x08AF0x08AF

    charcharshort intshort intintint

    Variables in MemoryVariables in Memory71616--bit Data Memorybit Data Memory

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 441421 CPL

    00004200

    4200

    32004800

    4800

    0x08B00x08B00x08B20x08B2

    0x08B40x08B4

    0x08B60x08B6

    0x08B80x08B8

    0x08BA0x08BA

    0x08BC0x08BC

    0x08B10x08B10x08B30x08B3

    0x08B50x08B5

    0x08B70x08B7

    0x08B90x08B9

    0x08BB0x08BB

    0x08BD0x08BD

    long intlong int

    floatfloat

    doubledouble

    MultiMulti--byte valuesbyte values

    stored in "Littlestored in "Little

    Endian" formatEndian" format

    on PICon PICmicrocontrollersmicrocontrollers

    Lab 01

  • 8/10/2019 programacion en c para pic mplaide

    45/443

    Lab 01Variables and Data Types

    What does the code do?

    START

    Declare Constant #define CONSTANT1 50

    Example lines of code from the demo program:

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 451421 CPL

    Initialize Variables

    Print Variable

    Sizes

    Loop

    Forever

    intVariable = CONSTANT1;

    printf("\nAn integer variablerequires %d bytes.",

    sizeof(int));

    while(1);

    Lab 01

  • 8/10/2019 programacion en c para pic mplaide

    46/443

    Lab 01Conclusions

    Variables must be declared before used

    Variables must have a data typeData type determines memory use

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 461421 CPL

    Most efficient data types:int on 16-bit architectures

    char on 8-bit architectures (if int is 16-bit)

    Don't use float/double unless you really

    need them

  • 8/10/2019 programacion en c para pic mplaide

    47/443

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 471421 CPL

    Literal Constants

    A Simple C Program

  • 8/10/2019 programacion en c para pic mplaide

    48/443

    Example

    unsigned intunsigned int aa;;unsigned intunsigned int cc;;#define#definebb 22

    A Simple C ProgramLiteral Constants

    Literal

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 481421 CPL

    voidvoidmainmain((voidvoid)){{

    aa == 55;;

    cc == aa ++bb;;printfprintf(("a=%d, b=%d, c=%d"a=%d, b=%d, c=%d\\n"n",, aa,,bb,, cc););}}

    Literal

    Lit l C t t

  • 8/10/2019 programacion en c para pic mplaide

    49/443

    Literal Constants

    Definition

    AA literalliteral oror aa literalliteral constantconstant isis aa value,value, suchsuch asas aanumber,number, charactercharacter oror string,string, whichwhich maymay bebe assignedassigned toto aa

    variablevariable oror aa constantconstant.. ItIt maymay alsoalso bebe usedused directlydirectly asas aafunctionfunction parameterparameter oror anan operandoperand inin anan expressionexpression..

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 491421 CPL

    era s

    Are "hard coded" values

    May be numbers, characters or strings

    May be represented in a number of formats(decimal, hexadecimal, binary, character, etc.)

    Always represent the same value (5 alwaysrepresents the quantity five)

    Constant vs Literal

  • 8/10/2019 programacion en c para pic mplaide

    50/443

    Constant vs. LiteralWhat's the difference?

    Terms are used interchangeably in most

    programming literature

    A literal is a constant, but a constant is nota literal

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 501421 CPL

    #defineMAXINT 32767const intMAXINT = 32767;

    For purposes of this presentation:

    Constants are labels that represent a literal

    Literals are values, often assigned to symbolic

    constants and variables

    Lit l C t t

  • 8/10/2019 programacion en c para pic mplaide

    51/443

    Literal Constants

    Four basic types of literals:

    Integer

    Floating Point

    Character

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 511421 CPL

    String

    Integer and Floating Point are numer ic

    typeconstants:

    Commas and spaces are not allowedValue cannot exceed type bounds

    May be preceded by a minus sign

    Integer Literals

  • 8/10/2019 programacion en c para pic mplaide

    52/443

    Integer LiteralsDecimal (Base 10)

    Cannot start with 0 (except for 0 itself)

    Cannot include a decimal point

    Valid Decimal Integers:

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 521421 CPL

    Invalid Decimal Integers:-

    32,767 25.0 1 024 0552

    Integer Literals

  • 8/10/2019 programacion en c para pic mplaide

    53/443

    Integer LiteralsHexadecimal (Base 16)

    Must begin with 0x or 0X (thats zero-x)

    May include digits 0-9 and A-F / a-f

    Valid Hexadecimal Integers:

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 531421 CPL

    Invalid Hexadecimal Integers:x x x x

    0x5.3 0EA12 0xEG 53h

    Integer Literals

  • 8/10/2019 programacion en c para pic mplaide

    54/443

    Integer LiteralsOctal (Base 8)

    Must begin with 0 (zero)

    May include digits 0-7Valid Octal Integers:

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 541421 CPL

    Invalid Octal Integers:

    05.3 0o12 080 53o

    While Octal is still part of the ANSI specification, almost noWhile Octal is still part of the ANSI specification, almost no

    one uses it anymore.one uses it anymore.

    Integer Literals

  • 8/10/2019 programacion en c para pic mplaide

    55/443

    Integer LiteralsBinary (Base 2)

    Must begin with 0b or 0B (thats zero-b)

    May include digits 0 and 1

    Valid Binary Integers:

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 551421 CPL

    Invalid Binary Integers:

    0b1.0 01100 0b12 10bANSI C doesANSI C does notnotspecify a format for binary integer literals.specify a format for binary integer literals.

    However, this notation is supported by most compilers.However, this notation is supported by most compilers.

    Integer Literals

  • 8/10/2019 programacion en c para pic mplaide

    56/443

    Integer LiteralsQualifiers

    Like variables, literals may be qualified

    A suffix is used to specify the modifier

    U or u for unsigned: 25u

    L or l for lon : 25L

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 561421 CPL

    'F' or 'f' for float: 10f or 10.25FSuffixes may be combined: 0xF5UL

    Note: U must precede L

    Numbers without a suffix are assumed to

    be signed and short

    Floating Point Literals

  • 8/10/2019 programacion en c para pic mplaide

    57/443

    gDecimal (Base 10)

    Like decimal integer literals, but

    decimal point is allowed

    e notation is used to specify

    n

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 571421 CPL

    Valid Floating Point Literals:

    Invalid Floating Point Literals:

    2.56e-5 10.4378 48e8 0.5 10f

    0x5Ae-2 02.41 F2.33

    Character Literals

  • 8/10/2019 programacion en c para pic mplaide

    58/443

    Character Literals

    Specified within single quotes (')

    May include any single printable characterMay include any single non-printable

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 581421 CPL

    c arac er us ng escape sequences e.g.

    '\0' = NUL) (also called digraphs)

    Valid Characters: 'a', 'T', '\n', '5',

    '@', ' ' (space)

    Invalid Characters: 'me', '23', '''

    String Literals

  • 8/10/2019 programacion en c para pic mplaide

    59/443

    String Literals

    Specified within double quotes (")

    May include any printable or non-printable

    characters (using escape sequences)

    Usually terminated by a null character \0

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 591421 CPL

    Valid Strings: "Microchip", "Hi\n","PIC", "2500","[email protected]","He said, \"Hi\""

    Invalid Strings: "He said, "Hi""

    String Literals

  • 8/10/2019 programacion en c para pic mplaide

    60/443

    gDeclarations

    Strings are a special case of arrays

    If declared without a dimension, the null

    character is automatically appended to theend of the string:

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 601421 CPL

    charchar colorcolor[[33] =] = "RED""RED";;

    Is stored as:Is stored as:

    colorcolor[[00] =] = 'R''R'colorcolor[[11] =] = 'E''E'colorcolor[[22] =] = 'D''D'

    NOTNOT a complete stringa complete string no 'no '\\0' at end0' at end

    charchar colorcolor[] =[] = "RED""RED";;

    Is stored as:Is stored as:

    colorcolor[[00] =] = 'R''R'colorcolor[[11] =] = 'E''E'colorcolor[[22] =] = 'D''D'colorcolor[[33] =] = ''\\0'0'

    Example 1 Wrong Way Example 2 Right Way

    String Literals

  • 8/10/2019 programacion en c para pic mplaide

    61/443

    gHow to Include Special Characters in Strings

    Escape Sequence Character ASCII Value

    \\aa

    \\bb\\tt\\nn

    BELL (alert)BELL (alert)

    BackspaceBackspaceHorizontal TabHorizontal Tab

    Newline (Line Feed)Newline (Line Feed)

    77

    8899

    1010

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 611421 CPL

    vv

    \\ff\\rr\\""\\''\\??\\\\\\00

    Vertical TabVertical Tab

    Form FeedForm Feed

    Carriage ReturnCarriage Return

    Quotation Mark (")Quotation Mark (")

    Apostrophe/Single Quote (')Apostrophe/Single Quote (')Question Mark (?)Question Mark (?)

    Backslash (Backslash (\\))

    NullNull

    1212

    1313

    3434

    3939

    6363

    9292

    00

    String Literals

  • 8/10/2019 programacion en c para pic mplaide

    62/443

    Example

    How to Include Special Characters in Strings

    This string includes a newline character

    charcharmessagemessage[] =[] = "Please enter a command"Please enter a command\\n"n"

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 621421 CPL

    scape sequences may e nc u e n a

    string like any ordinary character

    The backslash plus the character that

    follows it are considered a singlecharacter and have a single ASCII value

  • 8/10/2019 programacion en c para pic mplaide

    63/443

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 631421 CPL

    Symbolic Constants

    Symbolic Constants

  • 8/10/2019 programacion en c para pic mplaide

    64/443

    Symbolic Constants

    Definition

    AA constantconstant oror aa symbolicsymbolic constantconstant isis aa labellabel thatthatrepresentsrepresents aa literalliteral.. AnywhereAnywhere thethe labellabel isis encounteredencountered

    inin code,code, itit willwill bebe interpretedinterpreted asas thethe valuevalue ofof thethe literalliteral ititrepresentsrepresents..

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 641421 CPL

    ons an s

    Once assigned, never change their value

    Make development changes easy

    Eliminate the use of "magic numbers"

    Two types of constantsText Substitution Labels

    Variable Constants (!!??)

    Symbolic ConstantsC t t V i bl U i

  • 8/10/2019 programacion en c para pic mplaide

    65/443

    Some texts on C declare constants like:

    This is not efficient for an embedded

    Constant Variables Using const

    Example

    constconst floatfloat PIPI == 3.1415933.141593;;

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 651421 CPL

    sys em: var a e s a oca e n program

    memory, but it cannot be changed due tothe const keyword

    This is not the traditional use of constIn the vast majority of cases, it is better touse #define for constants

    Symbolic ConstantsT t S b tit ti L b l U i #d fi

  • 8/10/2019 programacion en c para pic mplaide

    66/443

    Text Substitution Labels Using #define

    Defines a text substitution labelSyntax

    #define#definel abel t ex tl abel t ex tEach instance of l abelwill be replaced with t ex tby the

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 661421 CPL

    Example

    #define#define PIPI 3.141593.14159

    #define#definemolmol 6.02E236.02E23#define#defineMCUMCU "PIC24FJ128GA010""PIC24FJ128GA010"#define#define COEF 2 * PICOEF 2 * PI

    a e

    No memory is used in the microcontroller

    Symbolic Constants#d fi Gotchas

  • 8/10/2019 programacion en c para pic mplaide

    67/443

    Note: a #define directive is NEVER

    terminated with a semi-colon (;), unless

    you want that to be part of the textsubstitution.

    #define Gotchas

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 671421 CPL

    Example

    #define#defineMyConstMyConst 55;;

    cc ==MyConstMyConst ++ 33;;

    cc == 55; +; + 33;;

    Symbolic ConstantsInitializing Variables When Declared

  • 8/10/2019 programacion en c para pic mplaide

    68/443

    Initializing Variables When Declared

    A constant declared with const may not

    be used to initialize a global or static

    variable when it is declared (though it maybe used to initialize local variables)

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 681421 CPL

    Example

    #define#define CONSTANT1CONSTANT1 55constconst CONSTANT2CONSTANT2 == 1010;;

    intint variable1variable1 == CONSTANT1CONSTANT1;;intint variable2variable2;;// Cannot do: int variable2 = CONSTANT2// Cannot do: int variable2 = CONSTANT2

  • 8/10/2019 programacion en c para pic mplaide

    69/443

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 691421 CPL

    Lab Exercise 2

    Symbolic Constants

    Lab 02Symbolic Constants

  • 8/10/2019 programacion en c para pic mplaide

    70/443

    Symbolic Constants

    Open the projects workspace:

    On the lab PCOn the lab PC

    C:C:\\MastersMasters\\14211421\\Lab02Lab02\\Lab02.mcwLab02.mcw

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 701421 CPL

    1 Open MPLABOpen MPLAB IDE and selectIDE and select OpenOpen

    WorkspaceWorkspace from thefrom the FileFile menu.menu.Open the file listed above.Open the file listed above.

    If you already have a project openIf you already have a project open

    in MPLAB IDE, close it byin MPLAB IDE, close it byselectingselecting Close WorkspaceClose Workspace fromfrom

    thethe FileFile menu before opening amenu before opening anew one.new one.

    Lab 02Symbolic Constants

  • 8/10/2019 programacion en c para pic mplaide

    71/443

    Symbolic Constants

    Compile and run the code:

    Compile (Build All)Compile (Build All) RunRun2 3 HaltHalt4

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 711421 CPL

    2 Click on theClick on the Build AllBuild All button.button.

    3 If no errors are reported,If no errors are reported,

    click on theclick on the RunRun button.button.

    4 Click on theClick on the HaltHalt button.button.

    Lab 02Symbolic Constants

  • 8/10/2019 programacion en c para pic mplaide

    72/443

    Symbolic Constants

    Expected Results (1):

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 721421 CPL

    5 TheThe SIMSIM UartUart11 windowwindow shouldshould showshow thethe texttext thatthat

    isis outputoutput byby thethe program,program, indicatingindicating thethe valuesvalues ofofthethe twotwo symbolicsymbolic constantsconstants inin thethe codecode..

    Lab 02Symbolic Constants

  • 8/10/2019 programacion en c para pic mplaide

    73/443

    Symbolic Constants

    Expected Results (2):

    CONSTANT1CONSTANT1 hashas

    nono addressaddress

    CONSTANT2CONSTANT2 has ahas a

    program memoryprogram memory

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 731421 CPL

    6 TheThe watchwatch windowwindow shouldshould showshow thethe twotwo symbolicsymbolicconstantsconstants declareddeclared inin codecode.. CONSTANTCONSTANT11 waswasdeclareddeclared withwith #define#define,, andand thereforetherefore usesuses nono

    memorymemory.. CONSTANTCONSTANT22 waswas declareddeclared withwith constconstandand isis storedstored asas anan immutableimmutable variablevariable inin flashflash

    programprogram memorymemory..

    address ( )address ( )

    Lab 02Symbolic Constants

  • 8/10/2019 programacion en c para pic mplaide

    74/443

    Symbolic Constants

    Expected Results (3):

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 741421 CPL

    7 IfIf wewe looklook inin thethe programprogram memorymemory window,window, wewe

    cancan findfind CONSTANTCONSTANT22 whichwhich waswas createdcreated withwithconstconst atat addressaddress 00xx011011DD00 (as(as waswas shownshown inin thethe

    watchwatch window)window)

    Lab 02Symbolic Constants

  • 8/10/2019 programacion en c para pic mplaide

    75/443

    y

    Expected Results (4):

    External Symbols in Program Memory (by name):

    0x0011d0 _CONSTANT20x000e16 __Atexit0x000b9c __Closreg

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 751421 CPL

    8 IfIf wewe openopen thethe mapmap filefile (in(in thethe lablab0202 projectproject

    directory),directory), wewe cancan seesee thatthat memorymemory hashas beenbeenallocatedallocated forforCONSTANTCONSTANT22 atat 00xx011011DD00,, butbut nothingnothinghashas beenbeen allocatedallocated forforCONSTANTCONSTANT11..

    0x00057c __DNKfflush0x0012d8 __DefaultInterrupt

    CONSTANT1 does not appear anywhere in the map file

    a .map

  • 8/10/2019 programacion en c para pic mplaide

    76/443

  • 8/10/2019 programacion en c para pic mplaide

    77/443

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 771421 CPL

    printf() Library Function

    printf()Standard Library Function

  • 8/10/2019 programacion en c para pic mplaide

    78/443

    Used to write text to the "standard output"

    Normally a computer monitor or printer

    Often the UART in embedded systems

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 781421 CPL

    SIM Uart1 window in MPLAB IDE SIM

    printf()Standard Library Function

  • 8/10/2019 programacion en c para pic mplaide

    79/443

    Syntax

    printfprintf((Cont r o l St r i ngCont r o l St r i ng,, ar g1ar g1,,ar gnar gn););

    Everything printed verbatim within string except %d's,which are replaced by the argument values from the list

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 791421 CPL

    Example

    intint aa == 55,,bb == 1010;;printfprintf(("a ="a = %d%d\\nb =nb = %d%d\\n"n",, aa,,bb););

    Result:Result:

    a = 5a = 5

    b = 10b = 10

    NOTE: the 'd' in %d is the

    con vers ion character.

    (See next slide for details)

    printf()Conversion Characters for Control String

  • 8/10/2019 programacion en c para pic mplaide

    80/443

    Conversion

    Character Meaning

    %c%c%s%s%d%d%o%o

    Single characterSingle character

    String (all characters until 'String (all characters until '\\0')0')Signed decimal integerSigned decimal integer

    Unsigned octal integerUnsigned octal integer

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 801421 CPL

    uu

    %x%x%X%X%f%f%e%e%E%E%g%g%G%G

    Unsigned decimal integerUnsigned decimal integer

    Unsigned hexadecimal integer with lowercase digits (Unsigned hexadecimal integer with lowercase digits (1a5e1a5e))AsAs xx, but with uppercase digits (e.g., but with uppercase digits (e.g. 1A5E1A5E))

    Signed decimal value (floating point)Signed decimal value (floating point)

    Signed decimal with exponent (e.g.Signed decimal with exponent (e.g. 1.26e1.26e--55))

    AsAs ee, but uses, but uses EE for exponent (e.g.for exponent (e.g. 1.26E1.26E--55))

    AsAs ee oror ff, but depends on size and precision of value, but depends on size and precision of value

    AsAs gg, but uses, but uses EE for exponentfor exponent

    printf()Gotchas

  • 8/10/2019 programacion en c para pic mplaide

    81/443

    The value displayed is interpreted entirely

    by the formatting string:

    printf("ASCII = %d", 'a');will output:ASCII = 97

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 811421 CPL

    printf("Value = %d", 6.02e23);will output:Value = 26366

    Incorrect results may be displayed if the

    format type doesn't match the actual data

    type of the argument

    printf()Useful Format String Examples for Debugging

  • 8/10/2019 programacion en c para pic mplaide

    82/443

    Print a 16-bit hexadecimal value with a

    "0x" prefix and leading zeros if necessary

    to fill a 4 hex digit value:printf("Address of x =printf("Address of x = %#06x%#06x\\n", x_ptr);n", x_ptr);

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 821421 CPL

    # Specifies that a 0x or 0X should precede a hexadecimal value (hasother meanings for different conversion characters)

    06 Specifies that 6 characters must be output (including 0x prefix),

    zeros will be filled in at left if necessary

    x Specifies that the output value should be expressed as a

    hexadecimal integer

    printf()Useful Format String Examples for Debugging

  • 8/10/2019 programacion en c para pic mplaide

    83/443

    Same as previous, but force hex letters to

    uppercase while leaving the 'x' in '0x'

    lowercase:printf("Address of x = 0xprintf("Address of x = 0x%04X%04X\\n", x_ptr);n", x_ptr);

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 831421 CPL

    04 Specifies that 4 characters must be output (no longer including 0xprefix since that is explicitly included in the string), zeros will be

    filled in at left if necessary

    X Specifies that the output value should be expressed as ahexadecimal integer with uppercase A-F

  • 8/10/2019 programacion en c para pic mplaide

    84/443

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 841421 CPL

    Lab Exercise 3

    printf() Library Function

    Lab 03printf() Library Function

  • 8/10/2019 programacion en c para pic mplaide

    85/443

    Open the projects workspace:

    On the lab PCOn the lab PC

    C:C:\\MastersMasters\\14211421\\Lab03Lab03\\Lab03.mcwLab03.mcw

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 851421 CPL

    1 Open MPLABOpen MPLAB IDE and selectIDE and select OpenOpen

    WorkspaceWorkspace from thefrom the FileFile menu.menu.Open the file listed above.Open the file listed above.

    If you already have a project openIf you already have a project open

    in MPLAB IDE, close it byin MPLAB IDE, close it byselectingselecting Close WorkspaceClose Workspace fromfrom

    thethe FileFile menu before opening amenu before opening anew one.new one.

    Lab 03printf() Library Function

  • 8/10/2019 programacion en c para pic mplaide

    86/443

    Compile and run the code:

    Compile (Build All)Compile (Build All) RunRun2 3 HaltHalt4

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 861421 CPL

    2 Click on theClick on the Build AllBuild All button.button.

    3 If no errors are reported,If no errors are reported,

    click on theclick on the RunRun button.button.

    4 Click on theClick on the HaltHalt button.button.

    Lab 03printf() Library Function

  • 8/10/2019 programacion en c para pic mplaide

    87/443

    Expected Results (1):

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 871421 CPL

    5 TheThe SIMSIM UartUart11 windowwindow shouldshould showshow thethe texttext thatthat

    isis outputoutput byby thethe programprogram bybyprintf()printf(),, showingshowingthethe howhow valuesvalues areare printedprinted basedbased onon thethe

    formattingformatting charactercharacter usedused inin thethe controlcontrol stringstring..

    Lab 03printf() Library Function

  • 8/10/2019 programacion en c para pic mplaide

    88/443

    Expected Results (2):

    a

    25

    printfprintf(("'a' as character (c): %c"'a' as character (c): %c\\n"n",, 'a''a'););

    printfprintf(("25 as decimal (d): %d"25 as decimal (d): %d\\n"n",, 2525););

    Detailed Analysis:Detailed Analysis:Line of Code From Demo ProjectLine of Code From Demo Project OutputOutput

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 881421 CPL

    -24058printfprintf(("'Microchip' as decimal (d):"'Microchip' as decimal (d): %d%d\\n"n",, "Microchip""Microchip"););

    Microchipprintfprintf(("'Microchip' as string (s): %s"'Microchip' as string (s): %s\\n"n",, "Microchip""Microchip"););

    26366printfprintf(("6.02e23 as decimal (d):"6.02e23 as decimal (d): %d%d\\n"n",, 6.02e236.02e23););

    6.020000e+23printfprintf(("6.02e23 as exponent (e): %e"6.02e23 as exponent (e): %e\\n"n",, 6.02e236.02e23););

    16419

    2.550000

    97

    printfprintf(("2.55 as decimal (d):"2.55 as decimal (d): %d%d\\n"n",, 2.552.55););

    printfprintf(("2.55 as float (f): %f"2.55 as float (f): %f\\n"n",, 2.552.55););

    printfprintf(("'a' as decimal (d):"'a' as decimal (d): %d%d\\n"n",, 'a''a'););

    Lab 03Conclusions

  • 8/10/2019 programacion en c para pic mplaide

    89/443

    printf() has limited use in embedded

    applications themselves

    It is very useful as a debugging tool

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 891421 CPL

    can sp ay a a a mos any way you

    want

    Projects that use printf() must:

    Configure a heap (done in MPLAB IDE)

    Include the stdio.h header file

  • 8/10/2019 programacion en c para pic mplaide

    90/443

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 901421 CPL

    Operators

    OperatorsHow to Code Arithmetic Expressions

  • 8/10/2019 programacion en c para pic mplaide

    91/443

    Definition

    Operands may be variables, constants or

    AnAn arithmeticarithmetic expressionexpression isis anan expressionexpression thatthat containscontainsoneone oror moremore operandsoperands andand arithmeticarithmetic operatorsoperators..

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 911421 CPL

    A microcontroller register is usually treated asa variable

    There are 9 arithmetic operators that may

    be usedBinary Operators: +, -, *, /, %

    Unary Operators: +, -, ++, --

    OperatorsArithmetic

  • 8/10/2019 programacion en c para pic mplaide

    92/443

    ModuloModulo%%

    AdditionAddition++

    MultiplicationMultiplication**

    DivisionDivision//

    Operator ResultOperation Example

    x % yx % y

    x + yx + y

    x * yx * y

    x / yx / yRemainder ofRemainder of xx divided bydivided by yy

    Sum ofSum of xx andand yy

    Product ofProduct of xx andand yy

    Quotient ofQuotient of xx andand yy

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 921421 CPL

    NegativeNegative-- (unary)(unary)

    SubtractionSubtraction--

    PositivePositive++ (unary)(unary)

    NOTENOTE -- AnAn intint divided by andivided by an intint returns anreturns an intint::10/3 = 310/3 = 3

    Use modulo to get the remainder:Use modulo to get the remainder:

    10%3 = 110%3 = 1

    --xx

    xx -- yy

    +x+xNegative value ofNegative value of xx

    Difference ofDifference of xx andand yy

    Value ofValue of xx

    OperatorsDivision Operator

  • 8/10/2019 programacion en c para pic mplaide

    93/443

    If both operands are an integer type, the result

    will be an integer type (int, char)

    If one or both of the operands is a floating pointtype, the result will be a floating point type (float,

    double

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 931421 CPL

    Example: Integer Divide Example: Floating Point Divide

    intint aa == 1010;;intintbb == 44;;floatfloat cc;;

    cc == aa //bb;;

    intint aa == 1010;;floatfloatbb == 4.0f4.0f;;floatfloat cc;;

    cc == a / b;a / b;

    c = 2.c = 2.000000000000Because: int / intBecause: int / int intint

    c = 2.c = 2.550000000000Because: float / intBecause: float / int floatfloat

    OperatorsImplicit Type Conversion

  • 8/10/2019 programacion en c para pic mplaide

    94/443

    In many expressions, the type of one

    operand will be temporarily "promoted" to

    the larger type of the other operandExample

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 941421 CPL

    A smaller data type will be promoted to the

    largest type in the expression for the

    duration of the operation

    nn xx == ;;

    floatfloat yy == 2.02.0,, zz;;zz == xx ** yy;; // x promoted to float// x promoted to float

    OperatorsImplicit Arithmetic Type Conversion Hierarchy

  • 8/10/2019 programacion en c para pic mplaide

    95/443

    long long

    unsigned long long

    float

    double

    long double

    nverte

    dto

    press

    ion

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 951421 CPL

    char

    int

    unsigned intlong

    unsigned long

    unsigned charSma

    llertypes

    co

    larg

    esttypeine

    short

    unsigned short

    OperatorsArithmetic Expression Implicit Type Conversion

    E l i li it t i

  • 8/10/2019 programacion en c para pic mplaide

    96/443

    Expression Implicit Type Conversion Expression's Type

    Assume x is defined as:

    short x =short x = --5;5;Result

    Example implicit type conversions

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 961421 CPL

    --xx xx is promoted tois promoted to intint intint 55

    x *x * --2L2L xx is promoted tois promoted to longlongbecausebecause --2L2L is ais a longlong

    longlong 1010

    8/x8/x xx is promoted tois promoted to intint intint --11

    8%x8%x xx is promoted tois promoted to intint intint 33

    8.0/x8.0/x xx is promoted tois promoted to doubledoublebecausebecause 8.08.0 is ais a doubledouble

    doubledouble --1.61.6

  • 8/10/2019 programacion en c para pic mplaide

    97/443

    OperatorsArithmetic: Increment and Decrement

    Operator ResultOperation Example

  • 8/10/2019 programacion en c para pic mplaide

    98/443

    Operator ResultOperation Example

    DecrementDecrement----

    IncrementIncrement++++

    xx----

    ----xx

    x++x++

    ++x++x

    UseUse xx then decrementthen decrement xx by 1by 1

    DecrementDecrement xx by 1, then useby 1, then use xx

    UseUse xx then incrementthen increment xx by 1by 1

    IncrementIncrement xx by 1, then useby 1, then use xx

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 981421 CPL

    xx == 55;;yy == ((x++x++) +) + 55;;

    // y = 10// y = 10// x = 6// x = 6

    xx == 55;;yy = (= (++x++x) +) + 55;;

    // y = 11// y = 11// x = 6// x = 6

    Postfix Example Prefix Example

    Definition

    OperatorsHow to Code Assignment Statements

  • 8/10/2019 programacion en c para pic mplaide

    99/443

    Definition

    Two types of assignment statements

    AnAn assignmentassignment statementstatement isis aa statementstatement thatthat assignsassigns aavaluevalue toto aa variablevariable..

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 991421 CPL

    mp e ass gnmen

    v ar i ab l e= ex pr es s i on;The expression is evaluated and the result isassigned to the variable

    Compound assignmentv ar i ab l e= v ar i ab l e op ex pr es s i on;

    The variable appears on both sides of the =

    OperatorsAssignment

  • 8/10/2019 programacion en c para pic mplaide

    100/443

    --==

    *=*=

    AssignmentAssignment==

    +=+=xx --= y= y

    x *= yx *= y

    x = yx = y

    x += yx += yx = xx = x -- yy

    x = x * yx = x * y

    AssignAssign xx the value ofthe value of yy

    x = x + yx = x + y

    Operator ResultOperation Example

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1001421 CPL

    >>=>>=

    |=|== y

    x |= yx |= yx y

    x = x | yx = x | yx = x

  • 8/10/2019 programacion en c para pic mplaide

    101/443

    Statements with the same variable on each

    side of the equals sign:Example

    xx == xx ++ yy;;

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1011421 CPL

    May use the shortcut assignment

    operators (compound assignment):

    Example

    xx +=+= yy;; //Increment x by the value y//Increment x by the value y

    set equal to the current value ofset equal to the current value of xx plus the value ofplus the value of yy

    Example

    OperatorsCompound Assignment

  • 8/10/2019 programacion en c para pic mplaide

    102/443

    p

    intint xx == 22;; //Initial value of x is 2//Initial value of x is 2

    xx *=*= 55;; //x = x * 5//x = x * 5

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1021421 CPL

    e ore s a emen s execu e :e ore s a emen s execu e : xx ==

    After statement is executed:After statement is executed: xx = 10= 10x *= 5;x *= 5;x = (x * 5);x = (x * 5);x = (2 * 5);x = (2 * 5);x = 10;x = 10;

    Is equivalent to:Is equivalent to:

    Evaluate right side first:Evaluate right side first:

    Assign result toAssign result to xx::

    OperatorsRelational

    Operator Result (FALSE = 0 TRUE 0)Operation Example

  • 8/10/2019 programacion en c para pic mplaide

    103/443

    Operator Result (FALSE 0, TRUE 0)Operation Example

    Greater thanGreater than>>

    Less thanLess than= yx >= y

    1 if1 if xx equal toequal to yy, else 0, else 0

    1 if1 if xx not equal tonot equal to yy, else 0, else 0

    1 if1 if xx greater than or equal togreater than or equal to yy,,

    else 0else 0

    OperatorsDifference Between = and ==

    Be careful not to confuseBe careful not to confuse andand

  • 8/10/2019 programacion en c para pic mplaide

    104/443

    = is the assignment operator=

    Be careful not to confuseBe careful not to confuse == andand ====..

    They are not interchangeable!They are not interchangeable!

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1041421 CPL

    == is the 'equals to' relational operatorx == 5 tests whether the value of x is 5

    ifif ((xx ==== 55))

    {{do if value ofdo if value of xx is 5is 5

    }}

    OperatorsDifference Between = and ==

    What happens when the following code is

  • 8/10/2019 programacion en c para pic mplaide

    105/443

    Example

    What happens when the following code is

    executed?

    voidvoidmainmain((voidvoid))

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1051421 CPL

    {{

    intint xx == 22;; //Initialize x//Initialize xifif ((xx == 55)) //If x is 5,//If x is 5,{{

    printfprintf(("Hi!""Hi!");); //display "Hi!"//display "Hi!"}}

    }}

    OperatorsLogical

    Operator Result (FALSE = 0 TRUE 0)Operation Example

  • 8/10/2019 programacion en c para pic mplaide

    106/443

    Logical ORLogical OR||||

    Logical ANDLogical AND&&&&

    x || yx || y

    x && yx && y

    0 if0 if bothboth xx == 00 andand yy == 00,,else 1else 1

    1 if1 if bothboth xx 00 andand yy 00,,else 0else 0

    Operator Result (FALSE = 0, TRUE 0)Operation Example

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1061421 CPL

    Logical NOTLogical NOT!! !x!x 1 if1 if xx == 00, else 0, else 0

    In conditional expressions, any non-zero value is

    interpreted as TRUE. A value of 0 is always FALSE.

    OperatorsBitwise

    Operator Result (for each bit position)Operation Example

  • 8/10/2019 programacion en c para pic mplaide

    107/443

    p p p

    Bitwise ANDBitwise AND&&

    Bitwise ORBitwise OR||

    x & yx & y

    x | yx | y

    1, if 1 in both1, if 1 in both xx andand yy0, if 0 in0, if 0 in xx oror yy or bothor both

    1, if 1 in1, if 1 in xx oror yy or bothor both0, if 0 in both0, if 0 in both xx andand yy

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1071421 CPL

    Bitwise XORBitwise XOR^

    Bitwise NOTBitwise NOT(One's Complement)(One's Complement)

    ~~

    x ^ yx ^ y

    ~x~x

    ,,

    0, if 0 or 1 in both0, if 0 or 1 in both xx andand yy

    1, if 0 in1, if 0 in xx0, if 1 in0, if 1 in xx

    The operation is carried out on each bit ofthe first operand with each corresponding

    bit of the second operand

    OperatorsDifference Between & and &&

    Be careful not to confuseBe careful not to confuse && andand &&&&

  • 8/10/2019 programacion en c para pic mplaide

    108/443

    & is the bitwise AND operator

    Be careful not to confuseBe careful not to confuse && andand &&&&..

    They are not interchangeable!They are not interchangeable!

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1081421 CPL

    && is the logical AND operator0b1010 && 0b1101 0b0001 (TRUE)&& 1 (TRUE)

    ifif ((xx &&&& yy)){{do ifdo if xx andand yyare both TRUE (nonare both TRUE (non--zero)zero)

    }}

    OperatorsDifference Between & and &&

    What happens when each of these code

  • 8/10/2019 programacion en c para pic mplaide

    109/443

    What happens when each of these code

    fragments are executed?

    Example 1 Using A BitwiseAND Operator

    charchar xx == 0b10100b1010;;

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1091421 CPL

    Example 2 Using A LogicalAND Operator

    charchar xx == 0b10100b1010;;charchar yy == 0b01010b0101;;ifif ((xx &&&& yy))printfprintf(("Hi!""Hi!"););

    charchar yy == 0b01010b0101;;

    ifif ((xx && yy))printfprintf(("Hi!""Hi!"););

    OperatorsLogical Operators and Short Circuit Evaluation

    The evaluation of expressions in a logical

  • 8/10/2019 programacion en c para pic mplaide

    110/443

    p g

    operation stops as soon as a TRUE or

    FALSE result is knownExample

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1101421 CPL

    If we have two expressions being tested in a logical AND operation:If we have two expressions being tested in a logical AND operation:

    ex pr 1ex pr 1&&&& ex pr 2ex pr 2The expressions are evaluated from left to right. IfThe expressions are evaluated from left to right. If ex pr 1ex pr 1is 0 (FALSE), thenis 0 (FALSE), then

    ex pr 2ex pr 2would not be evaluated at all since the overall result is already knownwould not be evaluated at all since the overall result is already known

    to be false.to be false.

    ex pr 1 ex pr 2 Result0 X (0) 0

    0 X (1) 0

    1 0 0

    1 1 1

    Truth Table for AND (&&)Truth Table for AND (&&)FALSE = 0FALSE = 0

    TRUE = 1TRUE = 1

    ex pr 2ex pr 2is not evaluatedis not evaluatedin the first two casesin the first two cases

    since its value is notsince its value is not

    relevant to the result.relevant to the result.

    OperatorsLogical Operators and Short Circuit Evaluation

    The danger of short circuit evaluation

  • 8/10/2019 programacion en c para pic mplaide

    111/443

    Example

    g

    == ==

    IfIf zz = 0, then= 0, then cc willwill notnot be evaluatedbe evaluated

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1111421 CPL

    {{

    zz +=+= 55;;cc +=+= 1010;;

    }}

    It is perfectly legal in C to logically compare two assignment expressions inIt is perfectly legal in C to logically compare two assignment expressions in

    this way, though it is not usually good programming practice.this way, though it is not usually good programming practice.

    A similar problem exists when using function calls in logical operations, whichA similar problem exists when using function calls in logical operations, which

    is a very common practice. The second function may never be evaluated.is a very common practice. The second function may never be evaluated.

    Initial value ofInitial value of cc may not be correctmay not be correct

    OperatorsShift

    Operator ResultOperation Example

  • 8/10/2019 programacion en c para pic mplaide

    112/443

    Shift LeftShift Left>

    x yx >> y

    ShiftShift xx byby yy bits to the leftbits to the left

    ShiftShift xx byby yy bits to the rightbits to the right

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1121421 CPL

    x = 5; // x = 0b00000101 = 5y = x

  • 8/10/2019 programacion en c para pic mplaide

    113/443

    g g ( )

    If x is UNSIGNED (unsigned char in this case):

    x = 250; // x = 0b11111010 = 250y = x >>2; // y = 0b00111110 = 62

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1131421 CPL

    Arithmetic Shift Right (Sign Extend)If x is SIGNED (char in this case):

    x = -6; // x = 0b11111010 = -6

    y = x >>2; // y = 0b11111110 = -2

    OperatorsPower of 2 Integer Divide vs. Shift Right

    If you are dividing by a power of 2, it will

  • 8/10/2019 programacion en c para pic mplaide

    114/443

    usually be more efficient to use a right

    shift instead

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1141421 CPL

    0 0 0 0

    Works for integers or fixed point values

    y = xy = x y = x ny = x n

    1 0 1 0 >>

    1010 510

    0 0 0 0 0 1 0 1

    Right Shift

    OperatorsPower of 2 Integer Divide vs. Shift in MPLABC30

    Example: Divide by 2 Example: Right Shift by 1

    i ti t 2020 i ti t 2020

  • 8/10/2019 programacion en c para pic mplaide

    115/443

    intint xx == 2020;;intint yy;;

    yy == xx // 22;;

    intint xx == 2020;;intint yy;;

    yy == xx >>>>11;;10: y = x / 2;10: y = x / 2;00288 804000 mov.w 0x0800,0x000000288 804000 mov.w 0x0800,0x00000028A 200022 mov.w 0x2 0x00040028A 200022 mov.w 0x2 0x0004

    9: y = x >> 1;9: y = x >> 1;00282 804000 mov.w 0x0800,0x000000282 804000 mov.w 0x0800,0x000000284 DE8042 asr 0x0000 1 0x000000284 DE8042 asr 0x0000 1 0x0000

    y = 10y = 10 y = 10y = 10

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1151421 CPL

    0028C 090011 repeat #170028C 090011 repeat #170028E D80002 div.sw 0x0000,0x00040028E D80002 div.sw 0x0000,0x0004

    00290 884010 mov.w 0x0000,0x080200290 884010 mov.w 0x0000,0x0802

    00286 884010 mov.w 0x0000,0x080200286 884010 mov.w 0x0000,0x0802

    Example: Divide by 2 Example: Right Shift by 1

    intint xx == 2020;;

    OperatorsPower of 2 Integer Divide vs. Shift in MPLABC18

    intint xx == 2020;;

  • 8/10/2019 programacion en c para pic mplaide

    116/443

    10: y = x / 2;10: y = x / 2;

    0132 C08C MOVFF 0x8c, 0x8a0132 C08C MOVFF 0x8c, 0x8a0134 F08A NOP0134 F08A NOP

    intint xx == 2020;;intint yy;;

    yy == xx // 22;;9: y = x >> 1;9: y = x >> 1;0122 C08C MOVFF 0x8c, 0x8a0122 C08C MOVFF 0x8c, 0x8a0124 F08A NOP0124 F08A NOP

    intint xx == 2020;;intint yy;;

    yy == xx >>>>11;;y = 10y = 10 y = 10y = 10

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1161421 CPL

    0136 C08D MOVFF 0x8d, 0x8b0136 C08D MOVFF 0x8d, 0x8b0138 F08B NOP0138 F08B NOP013A 0E02 MOVLW 0x2013A 0E02 MOVLW 0x2013C 6E0D MOVWF 0xd, ACCESS013C 6E0D MOVWF 0xd, ACCESS013E 6A0E CLRF 0xe, ACCESS013E 6A0E CLRF 0xe, ACCESS0140 C08A MOVFF 0x8a, 0x80140 C08A MOVFF 0x8a, 0x80142 F008 NOP0142 F008 NOP0144 C08B MOVFF 0x8b, 0x90144 C08B MOVFF 0x8b, 0x90146 F009 NOP0146 F009 NOP0148 EC6B CALL 0xd6, 00148 EC6B CALL 0xd6, 0

    014A F000 NOP014A F000 NOP014C C008 MOVFF 0x8, 0x8a014C C008 MOVFF 0x8, 0x8a014E F08A NOP014E F08A NOP0150 C009 MOVFF 0x9, 0x8b0150 C009 MOVFF 0x9, 0x8b0152 F08B NOP0152 F08B NOP

    0126 C08D MOVFF 0x8d, 0x8b0126 C08D MOVFF 0x8d, 0x8b0128 F08B NOP0128 F08B NOP012A 0100 MOVLB 0012A 0100 MOVLB 0

    012C 90D8 BCF 0xfd8, 0, ACCESS012C 90D8 BCF 0xfd8, 0, ACCESS012E 338B RRCF 0x8b, F, BANKED012E 338B RRCF 0x8b, F, BANKED0130 338A RRCF 0x8a, F, BANKED0130 338A RRCF 0x8a, F, BANKED

    1616--bit Shift on 8bit Shift on 8--bit Architecturebit Architecture

    OperatorsMemory Addressing

    Operator ResultOperation Example

  • 8/10/2019 programacion en c para pic mplaide

    117/443

    SubscriptingSubscripting[][]

    Address ofAddress of&&

    IndirectionIndirection**

    x[y]x[y]

    &x&x

    *p*p

    TheThe yythth element of arrayelement of array xx

    Pointer toPointer to xx

    The object or function thatThe object or function thatpppoints topoints to

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1171421 CPL

    These operators will be discussed later in the sections onThese operators will be discussed later in the sections onarrays, pointers, structures, and unions. They are includedarrays, pointers, structures, and unions. They are includedhere for reference and completeness.here for reference and completeness.

    Struct / UnionStruct / UnionMember byMember byReferenceReference

    -->>

    Struct / UnionStruct / Union

    MemberMember

    ..

    pp-->y>y

    x.yx.y

    The member namedThe member named yy in thein thestructure or union thatstructure or union thatpppoints topoints to

    The member namedThe member named yy in thein the

    structure or unionstructure or union xx

    OperatorsOther

    Operator ResultOperation Example

  • 8/10/2019 programacion en c para pic mplaide

    118/443

    ()()

    sizeofsizeof

    Function CallFunction Call

    Size of anSize of an

    foo(x)foo(x) Passes control to thePasses control to thefunction with thefunction with the

    specified argumentsspecified arguments

    sizeof xsizeof x The number of bytesThe number of bytes xx

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1181421 CPL

    (type)(type)

    ?:?:

    ,,

    in bytesin bytes

    Explicit typeExplicit type

    castcast

    ConditionalConditional

    expressionexpression

    SequentialSequential

    evaluationevaluation

    (short) x(short) x Converts the value ofConverts the value of xx

    to the specified typeto the specified type

    x ? y : zx ? y : z The value ofThe value of yy ifif xx is true,is true,else value ofelse value of zz

    x, yx, y EvaluatesEvaluates xx thenthen yy, else, elseresult is value ofresult is value of yy

    Syntax

    OperatorsThe Conditional Operator

    ((t tt t ) ?) ? dd i fi f tt dd i fi f f lf l

  • 8/10/2019 programacion en c para pic mplaide

    119/443

    Example

    ((t es tt es t -- ex prexp r) ?) ? dodo-- i fi f -- t r uet r ue:: dodo-- i fi f -- f a l s ef a l s e;;

    intint xx == 55;;

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1191421 CPL

    5 is odd5 is oddResult:Result:

    ((xx %% 22 !=!= 00) ?) ?printfprintf(("%d is odd"%d is odd\\n"n",, xx) :) :printfprintf(("%d is even"%d is even\\n"n",, xx););

    OperatorsThe Conditional Operator

    The conditional operator may be used to

    diti ll i l t i bl

  • 8/10/2019 programacion en c para pic mplaide

    120/443

    Example 1 (most commonly used)

    x = (c ondi t i on) ? a : b;

    conditionally assign a value to a variable

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1201421 CPL

    x = a if condition is true

    x = b if condition is false

    Example 2 (less often used)

    (c ondi t i on) ? (x = a):(x = b);

    In both cases:

    OperatorsThe Explicit Type Cast Operator

    Earlier, we cast a literal to type float byt i it 4 0f

  • 8/10/2019 programacion en c para pic mplaide

    121/443

    entering it as: 4.0f

    We can cast the variable instead by usingthe cast operator: (t y pe)v ar i ab l e

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1211421 CPL

    Example: Integer Divide Example: Floating Point Divide

    intint xx == 1010;;floatfloat yy;;

    yy == xx // 44;;

    intint xx == 1010;;floatfloat yy;;

    yy == ((floatfloat))xx // 44;;

    y = 2.y = 2.000000000000Because: int / intBecause: int / int intint

    y = 2.y = 2.550000000000Because: float / intBecause: float / int floatfloat

    OperatorsPrecedence

    Operator Description Associativity

    ( )( ) Parenthesized ExpressionParenthesized Expression

  • 8/10/2019 programacion en c para pic mplaide

    122/443

    pp

    [ ][ ] Array SubscriptArray Subscript

    .. Structure MemberStructure Member-->> Structure PointerStructure Pointer

    LeftLeft--toto--RightRight

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1221421 CPL

    -- nary + annary + an os ve an ega ve gnsos ve an ega ve gns

    ++++ ---- Increment and DecrementIncrement and Decrement

    ! ~! ~ Logical NOT and Bitwise ComplementLogical NOT and Bitwise Complement

    ** Dereference (Pointer)Dereference (Pointer)

    && Address ofAddress of

    sizeofsizeof Size of Expression or TypeSize of Expression or Type(type)(type) Explicit TypecastExplicit Typecast

    RightRight--toto--LeftLeft

    Continued on next slideContinued on next slide

    OperatorsPrecedence

    Operator Description Associativity

    * / %* / % Multiply, Divide, and ModulusMultiply, Divide, and Modulus LeftLeft--toto--RightRight

  • 8/10/2019 programacion en c para pic mplaide

    123/443

    p yp y

    ++ -- Add and SubtractAdd and Subtract

    >> Shift Left and Shift RightShift Left and Shift Right

    < => >= Greater Than and Greater Than or Equal ToGreater Than and Greater Than or Equal To

    LeftLeft--toto--RightRight

    LeftLeft--toto--RightRight

    LeftLeft--toto--RightRight

    LeftLeft--toto--RightRight

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1231421 CPL

    &&&& Logical ANDLogical AND

    |||| Logical ORLogical OR

    ?:?: Conditional OperatorConditional Operator

    LeftLeft--toto--RightRight

    LeftLeft--toto--RightRight

    RightRight--toto--LeftLeft

    == !=== != Equal To and Not Equal ToEqual To and Not Equal To

    && Bitwise ANDBitwise AND^ Bitwise XORBitwise XOR

    || Bitwise ORBitwise OR

    Continued on next slideContinued on next slide

    LeftLeft--toto--RightRight

    LeftLeft--toto--RightRight

    LeftLeft--toto--RightRight

    LeftLeft--toto--RightRight

    OperatorsPrecedence

    Operator Description Associativity

    == AssignmentAssignment

  • 8/10/2019 programacion en c para pic mplaide

    124/443

    +=+= --== Addition and Subtraction AssignmentsAddition and Subtraction Assignments

    /= *=/= *= Division and Multiplication AssignmentsDivision and Multiplication Assignments

    %=%= Modulus AssignmentModulus Assignment

    == Shift Left and Shift Right AssignmentsShift Left and Shift Right Assignments

    RightRight--toto--LeftLeft

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1241421 CPL

    &= |=&= |= Bitwise AND and OR AssignmentsBitwise AND and OR Assignments

    ^=^= Bitwise XOR AssignmentBitwise XOR Assignment

    ,, Comma OperatorComma Operator LeftLeft--toto--RightRight

    Operators grouped together in a section havethe same precedence conflicts within a sectionare handled via the rules of associativity

    OperatorsPrecedence

    When expressions contain multiple

    operators their precedence determines

  • 8/10/2019 programacion en c para pic mplaide

    125/443

    Expression Effective Expression

    operators, their precedence determines

    the order of evaluation

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1251421 CPL

    a + ++ba + ++b a + (++b)a + (++b)a + ++b * ca + ++b * c a + ((++b) * c)a + ((++b) * c)

    If functions are used in an expression, there is no set order ofIf functions are used in an expression, there is no set order of

    evaluation for the functions themselves.evaluation for the functions themselves.

    e.g.e.g. x = f() + g()x = f() + g()There is no way to know ifThere is no way to know if f()f() oror g()g() will be evaluated first.will be evaluated first.

    If two operators have the same

    precedence their associativity determines

    OperatorsAssociativity

  • 8/10/2019 programacion en c para pic mplaide

    126/443

    precedence, their associativity determines

    the order of evaluationExpression Effective ExpressionAssociativity

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1261421 CPL

    You can rely on these rules, but it is goodprogramming practice to explicitly group

    elements of an expression

    -- --

    x = y = zx = y = z x = (y = z)x = (y = z)RightRight--toto--LeftLeft~++x~++x ~(++x)~(++x)RightRight--toto--LeftLeft

  • 8/10/2019 programacion en c para pic mplaide

    127/443

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1271421 CPL

    Lab Exercise 4

    Operators

    Lab 04Operators

    Open the projects workspace:

    O th l b PCO th l b PC

  • 8/10/2019 programacion en c para pic mplaide

    128/443

    On the lab PCOn the lab PC

    C:C:\\MastersMasters\\14211421\\Lab04Lab04\\Lab04.mcwLab04.mcw

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1281421 CPL

    1 Open MPLABOpen MPLAB IDE and selectIDE and select OpenOpen

    WorkspaceWorkspace from thefrom the FileFile menu.menu.Open the file listed above.Open the file listed above.

    If you already have a project openIf you already have a project open

    in MPLAB IDE, close it byin MPLAB IDE, close it by

    selectingselecting Close WorkspaceClose Workspace fromfromthethe FileFile menu before opening amenu before opening anew one.new one.

    Lab 04Operators

    /*###########################################################################

    Solution: Steps 1 and 2

  • 8/10/2019 programacion en c para pic mplaide

    129/443

    # STEP 1: Add charVariable1 to charVariable2 and store the result in

    # charVariable1. This may be done in two ways. One uses the# ordinary addition operator, the other uses a compound assignment

    # operator. Write two lines of code to perform this operation# twice - once for each of the two methods.

    # Don't forget to end each statement with a semi-colon!

    *

    2010 Microchip Technology Incorporated. All Rights Reserved.Slide 1291421 CPL

    //Add using addition operator

    charVariable1 = charVariable1 + charVariable2;//Add using compound assignment operator

    charVariable1 += charVariable2;

    /*###########################################################################

    # STEP 2: Increment charVariable1. There are several ways this could be

    # done. Use the one that requires the least amount of typing.

    ###########################################################################*/

    //Increment charVariable1

    charVariable1++;

    Lab 04Operators

    /*###########################################################################

    Solution: Steps 3 and 4

  • 8/10/2019 programacion en c para pic mplaide

    130/443

    # STEP 3: Use the conditional operator to set longVariable1 equal to

    # intVariable1 if charVariable1 is less than charVariable2.# Otherwise, set longVariable1 equal to intVariable2

    # NOTE: The comments below are broken up into 3 lines, but the code you# need to write can fit on a single line.

    ###########################################################################*/

    2010 Microchip Technology Incorporated. All Rights Reserved.Slide 1301421 CPL

    //If charVariable1 < charVariable2, then

    //longVariable1 = intVariable1, otherwise

    //longVariable1 = intVariable2longVariable1 = (charVariable1 < charVariable2) ? intVariable1 : intVariable2;

    /*###########################################################################

    # STEP 4: Shift longVariable2 one bit to the right. This can be accomplished

    # most easily using the appropriate compound assignment operator.

    ###########################################################################*/

    //Shift longVariable2 one bit to the right

    longVariable2 >>= 1;

    Lab 04Operators

    /*###########################################################################

    Solution: Step 5

  • 8/10/2019 programacion en c para pic mplaide

    131/443

    / ###########################################################################

    # STEP 5: Perform the operation (longVariable2 AND 0x30) and store the result# back in longVariable2. Once again, the easiest way to do this is

    # to use the appropriate compound assignment operator that will# perform an equivalent operation to the one in the comment below.

    ###########################################################################*/

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1311421 CPL

    //longVariable2 = longVariable2 & 0x30

    longVariable2 &= 0x30;

    Lab 04Conclusions

    Most operators look just like their normal

    mathematical notation

  • 8/10/2019 programacion en c para pic mplaide

    132/443

    mathematical notation

    C adds several shortcut operators in theform of compound assignments

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1321421 CPL

    Most C programmers tend to use the

    shortcut operators

  • 8/10/2019 programacion en c para pic mplaide

    133/443

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1331421 CPL

    Expressions and

    Statements

    Expressions

    Represents a single data item (e.g.

    h t b t )

  • 8/10/2019 programacion en c para pic mplaide

    134/443

    character, number, etc.)

    May consist of:

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1341421 CPL

    A single entity (a constant, variable, etc.)

    A combination of entities connected by

    operators (+, -, *, / and so on)

    Example

    ExpressionsExamples

    aa ++bb

  • 8/10/2019 programacion en c para pic mplaide

    135/443

    xx == yyspeedspeed == distdist//timetime

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1351421 CPL

    zz == ReadInputReadInput()()

    cc

  • 8/10/2019 programacion en c para pic mplaide

    136/443

    Three kinds of statements in C:

    Ex ression Statements

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1361421 CPL

    Compound StatementsControl Statements

    Expression Statements

    An expression followed by a semi-colon

    Execution of the statement causes the

  • 8/10/2019 programacion en c para pic mplaide

    137/443

    Examples

    Execution of the statement causes the

    expression to be evaluated

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1371421 CPL

    ii == 00;;

    ii++;++;aa == 55 ++ ii;;yy = (= (mm ** xx) +) +bb;;

    printf(printf("Slope = %f""Slope = %f", m, m););;;

    Compound Statements

    A group of individual statements enclosed

    within a pair of curly braces { and }

  • 8/10/2019 programacion en c para pic mplaide

    138/443

    within a pair of curly braces { and }

    Individual statements within may be any

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1381421 CPL

    ,

    Allows statements to be embedded withinother statements

    Does NOT end with a semicolon after }Also called Block Statements

    Example

    Compound StatementsExample

    {{flfl fi i hfi i h

  • 8/10/2019 programacion en c para pic mplaide

    139/443

    floatfloat startstart,, finishfinish;;

    startstart == 0.00.0;;

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1391421 CPL

    finishfinish == 400.0400.0;;

    distancedistance == finishfinish startstart;;timetime == 55.255.2;;speedspeed == distancedistance // timetime;;

    printfprintf(("Speed = %f m/s""Speed = %f m/s",, speedspeed););}}

    Control Statements

    Used for loops, branches and logical tests

    Often require other statements embedded

  • 8/10/2019 programacion en c para pic mplaide

    140/443

    Example

    q

    within them

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1401421 CPL

    whilewhile ((distancedistance

  • 8/10/2019 programacion en c para pic mplaide

    141/443

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1411421 CPL

    Making Decisions

    C has no Boolean data type

    Boolean expressions return integers:

    Boolean Expressions

  • 8/10/2019 programacion en c para pic mplaide

    142/443

    p g

    0 if expression evaluates as FALSENon-zero if expression evaluates as TRUE

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1421421 CPL

    (usually returns 1, but this is not guaranteed)

    intintmainmain((voidvoid)){{

    intint xx == 55,, yy,, zz;;

    yy = (= (xx >>44););zz = (= (xx >>66););whilewhile ((11););

    }}

    y = 1 (TRUE)y = 1 (TRUE)z = 0 (FALSE)z = 0 (FALSE)

    Boolean ExpressionsEquivalent Expressions

    If a variable, constant or function call isused alone as the conditional expression:

  • 8/10/2019 programacion en c para pic mplaide

    143/443

    (MyVar) or (Foo())

    This is the same as saying:

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1431421 CPL

    (MyVar != 0) or (Foo() != 0)

    In either case, ifMyVar 0 or Foo()0,then the expression evaluates as TRUE

    (non-zero)

    C Programmers almost always use the

    first method (laziness always wins in C)

    Syntax

    if Statement

    ifif ((ex pr es s i onex pr es s i on))s t at ements t at ement

  • 8/10/2019 programacion en c para pic mplaide

    144/443

    ex pr es s i onis evaluated for booleanTRUE (0) or FALSE (=0)

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1441421 CPL

    Note

    If TRUE, then s t at ement is executed

    if (ex pr es s i on){

    s t at ement1s t at ement2

    }

    Whenever you sees t at ement in a

    syntax guide, it may be replaced by a

    compound (block) statement.

    Remember: spaces and new lines are

    not significant.

    Syntax

    if StatementFlow Diagram

    ifif ((ex pr es s i onex pr es s i on))s t at ements t at ement

  • 8/10/2019 programacion en c para pic mplaide

    145/443

    2010 Microchip Technology Incorporated. All Rights Reserved. Slide 1451421 CPL

    TRUE

    FALSEex pr es s