+ All Categories
Home > Documents > C Language Quick Reference

C Language Quick Reference

Date post: 04-Apr-2018
Category:
Upload: cikguusin
View: 235 times
Download: 2 times
Share this document with a friend

of 39

Transcript
  • 7/31/2019 C Language Quick Reference

    1/39

    C Programming Language

    Quick Reference

    V1.3

    June 2009Information contained in this publication regarding device applications and the like is intended through suggestion only and may besuperseded by updates. It is your responsibility to ensure that your application meets with your specifications. No representation or

    warranty is given and no liability is assumed by Cytron Technologies Incorporated with respect to the accuracy or use of such information

    or infringement of patents or other intellectual property rights arising from such use or otherwise. Use of Cytron Technologiess products

    as critical components in life support systems is not authorized except with express written approval by Cytron Technologies. No licenses

    are conveyed, implicitly or otherwise, under any intellectual property rights.

  • 7/31/2019 C Language Quick Reference

    2/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved

    Index

    1. Introduction 1

    2. Standard Method to Start 1

    a. C Comments 1

    b. Include Header File 2

    c. Configuration Bits 2

    d. Include Libraries, Functions declaration and Global variables 2

    e. Function Name 2

    f. Function Body 2

    3. Radix Format 3

    4. Identifiers, Variables and Keywords 3

    a. Identifiers 3

    b. Variable 4

    c. Keywords 4

    d. Data Type 5

    e. Declaring Variable 6

    f. Array 6

    g. String 7

    5. Operators 9

    a. Arithmetic Operators 9

    b. Assignment Operators 9

    c. Relational Operators 10

    d. Logical Operators 10

    e. Bitwise Operators 10

    f. Shift Operators 10

    g. Memory Addressing Operators 11

  • 7/31/2019 C Language Quick Reference

    3/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved

    h. Other Operators 11

    i. Operator Precedence 12

    6. Statements 13

    a. Expression Statements 13

    b. Compound Statements 13

    c. Control Statements 14

    i. if Statement 15

    ii. switch Statement 16

    iii. for Statement 19

    iv. while Statement 20

    v. do-while Statement 21

    vi. break Statement 22

    vii. continue Statement 23

    7. Function 24

    8. Creating Project using MPLAB + HI-TECH C PRO Compiler 27

    9. Starting a PIC Program 36

  • 7/31/2019 C Language Quick Reference

    4/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 1

    1. Introduction

    This reference guide is intended to quickly introduce user to C language syntax with the aim

    to easily start programming microcontroller (PIC) during code development.

    1st

    question, Why C language? Because C offers unmatched power and flexibility in

    programming microcontrollers.

    2. Standard Method to Start

    There is no 100% correct ways to write c program, anyway there are guide lines to follow.

    Let see what a C file contains.

    a. C Comments/* Put your comments here. This is actually the format of C comments. It may takes

    multiple lines, as long as it is end with */

    OR

    // Put your comments after //, this only allow one line.

    // If you need multiple lines you will need // in front of each line.

    // This is C++ format of putting comments.

    Prepared byCytron Technologies Sdn. Bhd.

    19, Jalan Kebudayaan 1A,

    Taman Universiti,

    81300 Skudai,

    Johor, Malaysia.

    Tel: +607-521 3178

    Fax: +607-521 1861

    URL: www.cytron.com.my

    Email: [email protected]

    [email protected]

    a. Comments

    b. Include header

    file

    c. Configuration

    bits

    d. Include libraries,

    function declaration,lobal variable

    e. Function name

    f. Function

    body

    End of block

    Begin of

    Block

  • 7/31/2019 C Language Quick Reference

    5/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 2

    b. Include Header File#include is to called the proper header file. It enables the compiler to

    include file which define standard keyword for PIC based on model. It also includes

    certain functions contained in the external file htc.h.

    As the file placed before the program proper, it is called a header file (with the fileextension .h).

    c. Configuration BitsA macro that writes a value into the special register that controls the core executing

    operations of the microcontroller. It start with two _ and followed with

    CONFIG(configuration bits);

    If the configuration bits are not specified correctly, the PIC MCUs might not run the

    application code properly

    d. Include Libraries, Functions declaration and Global variablesThis section can be leaved blank depend on program writer. However, if there is

    necessary to include other header file, libraries, to declare functions prototype and global

    variables, it should be placed here.

    e. Function NameAll C programs are written in terms offunctions. It is the basic building block in C

    programming. C program must have at least the function main( ). The void means the

    main( ) function doesn't return any value when it exit (finish running)..

    f. Function BodyEvery function, including main( ), must have a body enclosed in braces { }.The function

    body (also called block) can be of any size. The curly braces are to signify the block of

    codes belonging to main( ). Do take note that there MUST NOT be a semicolon after the

    closing brace.

  • 7/31/2019 C Language Quick Reference

    6/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 3

    3. Radix Format

    Radix format is the way a value is being presented in C language

    There are four methods to present value:

    Radix Format Comments

    Binary 0bnumberor0BnumberMPASM binary is in format Bnumber.

    Octal 0numberor\number Inadvertently putting a 0 in front of a decimal

    number will convert it to octal for the compiler,

    potentially resulting in errors that are very hard to

    find.

    Decimal number MPASM default is hexadecimal

    Hexadecimal 0xnumberor0XnumberMPASM also enables Xnumber.

    4. Identifiers, Variables and Keywords

    a. Identifiers

    Identifiers are simply names or labels given to program elements such as variables, functions,

    arrays.

    A valid identifier has the rules of:

    Remember! Is case sensitive, Temp not the same as temp.

    I d e n t i f i e rFirst Character

    _ (underscore)A to Za to z

    Remaining Characters_ (underscore)

    A to Za to z0 to 9

  • 7/31/2019 C Language Quick Reference

    7/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 4

    b. VariableA variable is a valid identifier that represents one or more memory locations used to hold

    program data. It must be declared before uses. Data type must be assigned to a variable.

    c. KeywordsKeywords also called reserved words, have standard, predefined meanings and must be used

    only for their intended purpose.

    asm

    class

    do

    far

    huge

    long

    protected

    sizeof

    typedef

    volatile

    auto

    const

    double

    float

    if

    near

    public

    static

    union

    while

    break

    continue

    else

    for

    inline

    new

    register

    struct

    unsigned

    case

    default

    enum

    friend

    int

    operator

    return

    switch

    virtual

    char

    delete

    extern

    goto

    interrupt

    private

    short

    this

    void

  • 7/31/2019 C Language Quick Reference

    8/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 5

    d. Data TypeData Type is type assigned to variable to determine the size and how the variable being

    interpreted.

    Fundamental Type

    Type Description Bitschar single character 8

    int integer 16

    float single precision floating point number 32

    double double precision floating point number 64

    Modified Integer Types

    Qualifiers: unsigned, signed, short and long

    Qualified Type Min Max Bits

    unsigned char 0 255 8char, signed char -128 127 8

    unsigned short int 0 65535 16

    short int, signed short int -32768 32767 16

    unsigned int 0 65535 16

    int, signed int -32768 32767 16

    unsigned long int 0 232-1 32

    long int, signed long int -231 231-1 32

    unsigned long long int 0 264-1 64

    long long int, signed long long int -263 263-1 64

    Modified Floating Point Types

    Qualified TypeAbsolute

    MinAbsolute

    Max Bits

    float ~10-44.85 ~1038.53 32

    double1 ~10-44.85 ~1038.53 32

    long double ~10-323.3

    ~10308.3

    641. HI-TECH C PRO is either using IEEE-754 Format or modified (Truncated) 24-bit Format

  • 7/31/2019 C Language Quick Reference

    9/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 6

    e. Declaring Variable

    Standard Syntax

    type identifier1, identifier2,.., identifiern;

    Other methodOne declaration on a line

    type identifier;

    One declaration on a line with an initial value

    type identifier InitialValue;

    Multiple declarations of same type of a line

    type identifier1, identifier2, identifier3;

    Multiple declarations of same type of a line with initial values

    type identifier1= Value1, identifier2 = Value2;

    Example:unsigned int x;

    unsignedy = 12;int a, b, c;long int myVar = 0x12345678;long z;char first = 'a', second, third = 'c';

    float big_number = 6.02e+23;

    f. ArrayArrays are variables that can store many items of the same data type. The individual items

    known as elements, are stored sequentially and are uniquely identified by the array index

    (sometimes called a subscript). The index is zero based.

    Standard Syntax

    type arrayName[size];

    size refer to the number of elements and it must be a constant integer.

    Declaration with initialization

    type arrayName[size] = {item1, . , itemn};

    The items must all match the type of the array.

    Example:int a[5] = {10, 20, 30, 40, 50};

  • 7/31/2019 C Language Quick Reference

    10/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 7

    Using Array:

    Standard Syntax

    arrayName[index]

    index may be a variable or a constant

    The first element in the array has an index of 0

    Example1:int i, a[10]; //An array that can hold 10 integers

    for(i = 0; i < 10; i++)

    {a[i] = 0; //Initialize all array elements to 0

    }

    a[4] = 42; //Set fifth element to 42

    Example2:unsigned char count[5] = {1,2,3,4,5};

    element Value

    count[0] 1

    count[1] 2

    count[2] 3

    count[3] 4

    count[4] 5

    g. StringStrings are arrays of char whose last element is a null character \0 with an ASCII of 0. C has

    no native string data type, so strings must always be treated as character arrays.

    Strings:

    - Are enclosed in double quotes string.- Are terminated by a null character \0.- Must be manipulated as arrays of characters (treated element by element).- May be initialized with a string literal.

    Declaration with initializationchar arrayName[] = Cytron Technologies;

    Element size is not required.

    Size automatically determined by length of string.

    NULL character \0 is automatically appended.

    Example:char str1[] = Cytron"; // 7 chars Cytron\0"

    //Alternative string declaration size requiredchar str3[4] = {'P', 'I', 'C', '\0'};

  • 7/31/2019 C Language Quick Reference

    11/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 8

    Following show the ASCII table:

  • 7/31/2019 C Language Quick Reference

    12/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 9

    5. Operators

    Most C Compiler recognizes following operators:

    - Arithmetic Operators- Assignment Operators- Relational Operators- Logical Operators

    - Bitwise Operators- Shift Operators- Memory Addressing Operators- Other Operators

    a. Arithmetic Operators

    Operator Operation Example Product Remarks

    * Multiplication x * y Product of x and y Binary

    / division x / y Quotient of x and y Binary

    % Modulo x % yRemainder of x divided byy Binary

    + Addition x + y Sum of x and y Binary- Subtraction x - y Difference of x and y Binary

    + Positive + x Value of x Unary

    - Negative - y Negative value of y Unary

    ++ Increment ++ x increase x by 1 Unary

    -- Decrement -- x decrease x by 1 Unary

    b. Assignment Operators

    Operator Operation Example Result

    = Assignment x = y Assign x the value of y

    += Compound Assignment x += y x = x + y-= Compound Assignment x -= y x = x - y

    *= Compound Assignment x *= y x = x * y

    /= Compound Assignment x /= y x = x / y

    %= Compound Assignment x %= y x = x % y

    &= Compound Assignment x &= y x = x & y

    ^= Compound Assignment x ^= y x = x ^ y

    |= Compound Assignment x |= y x = x | y

    > y

  • 7/31/2019 C Language Quick Reference

    13/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 10

    c. Relational Operators

    Operator Operation Example Result (FASLE = 0, TRUE0)

    < Less than x < y 1 if x less than y, else 0

    y 1 if x greater than y, else 0

    >= Greater than or equalto x >= y 1 is x greater than or equal to y, else0

    == Equal to x == y 1 is x equal to y, else 0

    != Not equal to x != y 1 is x not equal to y, else 0

    d. Logical Operators

    Operator Operation Example Result (FASLE = 0, TRUE0)

    && Logical AND x && y 1 if both x 0 and y 0, else 0

    || Logical OR x || y 1 if both x = 0 and y = 0, else 1

    ! Logical NOT !x 1 if x = 0, else 0

    e. Bitwise Operators

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

    second operand.

    Operator Operation Example Result (for each bit position)

    & Bitwise AND x & y1 if 1 in both x and y

    0, if 0 is x or y or both

    | Bitwise OR x | y1, if 1 in x or y or both

    0, if 0 in both x and y^ Bitwise XOR x ^ y

    1, is 1 in x or y but not both

    0, if 0 or 1 in both x and y

    ~ Bitwise NOT ~x1, if 0 in x

    0, if 1 in x

    f. Shift Operators

    Operator Operation Example Result

    Shift Right x >> y Shift x by y bits to the right

  • 7/31/2019 C Language Quick Reference

    14/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 11

    g. Memory Addressing Operators

    Operator Operation Example Result& Address of &x Pointer to x* Indirection *p The object of function that p points to[ ] Subscripting x[y]

    The y

    th

    element of array x. Struct/Union Member x.y

    The member named y in the structureor union x

    ->Struct/Union Memberby Reference

    p->yThe member named y in the structureor union that p points to

    h. Other Operators

    Operator Operation Example Result

    ( ) Function call foo(x)Passes control to the function withthe specified arguments

    sizeof Size of an object ortype in bytes sizeof x the number of bytes x occupies inmemory

    (type) Explicit type cast (short) xConverts the value of c to thespecified type

    ?:Conditionalexpression

    x ? y : zThe value of y if x is true, else valueof z

    ,Sequentialevaluation

    x, yEvaluates x then y, else result isvalue of y

  • 7/31/2019 C Language Quick Reference

    15/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 12

    i. Operator Precedence

    Which operator will be evaluated first?

    Operator Description Associativity

    ( ) Parenthesized Expression

    Left-to-Right[ ] Array Subscript

    . Structure Member

    -> Structure Pointer

    + - Unary + and - (Positive and Negative Signs)

    Right-to-Left

    ++ -- Increment and Decrement

    ! ~ Logical NOT and Bitwise Complement

    * Deference (Pointer)

    & Address of

    sizeof Size of Expression or Type

    (type) Explicit Typecast

    * / % Multiply, Divide, and Modulus

    Left-to-Right

    + - Add and Subtract

    > Shift Left and Shift Right< >= Greater Than and Greater Than or Equal To

    == != Equal To and Not Equal to

    & Bitwise AND

    ^ Bitwise XOR

    | Bitwise OR

    && Logical AND

    || Logical OR

    ? : Conditional Operator

    Right-to-Left

    = Assignment+= -= Addition and Subtraction Assignments

    /= *= Division and Multiplication Assignments

    %= Modules Assignment

    = Shift Left and Shift Right Assignments

    &= |= Bitwise AND and OR Assignments

    ^= Bitwise XOR Assignments

    , Comma Operator Left-to-Right

  • 7/31/2019 C Language Quick Reference

    16/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 13

    6. Statements

    Statements can be roughly divided into:

    - Expression Statements- Compound Statements- Control Statements

    a. Expression StatementsAn expression followed by a semi-colon. It caused the expression to be evaluated.

    Example:i = 0;i++;

    a = 5 + i;y = (m * x) + b;printf("Slope = %f", m);;

    b. Compound StatementsA group of individual statements enclosed within a pair of curly braces { and }. It does not

    end with a semicolon after }. It is also called Block Statements.

    Example:{

    float start, finish;

    start = 0.0;finish = 400.0;

    distance = finish start;

    time = 55.2;speed = distance / time;

    printf("Speed = %f m/s", speed);}

  • 7/31/2019 C Language Quick Reference

    17/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 14

    c. Control StatementsUsed for loops, branches and logical tests. Often require other statements embedded within

    them.

    Before exploring more in to Control Statements, we must understand Boolean expressions.

    Boolean expressions return integers:

    - 0 if expression evaluates as FALSE- Non-zero if expression evaluates as TRUE (usually returns 1, but this is not

    guaranteed)

    Example:intmain(void){

    int x = 5, y, z;

    y = (x > 4);z = (x > 6);

    while (1);

    }

    y = 1 (TRUE)

    z = 0 (FALSE)

  • 7/31/2019 C Language Quick Reference

    18/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 15

    i. if Statement

    Standard Syntaxif (expression) statement

    expression is evaluated for Boolean TRUE (0) or FALSE (=0), if TRUE, then

    statement is executed.

    Flow diagram of if statement

    Example:{

    int x = 5;

    if (x){

    printf("x = %d\n", x);}while (1);

    }

    if statement may has several combination of:

    a. Nested if statementb. if-else statementc. if-else if statement

    expression statement

    START

    END

    expression statement

    START

    END

    TRUE

    FALSEexpression = 0

    expression 0

  • 7/31/2019 C Language Quick Reference

    19/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 16

    ii. switch StatementStandard Syntaxswitch (expression){

    case const-expr1: statements1

    .

    .

    .case const-exprn: statementsndefault: statementsn+1

    }

    expression is evaluated and tested for a match with the const-expr in each case

    clause. The statements in the matching case are executed.

  • 7/31/2019 C Language Quick Reference

    20/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 17

    Flow diagram of default switch statement

    Flow diagram of modified switch Statement

    Const-expr1=

    expression?

    START

    END

    statement2

    statement1

    Const-expr2=

    expression?

    statementn+1

    Const-exprn=

    expression?statement

    n

    Const-expr1=

    expression?

    START

    END

    statement2

    statement1

    Const-expr2=

    expression?

    statementn+1

    Const-exprn=

    expression?statement

    n

    Notice that each statementfalls through to the next

    This is the default behavior

    of the switch statement

    Const-expr1=

    expression?

    START

    END

    Const-expr2=

    expression?

    statementn+1

    Const-exprn=

    expression?

    statement1

    break;

    statement2

    break;

    statementn

    break;

    Const-expr1=expression?

    START

    END

    Const-expr2=

    expression?

    statementn+1

    Const-exprn=

    expression?

    statement1break;

    statement2

    break;

    statementn

    break;

    Adding abreak

    statement to eachstatement block willeliminate fallthrough, allowingonly one caseclause's statement

    block to be executed

  • 7/31/2019 C Language Quick Reference

    21/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 18

    Example:switch(channel){

    case 2: printf("WBBM Chicago\n"); break;case 3: printf("DVD Player\n"); break;case 4: printf("WTMJ Milwaukee\n"); break;

    case 5: printf("WMAQ Chicago\n"); break;case 6: printf("WITI Milwaukee\n"); break;case 7: printf("WLS Chicago\n"); break;case 9: printf("WGN Chicago\n"); break;

    case 10: printf("WMVS Milwaukee\n"); break;case 11: printf("WTTW Chicago\n"); break;case 12: printf("WISN Milwaukee\n"); break;

    default: printf("No Signal Available\n");}

  • 7/31/2019 C Language Quick Reference

    22/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 19

    iii. for StatementAlso being called as for loop.

    Standard Syntaxfor(expression1; expression2; expression3)

    statement

    - expression1initializes a loop count variable once at start of loop (e.g. I = 0).

    - expression2is the test condition: the loop will continue while this is true (e.g. I

  • 7/31/2019 C Language Quick Reference

    23/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 20

    iv. while StatementOften called while loop.

    Standard Syntaxwhile (expression) statement

    - Ifexpression is TRUE, statement will be executed and then expressionwill be re-evaluated to determine whether or not to execute statement again.

    - It is possible that statement will never be executed ifexpression is FALSE

    when it is first evaluated.

    Flow diagram of while Statement

    Example:

    Expected result:

    Loop iteration 0

    Loop iteration 1Loop iteration 2

    Loop iteration 3

    Loop iteration 4

    expression?

    START

    END

    statementexpression?

    START

    END

    statement

    iinntt ii == 00;;

    wwhhiillee ((ii

  • 7/31/2019 C Language Quick Reference

    24/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 21

    v. do-while StatementAlways called do-while loop

    Standard Syntaxdo statement while (expression);

    - statement is executed and then expression is evaluated to determine whetheror not to execute statementagain.

    - statement will always execute at least once, even if the expression is FALSE

    when the loop starts.

    Flow diagram of do-while Statement

    Example:

    Expected result:

    Loop iteration 0

    Loop iteration 1

    Loop iteration 2

    Loop iteration 3Loop iteration 4

    Loop iteration 5

    expression?

    START

    END

    statement

    expression?

    START

    END

    statement

    Loop counter incremented

    manually inside loop

    Loop counter initialized outside

    of loop

    Condition checked at end of

    loop iterations

    iinntt ii == 00;;

    ddoo{{

    pprriinnttff((""LLoooopp iitteerraattiioonn ##%%dd\\nn"",, ii++++));;

    }} wwhhiillee ((ii

  • 7/31/2019 C Language Quick Reference

    25/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 22

    vi. break StatementStandard Syntaxbreak;

    - Causes immediate termination of a loop even if the exit condition hasnt been met.- Exits from a switch statement so that execution doesnt fall through the next case

    clause.

    Flow diagram of break Statement

    Example:

    Expected result:

    Loop iteration 1

    Loop iteration 2

    Loop iteration 3

    Loop iteration 4

    expression?

    START

    END

    break

    statement

    statement

    expression?

    START

    END

    break

    statement

    statement

    TRUE

    FALSE

    iinntt ii == 00;;

    wwhhiillee ((ii

  • 7/31/2019 C Language Quick Reference

    26/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 23

    vii. continue StatementStandard Syntaxcontinue;

    - Causes program to jump back to the beginning of a loop without completing thecurrent iteration.

    Flow diagram of break Statement

    Example:

    Expected result:

    Loop iteration 1

    Loop iteration 3

    Loop iteration 4

    Loop iteration 5

    expression?

    START

    END

    continue

    statement

    statement

    expression?

    START

    END

    continue

    statement

    statement

    TRUE

    FALSE

    iinntt ii == 00;;

    wwhhiillee ((ii

  • 7/31/2019 C Language Quick Reference

    27/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 24

    7. Functions

    Functions are self contained program segments designed to perform a specific, well defined

    task.

    - All C programs have one or more functions.- Themain( ) function is the minimum function needed.

    - Functions can accept parameters from the code that calls them.- Functions usually return a single value.- Functions help to organize a program into logical, manageable segments.

    Program Structure in C programming

    drink(){...

    be_merry(); return;

    be_merry(){...return;

    }

    eat(){...return;

    main(){

    ...eat();...drink();...

  • 7/31/2019 C Language Quick Reference

    28/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 25

    Standard Syntax of function definition

    Example:

    int maximum(int x, int y){int z;

    z = (x >= y) ? x : y;

    return z;}

    Standard Syntax of function calling

    a. No parameters and no return value:foo( );

    b. No parameters, but with a return value:x = foo ( );

    c. With parameters, but no return value:foo(a, b);

    d. With parameters and a return value:x = foo(a, b);

    Syntax

    ttyyppee iiddeennttiiffiieerr((ttyyppee11aarrgg11,,,,ttyyppeennaarrggnn))

    {{ddeeccllaarraattiioonnss

    ssttaatteemmeennttss

    rreettuurrnneexxpprreessssiioonn;;}}

    DDaattaa ttyyppee ooffrreettuurrnneexxpprreessssiioonn

    NNaammee

    PPaarraammeetteerrLLiisstt((ooppttiioonnaall))

    RReettuurrnn VVaalluuee ((ooppttiioonnaall))HHeeaaddeerr

    BBooddyy

  • 7/31/2019 C Language Quick Reference

    29/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 26

    Function Prototypes

    - Like variables, a function must be declared before it may be used.- Declaration must occur beforemain( ) or other functions that use it.

    - Declaration may take two forms:o The entire function definitiono Just a function prototype the function definition itself may then be placed

    anywhere in the program

    Example:

    iinntt aa == 55,, bb == 1100,, cc;;

    iinntt mmaaxxiimmuumm((iinntt xx,, iinntt yy));;

    iinntt mmaaiinn((vvooiidd))

    {{cc == mmaaxxiimmuumm((aa,, bb));;pprriinnttff((""TThhee mmaaxx iiss %%dd\\nn"",, cc))

    }}

    iinntt mmaaxxiimmuumm((iinntt xx,, iinntt yy)){{rreettuurrnn ((((xx >>== yy)) ?? xx :: yy));;

    }}

    Function is declared with

    prototype before use in main ( )

    Function is defined after it is used

    in main ( )

  • 7/31/2019 C Language Quick Reference

    30/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 27

    8. Creating Project using MPLAB + HI-TECH C PRO Compiler

    To start MPLAB IDE and open project for PIC16F series, please follow the step below:

    1. Double click on the icon installed on the desktop after installation or selectStart>Programs>Microchip> MPLAB IDE v8.20a>MPLAB IDE. A screen will

    display the MPLAB IDE logo followed by the MPLAB IDE desktop as in diagrambelow.

    2. The next step is to create a project using the Project Wizard. A project is the way thefiles are organized to be compiled and assembled. We Choose Project>Project

    Wizard.

  • 7/31/2019 C Language Quick Reference

    31/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 28

    3. From the Welcome dialog, click onNextto proceed.

    4. The next dialog (Step One) allows you to select the device. In this example,PIC16F877A was selected from the drop down menu. ClickNext>.

  • 7/31/2019 C Language Quick Reference

    32/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 29

    5. The next step of the Project Wizard is sets up the language tools that are used withthis project. Select HI-TECH Universal Toolsuite in the Active Toolsuite list box.

    Then select HI-TECH ANSI C Compiler in the Toolsuite Contents box. When you

    are finished, clickNext.

    6. Step three of the project wizard allows user to create new project file.

  • 7/31/2019 C Language Quick Reference

    33/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 30

    7. For an example, a folder named Projectwas first created at Desktop.

    8. Then open the folder, project. Project named project can be created by typing theproject name in the column for File name, and clickSave.

  • 7/31/2019 C Language Quick Reference

    34/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 31

    9. Diagram below shown the Project project had been created and the directory. ClickNext>.

    10.Step four of the project wizard allow user to add existing file to the project, however,for this example, no files will be added. Please clickNext> to proceed.

  • 7/31/2019 C Language Quick Reference

    35/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 32

    11.A summary will be shown at the end of project wizard, all the project parameters areshown. Please clickFinish to exit from project wizard.

    12.After pressing the Finish button, review the Project Window on the MPLAB IDEdesktop. It should look like the diagram below. If the Project Window is not open,

    please select View>Project.

  • 7/31/2019 C Language Quick Reference

    36/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 33

    13.In this example, sample source code for Cytron DIY project, PR23 will be added tothis project. The sample source code can be downloaded at

    http://www.cytron.com.my/PR23.asp . Diagram below show the sample source code,

    PR23.c being copied and pasted in the folder,project.

    14.To add file in Source Files, right click on the Source Files, then click onAdd Files,diagram below shown the example for add file to Source Files

  • 7/31/2019 C Language Quick Reference

    37/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 34

    15.After clicking onAdd Files, a window pop out, do make sure the Files of type isAllSource Files(*.asm;*.c), then browse to the folderProject to add in PR23.c. User

    can select the file, PR23.c, and click open to add the file.

    16.Diagram below shown PR23.c added to the project.

  • 7/31/2019 C Language Quick Reference

    38/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    Created by Cytron Technologies Sdn. Bhd. All Rights Reserved 35

    17.After added the source file, user can open PR23.c file in this workspace and try tocompile it. Diagram below shown opened PR23.c file. To compile, user can go

    Project>Build or the build icon (in red circle) on menu bar as shown in diagram

    below.

    18.After build success, a message Build successful! will appear in output window likeshown in diagram below.

  • 7/31/2019 C Language Quick Reference

    39/39

    ROBOT . HEAD to TOEQuick Reference C Programming Language

    9. Starting a PIC Program

    There are basic steps to start a program for PIC microcontroller

    a. Create a project.

    b. Create a C file.

    c. Place some comments on top of C file.

    d. Include necessary header file.

    e. Write configuration bit.

    f. Function prototype declaration, global variables.

    g. Start main function, void main ().

    h. 1st thing after PIC reset, it will come to main function and look at first program line.

    Thus program write must initialize the PIC Input, Output, Analog input, UART, and

    also other peripherals which going to be used in later program.i. Also please ensure the initial stage of output is not activated after reset.

    Prepared by

    Cytron Technologies Sdn. Bhd.19, Jalan Kebudayaan 1A,

    Taman Universiti,

    81300 Skudai,

    Johor, Malaysia.

    Tel: +607-521 3178

    Fax: +607-521 1861

    URL: www.cytron.com.my

    Email: [email protected]


Recommended