C Language QR v2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

C Language

Quick Reference
V1.2

Nov 2008
Information contained in this publication regarding device applications and the like is intended through suggestion only and may
be superseded 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 Technologies’s 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.
ROBOT . HEAD to TOE
Quick Reference – C Language

C language Quick Reference


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. Comments

b. Include header
file
c. Configuration
bits
d. Include libraries,
function declaration,
global variable
e. Function name

Begin of
Block

f. Function
body

End of block

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.

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


ROBOT . HEAD to TOE
Quick Reference – C Language

b. Include header file


#include<pic.h> 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 pic.h.

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

c. Configuration bits
A 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 variables


This section can be leaved blank depend on program writer. However, if there is
necessary to include other header file, libraries and to declare functions prototype and
global variables, it should be placed here.

e. Function name
All C programs are written in terms of functions. 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 body
Every 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.

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


ROBOT . HEAD to TOE
Quick Reference – C Language

3. Radix format
Radix format is the way a value is being presented in C language
There are four method to present value:
Radix Format Comments
Binary 0bnumber or 0Bnumber MPASM binary is in format B’number’.

Octal 0number or \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 0xnumber or 0Xnumber MPASM also enables X’number’.

4. Identifiers, Variables and Keywords


4.1 Identifiers are simply references to memory locations which can hold values.

Valid Invalid

x “x” illegal character “

Sumx2 2sumx illegal first character

hourly_rate hourly-rate illegal character –

Name name@ illegal character @

GROSS_PAY GROSS PAY illegal blank

4.2 Keywords, also called reserved words, have standard, predefined meanings and must be
used only for their intended purpose.
asm auto break case char
class const continue default delete
do double else enum extern
far float for friend goto
huge if inline int interrupt
long near new operator private
protected public register return short
sizeof static struct switch this
typedef union unsigned virtual void
volatile while

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


ROBOT . HEAD to TOE
Quick Reference – C Language

4.3 Variables are identifiers whose value may change during the course of execution of a
program. Before variables can be used in C program, it must be declare or define.
Variable is define based on data types.

Type Size Range

bit 1 0 .. 1 (not a standard C data type)


(signed) char 8 -128 .. 127
unsigned char 8 0 .. 255
(signed) short 16 -128 .. 127
unsigned short 16 0 .. 255
(signed) int 16 -32768 .. 32767
unsigned int 16 0 .. 65535
(signed) long 32 -2147483648 .. 2147483647
unsigned long 32 0 .. 4294967295
float 32 ±1.17549435082 E-38 .. ±6.80564774407 E38
double 32 ±1.17549435082 E-38 .. ±6.80564774407 E38

type variable_name;

Example:
float amount; //Declares amount as a floating variable

int number=5; //Declares number as an singed integer variable


//at initial value 5

unsigned char ch1, ch2; //Declares ch1 and ch2 as a character


//variable

Array
Used to store related items in the same block of memory and under a specified name.
Declared by specifying its type, name and the number of elements it will store. The general
form of the declaration is

type variable_name[element number];

Example:
unsigned int Total [5]; //Declares an array of unsigned int
//with the name Total, and
//it will store 5 elements.
or
unsigned int days[4] = {1,200,3,365};

Data can be store to particular elements with:


Total [2] = 34; //Store value 34 to 3rd element of
//Total array

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


ROBOT . HEAD to TOE
Quick Reference – C Language

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

If ‘A’ is being stored, the single quote ‘ mark will convert the character into ASCII code,
which is decimal 65 (0x41) for character A.

To store character:
unsigned char name[4] = {‘O’,’b’,’e’,’r’};
is the same as:
unsigned char name[4] = {79, 98, 101, 114};

Following show the ASCII table:

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


ROBOT . HEAD to TOE
Quick Reference – C Language

Use double quotation marker “ to enclose the string.


unsigned char name[5] = “Ober”;

Noted that 4 ASCII character stored in 5 elements, why? Because C will need to terminate
the string with ‘/0’ or NULL or 0 at the last element. No { } is required for string.

Pointer
Pointer is used to position a memory.
The value inside pointer is used as address of memory.

type *pointer_name;

unsigned int *s; //16-bit pointer


s = &a; //s is being assign to point to variable a

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


ROBOT . HEAD to TOE
Quick Reference – C Language

5. Operators
PICC Lite Compiler recognizes following operators:
- Arithmetic Operators
- Assignment Operators
- Bitwise Operators
- Logical Operators
- Relational Operators

5.1 Arithmetic Operators


Operator Action
- subtraction
+ addition
* multiplication
/ division
% modulus division
-- decrement
++ increment

5.2 Assignment Operators

expression1 = expression2

expression1 op=expression2 is the same as expression1 = expression1 op


expression2

where op can be one of binary operator +, - , *, /, %, &, |, ^, <<, or >>


Example:
counter += 1; is the same as counter = counter + 1

5.3 Bitwise Operators

Operator Meaning

& Bitwise AND


| Bitwise OR
^ Bitwise XOR
~ Bitwise Complement
<< Shift Left
>> Shift Right

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


ROBOT . HEAD to TOE
Quick Reference – C Language

5.4 Logical Operators


Operator
Meaning

&& AND
|| OR
! NOT

5.5 Relational Operators

Operator Meaning

< less than


<= less than or equal
> greater than
>= greater than or equal
== equal
!= not equal

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


ROBOT . HEAD to TOE
Quick Reference – C Language

6. Statements
Statements can be roughly divided into:
- Labeled Statements
- Selection Statements
- Iteration Statements (Loops)
- Jump Statements

6.1 Labeled Statements

Label_identifier: statement;

Example 1:
loop : Display(message);
goto loop; //infinite loop that call Display function

Example 2:
Use in switch statement…….

6.2 Selection Statements

if Statement
if (expression) statement1 [else statement2]
else keyword with alternative statement is optional

switch Statement

switch (expression)
{
case expression_1 :
statement sequence
case expression_2 :
statement sequence
.
.
default:
statement sequence
}

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


ROBOT . HEAD to TOE
Quick Reference – C Language

6.3 Iteration Statements (Loops)

While Statements
while (expression) statement

Example:
while ((sensor1==0) && (sensor2==1) && (sensor3==0))
{
Motor1 = 100; // Motor’s PWM value
Motor2 = 100; // moving forward
}

Do Statements
do statement;
while (expression);

Example:
unsigned char i, s;
s = i = 0;
do
{
s = s + 2;
i = i + 1;
}
while( i < 7); // at the end, s = 14

For Statements
for ([initialization];[ condition-exp];[ increment-exp])
statement
Example:
for (i = 1 ; i <= 20 ; i++)
{
lcd_char(i); // display i on LCD
delay(1000);
} //i will be display from 1 until 20

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


ROBOT . HEAD to TOE
Quick Reference – C Language

6.4 Jump Statements


To allow program control to be transferred from one part of program to another
unconditionally

Break Statements
A break terminates the nearest enclosing loop. Applicable for switch, for, while and do
block

Example:
unsigned char j = 0, s = 1;
while (1) {
if (j == 4) break;
s = s * 2;
j++;
} // result s = 16

Continue Statements
Unlike the break statement, continue does not force the termination of a loop, it skip the rest
of statements and jump to the first statement in the loop.

Example:
unsigned char Sum = 0, i = 0;
for (i=1 ; i<=10; i++)
{
if (i==5) continue;
Sum = Sum + i;
} //This will add up 1, 2, 3, 4, 6, 7, 8, 9, 10

Goto Statements
The goto statement has the form

goto label;

Example:
TOGGLE:
RTC++;
if (RB0 == 1)
goto TOGGLE; //if RB0=1, program jump to TOGGLE
else if (RB1 == 1)
RTC--;
else
RTC = 0xFF;

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


ROBOT . HEAD to TOE
Quick Reference – C Language

Return Statements
The return statement has the form

return expression;

To terminate execution of the current function and optionally pass the return value contained
in the expression. The value return must be of the same type or convertible to the same types
as the function.

Example:
void main()
{

c = Calculate(a, b);

}

unsigned int Calculate (unsigned int TempA, unsigned int


TempB)
{
unsigned int TempC = 0;
TempC = TempA + TempB;
return TempC;
}

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


ROBOT . HEAD to TOE
Quick Reference – C Language

7. Defining functions

Function Declaration (Function Prototype)


C program function declaration takes the form

function_type function_name(parameter-list);

Example:
unsigned char Cal (unsigned char a, unsigned char b);

Function Definition
C program function definition takes the form

function_type function_name (parameter-list)


{
function body
}

Example:

unsigned char Cal (unsigned char a, unsigned char b)


{
unsigned char c;
c = a + b;
return c;
}

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


ROBOT . HEAD to TOE
Quick Reference – C Language

8. Creating Project using MPLAB + PICC Lite Compiler

a. Goto Project -> Project Wizard


b. Click Next to proceed.
c. Choose PIC model (PIC16F877A) for Device.
d. Click Next to proceed.
e. Search for HI-TECH Universal ToolSuite for Active Toolsuite.
f. Browse for C:\Program Files\HI-TECH Software\PICC\LITE\9.60\bin\picl.exe. Click
Next to proceed.
g. Create a project at preferred directory.
h. Click Next to proceed.
i. Skip the step of Adding existing files, it can be added later. Click Next to proceed.
j. Please click Finish to complete the Wizard.
k. User should see project window at the left top corner with the project.

l. If there is no project window, please go to View -> Project.

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


ROBOT . HEAD to TOE
Quick Reference – C Language

m. Now, create a C file using New and save as filename.c


n. C source code must be added into project.
o. To add C file, right click at Source Code, and Add Files.

p. Browse for the C.


q. If the project is ready to be compiled to generate Hex file, Click on the Build Project
icon.
r. Or goto Project -> Rebuild

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


ROBOT . HEAD to TOE
Quick Reference – C 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]
[email protected]

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

You might also like