Sie sind auf Seite 1von 17

C

Programming

  • C is a computer programming language used to create a list of instructions for the computer to follow.

Why Learn C?

Readability Portability Coding Efficiency Useful for all applications Easy to interface with system devices and/or assembly routines

Language of choice for programming embedded systems with hardware interfaces

Steps in Executing the C Program

  • 1. Write a program in C language

  • 2. Save it as a .c extension

  • 3. Compile the program

  • 4. If necessary, make corrections to any errors found during compilation and recompile it

  • 5. Run the program

Structure of a C Program

A C program basically consists of the following:

Header Files

• • Functions Variables Statements & Expressions

Basic C Program A simple C program consisting of a Header (line 1) and Main Function (line 36) is given below:

Basic C Program • A simple C program consisting of a Header (line 1) and Main

Header Files Header files contain definitions of data types and functions of the C program Appropriate header file should be included at the beginning of the source file #include <header file name>

Examples:

#include <stdio.h> defines standard input and output functions #include <math.h> defines common mathematical functions #include <time.h> defines date and time handling functions

Functions

Main building block of any C program that deals with a particular task C program has one or more functions Reusable block of code May take number of parameters and do the required processing and return a value or may not return any value Main Function is mandatory

Main Function

o

The main function is a must for every C program

o

Tells compiler where the program starts

o

Use int main() or void main() to declare the main function

o

Curly braces { } signal the beginning and end of functions and other code blocks

int main()

{

//body – consisting of one or more statements

}

Data Types Data types are used to define the type of data that will be stored in a variable.

o Use int main() or void main() to declare the main function o Curly braces {

Variables

A variable is used to hold a value (numeric or character) during the program execution It must have a type and a name Two main variable types:

o Local Variables

Declared inside the function Can only be accessed by the particular function where they are declared

o Global Variables Declared outside of all functions

Can be accessed by all functions

Characteristics of variable names:

Consists of characters, numbers, and underscore (_) only (no other special characters) Must begin with a character Cannot consist of numbers alone No space between the name Is case sensitive

Variable Declaration

[data type] [name] = [value];

Examples:

Unsigned int count = 0; int count; char a;

*[value] is optional

Constants A constant is a type of variable in which the value remains unchanged throughout the program execution

Constant Declaration Use the #define directive It must be declared outside of a function

• • It usually appears before the first function

#define [name] [value]

Examples:

#define MONTHS_IN_YEAR

12

#define ON

1

#define OFF

0

Reserved Keywords

The following names are reserved by the C language:

auto

else

long

switch

break

enum

register

typedef

case

extern

return

union

char

float

short

unsigned

const

for

signed

void

continue

goto

sizeof

volatile

default

if

static

while

do

int

struct

_Packed

double

Do not use reserved keywords while naming functions, variables, constants

Statement and Expressions An expression is some combination of constants, variables, operators, and function calls.

Examples:

a + b

2*pi*r

wait(time)

A statement is an expression terminated with a semicolon

Examples:

sum = a + b; printf(“Hello!\n”);

C Operat ors

C Operat ors Operator s • A rithmetic +, ‐ , * , / o •

Operator s

A rithmetic +, , * , /

o

C omparison/R elational o <, <=, >, >=, ==, != L ogical Operat ors o && (A ND), || (OR), ! (NOT)

In crement/ De crement ++, ‐‐ i++ is equivalent to i = i + 1

o

o

Loop Structure Loops provide a way to repeat commands and control how many times they are repeated

For Loops o for(exp1;exp2;exp3) {

 

Statement1;

Statement2;

}

 

o

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

 

Count = i + 1; printf(“Count: %d \n”, Count);

}

While Loops o While(expression)

 

{

Statement1;

Statement2;

o

} i = 0 While(i < 11) {

Count = i + 1; i++; printf(“Count: %d \n”, Count);

}

Do… While Loops o Do

o

{

Statement1;

Statement2;

} While(expression); i = 0; do

{

Count = I + 1; i++; printf(“Count: %d \n”, Count);

}

while(i<11);

Conditional Structure Decides what actions to take If Statement Takes an expression in parenthesis and a statement or block of statements. If the expression is ture, then the statement(s) gets executed. Otherwise, the statement(s) is skipped. o if(expression)

o

Statement1;

else if(expression)

Statement2;

else

{

Statement3;

Statement4;

} if(Temp >=90) printf(“It’s hot!\n”); else if (Temp == 75) printf(“It’s warm! \n”); else (Temp <=10) printf(“It’s cold!\n”);

Arrays Collection of the same type of data that is stored in consecutive memory locations

Examples:

int list[10] = {1,2,3,4,5,6,7,8,9,10};

char message[6] = “smile”;

for(i=0; i<100; i++) odd[i] = odd[i] + 1;

//integer array of 10 elements

//character array of 6 elements

//incrementing all array elements

Pointers A pointer is a variable that contains the memory addresses of any other variable

Ability to request both the address and value stored at that address

o

Address Operator (&)

Find out the memory address of a variable &x

 

Example:

#include <stdio.h> int main() {

float x;

x=2.17;

printf("The value of x is %f\n", x); printf("The address of x is %x\n", &x);

}

Results:

The value of x is 2.17 The address of x is EFF14

o

Indirection Operator (*) Returns the contents of the address stored in a pointer variable

*x

Example:

#include <stdio.h> int main() {

int a = 1, b = 78; int *ptr;

ptr = &a; b = *ptr; printf("The value of b is %d\n", b);

}

Result:

The value of b is 1

Pointer Declaration

<data type> *<pointer variable name>;

int *ptr;

Example:

int *p;

int count;

p=&count;

Pointer p is pointing to the variable count. It contains the memory address of count.

Rules for writing a C Program

C is case sensitive Each statement must end with a semicolon (;)

Braces must always match upon pairs, i.e. every opening brace ( { ) must have a matching close

( }

)

Every C program must have a main() function

Programming Style

Readability and Maintainability

o

Each source code file should include a heading that includes:

Name

Date of last modification and version number Description of what the program does

o Comments Provide more information on the program by inserting remarks and/or reminders without affecting the code Block Comments Write on multiple lines /* File Name:

Description:

Date:

*/

Short Comments – Write on one line, usually the same line as code //Write a Comment Meaningful Names Choose names for functions, constants, or variables that indicate the object’s purpose o Indentation

o

There are multiple indentation styles Choose a style and apply it consistently throughout the program Code within block should be indented

Sample P rogram Lighting L EDs

Sample P rogram Lighting L EDs LED Inter f ace 8 LEDs ar e available on

LED Inter face 8 LEDs ar e available on board the LPC2148 micr ocontroller. T hey are conn ected to pin P0.8 – P0.15.

Sample P rogram Lighting L EDs LED Inter f ace 8 LEDs ar e available on

General P urpose Input /Output (GPI O) A generic pin on a chip that can be cont rolled as eith er an input o r an output

Applicatio ns:

D riving LEDs, o r other indic ators

C ontrolling off chip devices

S ensing digital inputs

GPIO pins are controll ed by four 32 bit registers :

 

I OPIN I OSET I OCLR I ODIR

General P urpose Inpu t /Output (GPI O) • A generic pin on a chip tha
General P urpose Inpu t /Output (GPI O) • A generic pin on a chip tha

PINSEL (P in Function S elect Registe rs) E nables you to select which pin function s you would like to use T here are 3 PI NSEL register s:

o PINSE L0 o PINSE L1 o PINSE L2

PINSEL0 a nd PINSEL1 • P INSEL0 conta ins GPIO pins 0.0 to 0.15 • P
PINSEL0 a nd PINSEL1
• P INSEL0 conta ins GPIO pins 0.0 to 0.15
• P INSEL1 conta ins GPIO pins 0.16 to 0.31
PINSEL (P in Function S elect Registe rs) • E nables you to select which pin

E ach pin assig ned a 2bit ad dress

P INSEL0 P
P INSEL0
P

P in

0.15

0. 14

0.13

0 .12

0.11

0.10

0.9

 

0.8

 

0.7

0.6

0.5

0.4

 

0.3

0.2

0.1

 

0.0

B its

31

30

29 ..

28

27

26

2

5

..

24

23

..

22

21

..

20

19

..

18

17

..

16

15

4

13

12

.10

9

..

8

7

..

6

5

..

4

3

..

2

1

..0

P INSEL1

   

P

in

0.31

0.3 0

0.29

0. 28

 

0.27

0. 26

0.25

 

0 .24

 

0.23

0.22

0.21

 

0.20

 

0.19 0. 18

0.17 0.16

B

its

31

30

.28

27

26

25 ..

24

23

22

21 ..

20

19

18

1 7

..

16

15

..

14

1 3

..

12

11

..

10

9

..

8

7

..

6

5

.4

3

..

2

1

..

0

PINSEL2

S pecial case u sed to contro l whether pin s 1.16 to 1.3 1 are used as GPIO pins

P INSEL0 P P in 0.15 0. 14 0.13 0 .12 0.11 0.10 0.9 0.8 0.7

Function Selection Bits T o set pins as GPIO pins, as sign a 2bit v alue of 00 to the appropri ate location i n the PINSEL r egister

F unction Sele ction Bits

B inary Value

Selected Fun ction

0

0

Primary (defa ult) function (al ways GPIO)

0

1

First alternate function

1

0

Second altern ate function

1

1

Third alternat e function

E xample:

P INSEL0 = 0x0 0000000; P INSEL1 = 0x0 x000000;

//Set P0 .0 to P0.15 a s GPIO pins //Set P0 .16 to P0.31 as GPIO pins

IOPIN

R eads the curr ent state of every GPIO p n in the pin block (collect ion of all 32 p pins in GPIO0 ) V alue of ‘1’ m eans pin is cu rrently HIGH V alue of ‘0’ m eans pin is cu rrently LOW E xample:

U se IOPIN regi ster to see if an LED is cur rently turned on or off

I OPIN would r eturn 0 if it w as currently turned on (si nce setting G PIO pin to lo w turns the L ED o n) and return 1 if it was of f (since setti ng GPIO pin t o HIGH turns the LED off).

IODIR

C ontrols the d irection of th e GPIO pin U se this regist er to set pin as either inpu t (0) or outp ut (1) E xample:

IO0DI R = 0x0000 0 100; IO0DI R = 0x0000 0 200;

//pin P0.8 co nfigured as output //pin P0.9 co nfigured as output

IOSET • If GPIO pin is s et as output, use IOSET to set pin to
IOSET
• If GPIO pin is s et as output, use IOSET to set pin to HI GH (providin g small 3.3V electrical cur rent)
IOPIN R eads the cur r ent state of every GPIO p n in the pin

E xample:

IO0SE T = 0x0000 0 100;

//set pin P0. 8 in IO0PIN //turn off pi n P0.8 LED

IOCLR If GPIO pin is s et as output, use IOCLR to set pin to LO OW (providin g a connectio n to GROUN D)

• E xample: IO0CL R = 0x0000 0 100; //clear pin P 0.8 in IO0PIN //turn

E xample:

IO0CL R = 0x0000 0 100;

//clear pin P 0.8 in IO0PIN //turn on pin n P0.8 LED

Sample P rogram Lighting L EDs

• E xample: IO0CL R = 0x0000 0 100; //clear pin P 0.8 in IO0PIN //turn

Hea der File

• E xample: IO0CL R = 0x0000 0 100; //clear pin P 0.8 in IO0PIN //turn

Com ments

• E xample: IO0CL R = 0x0000 0 100; //clear pin P 0.8 in IO0PIN //turn

Functio n

  • 1. C omment Bloc k (lines 1 – 8 ) provides a description o f the written C source cod e. It explains what t he program w ill do.

  • 2. T he preproces sor directive #include and header file ( line 9) <lpc2 14x.h> tells t he C compile r to in clude lpc214 x.h file befor e compiling. The header f ile <lpc214x. h> contains a ll the registe r lo cations for t he ARM7 mic rocontroller.

4.

The main () function (lines 18 – 33) is the start of the executable source code.

  • 5. The statement “IO0DIR = 0x00000C00;” (line 21) sets pins P0.10 and P0.11 as outputs.

  • 6. The while (1) loop (lines 23 – 32) causes a permanent loop. The block of code within that loop is continuously being executed since the condition (while (condition)) always remains true (1 = true).

  • 7. The wait() function is called from the main () function (lines 25 and 29). The program jumps to the wait () function and executes the block of code within that function.

  • 8. IO0SET and IO0CLR (lines 26, 27, 30, and 31) turns the LEDs on and off.