Sie sind auf Seite 1von 29

EMBEDDED -C

BASIC
Training material

DOC Number : TR/SW02/v01

EMBEDDED C

Contents
Contents.........................................................................................................................................................................2
1.

Introduction ...........................................................................................................................................................4

Development of C language ..........................................................................................................................................4


Importance of C language..............................................................................................................................................4
Method of Coding in C ...................................................................................................................................................5
Stages of a C program ....................................................................................................................................................5
Creating the program ....................................................................................................................................................5
Compiling a program .....................................................................................................................................................6
Linking the program .......................................................................................................................................................6
Executing the program ..................................................................................................................................................6
2.

Describe the structure of C program .....................................................................................................................7

Documentation section .................................................................................................................................................7


Linkage section ..............................................................................................................................................................7
Global variable declaration section ...............................................................................................................................8
Main() function ..............................................................................................................................................................8
User defined functions ..................................................................................................................................................9
Comments and Remarks ................................................................................................................................................9
3.

Variables ................................................................................................................................................................9

4.

Data type in C programming language ............................................................................................................... 10

Integer data type ........................................................................................................................................................ 10


Character data type .................................................................................................................................................... 10
Floating point data type.............................................................................................................................................. 10
5.

Different types of Operators in C........................................................................................................................ 10

Arithmetic operators .................................................................................................................................................. 11


Logical operators ........................................................................................................................................................ 11
Relational operators ................................................................................................................................................... 11
Assignment operators................................................................................................................................................. 12
Compound Assignment operators .............................................................................................................................. 12
Conditional operators ................................................................................................................................................. 12
Increment or Decrement operators ........................................................................................................................... 12
Bit wise operators ....................................................................................................................................................... 13
Special operators ........................................................................................................................................................ 13
6.

Input and output operators in C ......................................................................................................................... 14

Decision making and branching in C program: if, else, goto, switch statements ....................................................... 15

SWASTIKA RESEARCH & TRAINING INSTITUTE

EMBEDDED C
Simple if-else statements ........................................................................................................................................... 15
else-if ladder statements ............................................................................................................................................ 15
goto statement ........................................................................................................................................................... 16
switch statement ........................................................................................................................................................ 16
7.

Loops in C programming ..................................................................................................................................... 16

while loop ................................................................................................................................................................... 17


dowhile loop ............................................................................................................................................................. 18
for loop ....................................................................................................................................................................... 18
8.

Your first C Program............................................................................................................................................ 19

How to write program codes in C compiler ................................................................................................................ 20


How to run a C program? ........................................................................................................................................... 21
How to create Stand alone EXE file?........................................................................................................................... 23
9.

Simple Program to Blink an LED (using embedded C language) ......................................................................... 26

SWASTIKA RESEARCH & TRAINING INSTITUTE

EMBEDDED C

1. Introduction
C is a powerful and effective programming language. We can create System software,
Embedded hardware and application software by programming with C. C is
popularly termed as the successor of basic combined programming language known as
B. The B language was implemented in 1960 at Cambridge University. Embedded C
programming is an essential tool for all electronic engineers and developers.

Development of C language
The development of C language is directly related to the Unix operating
system development. C was invented by Dennis Richey and Barian.W in 1972 at Bell
laboratory. C language is compatible with Windows, Dos and Unix operating systems.
The Unix operating system is mainly used for C language development. The coding
done in Unix and the coding method of C is almost similar in structure. Unix operating
system was also developed from Cambridge university.

Importance of C language
C programming language has accurate frame structure, so we can call it as a
structural programming language. There are wide varieties
of functions and operators available in C, it is possible to develop complex
programs, system software, embedded hardware and application software by
manipulating these operators and functions. Group of programs that helps the
working of a computer is known as system software, for example- Compiler,
Interpreter, Operating system, etc. Application software is nothing but a group of
programs that control a single application only; for example MS Word, MS Power
point, etc. C programming is a free language, that is it can run be in any computer
as well. Also the portability feature makes C language more popular. The programs
written in C language are very efficient and effective. For example to add 1 to 10
numbers using C language, it takes lower time as compared to that of written in
Basic.

SWASTIKA RESEARCH & TRAINING INSTITUTE

EMBEDDED C

Method of Coding in C
In normal case we are using small letter English alphabets for program coding,
but capital letters can also be used. Capital letters are often used for defining
some constants or variables. Another symbol for C language coding is {}
brackets. It is used to include the group of codes together while a program is
executing. This helps the programmer to easily identify the faults and errors in the
program. We can write the coding statements in any row, because C is an
independent programming language. Consider an example, a= b+c;
d=e-f;
i=a*b;
Above statements can also be written in single line as,
a=b+c; d=e-f; i=a*b;
It is important to provide semicolon ; at the end of any statement.

Stages of a C program
Programming language is a medium for communication between a computer and a
user. Before studying C programming we must be aware of the different symbols,
words, syntax etc. used in C language. The following are the different stages in a C
program.

Creating the program

Compiling the program

Linking the program

Execution of the program

Creating the program


A computer is ready to accept different programs after loading the operating
system in to the memory of that computer. Now we are going to give program codes
using input devices. These codes should be in the form of a File. A file name
contains two parts- File name and Extension name. These two parts are separated
by a period (.). In this, the Extension name indicates the behavior of that file. For

SWASTIKA RESEARCH & TRAINING INSTITUTE

EMBEDDED C

example a C program file consisting of a name followed by .C extension. That


is istar.c (Red colour indicates the extension)

Compiling a program
After the development of a program, we must convert it in to machine level
language from high level language because computer knows machine level
language only. The media for this conversion is called as compiler. Compiler is
simply a translating program, it translate High level language to machine level
language. The high level language programs written by the programmer are
called source codes. These source codes are then converted to machine level language
using compiler, and then it is known as objective program. A compiler is capable of
identifying the syntax errors in the program but it cant identify the logical
mistakes.

Linking the program


The process of connecting all the functions and other programs together for creating
our program is called linking. For example the object code of printf() function is stored in
the library files of the system, so at the stage of linking the object codes in library file
is linked to the main function.

Executing the program


The object code execution starts after the finishing of linking process. User gives the
necessary inputs at this stage.

SWASTIKA RESEARCH & TRAINING INSTITUTE

EMBEDDED C

2. Describe the structure of C program


Now C language has its own structure to write a program, that is there are particular
rules for writing codes in C. These rules are called Syntax Rules. All the codes written
in a C program is based on these syntax rules. We can classify a C program as many
sections, the different sections in a C program are followed, this is a general way of
representation.

1
2
3
4
5
6
7
8
9
10
11
12

Documentation section
Linkage section
Global variable declaration section
Main()
{
Local variable declaration part;
Execution part;
}
User defined functions()
{
..........;
}

Documentation section
Name of program, name of programmer, date etc. are included in the documentation part. These are non
executable. To start and stop documentation we are using /* and */ command. For example,
1 /*This program is done by i-St@r*/
2 /*Written date xx-06-2012*/

In Embedded C we are using // for commenting like,


1 //This program is done by i-St@r
2 //Written date xx-06-2012

Linkage section
In this section we provide instructions for linking different functions from the system library to the compiler.
This section is also known as Pre Processing stage, because this will run before the main() at the time of
execution. The file name starts with # symbol. For example,#include. Here we included the library

SWASTIKA RESEARCH & TRAINING INSTITUTE

EMBEDDED C

function stdio.h in our program. stdio.h contain standard input output functions. Without the stdio.h header
file the commands printf(), scanf() etc will not work.

Global variable declaration section


The variables declared in this section are accessible from any program. Any function other
than main() can use this variables. For example,
1
2
3
4
5
6
7
8
9
10

Int a,b,c
Main()
{
a=10;
b=2;
}
Function1()
{
c=a+b;
}

Here the variables a, b, c are global variables. The main() and function1() can also access these variables.

Main() function
We can group some codes together, these grouped program codes are called functions. Main()is the entry
function of any program. It indicates the starting of program. There are two sections in main function(),
1.Declaration part
In this part we declare all the variable used in the main() program. The variables cannot be accessible from
outside of main() function. For example
1
2
3
4
5

Main()
{
int a,b,c;
. ;
}

2. Executable part
Different operations are included in this part. For example
1 Main()
2 {
3 int a,b,c;/*Declaration part*/
4 a=b+c; /*Execution part*/

SWASTIKA RESEARCH & TRAINING INSTITUTE

EMBEDDED C

5 }

We can write main() function once in a program, so main() works as a built in function.
The user combines all other functions in main() section.

User defined functions


The functions defined by user and called from main() function are known as user defined
functions. All the user defined functions are written after the main() function.
In Embedded C, user defined functions are written before main().

Comments and Remarks


/* and */ are used anywhere in the program to indicate some information to another
programmer, this will help the programmer in the Debugging process also, another
user can easily understand the logic.

3. Variables
Variable is used to store a value. This value will change according to different situations
while the program is executing.
Rules for a variable
o

Variable name should start with a letter.

Cannot exceed 31 letters.

Variable name is case sensitive, that is a not equal to A.

Variable name should not be a keyword eg: int, float, if, else, etc.

Blank spaces are not allowed.

SWASTIKA RESEARCH & TRAINING INSTITUTE

EMBEDDED C

4. Data type in C programming language


Data types indicate the nature of data; it gives some information to user. So the user
should decide the type of data at the initial stage of the program, then only the
compiler can interpret the data. There are different types of data types in C
program language. Operators are used to perform certain operations in C.

Integer data type


It represents the integer data. It can be represented by a keyword int in the C
language, also an integer data type can hold positive and negative values. 2 byte
memory will allocate for this int.

Character data type


To represent a character value we are using character data type. This is represented
by keyword char.
1 byte memory is reserved for char.

Floating point data type


It is used to represent a floating point number (eg: 12.47).
Syntax is float

5. Different types of Operators in C


The symbols that give instructions to perform different types
of mathematical and logicaloperations are called operators. We can define operators
as the tools which can alter the values of data and variables. The important operators
used in C language are:

Arithmetic operators

Logical operators

Relational operators

Assignment operators

Conditional operators

Increment or decrement operators

10

SWASTIKA RESEARCH & TRAINING INSTITUTE

EMBEDDED C

Bit wise operators

Special operators

Arithmetic operators
Arithmetic operators are commonly used operator in programming languages. C
programming language consists of Binary arithmetic and Unary arithmetic. The
data, which is operated by the operator, is called operand. In Unary operation there
will be only one operand (eg: -1Negative number). To perform a binary
arithmetic, we need at least 2 operands. Different arithmetic operators are given
below:

Logical operators
Logical operators are also called Boolean operators. These operators are used
to check two or more conditions. Boolean operators are followed:

Relational operators
Operators used to compare two values according to their relation are called Relational
operators. These are also called Comparison operators. For performing relational
operation we must need two operands, then only we can illustrate and check the

11

SWASTIKA RESEARCH & TRAINING INSTITUTE

EMBEDDED C

relation between them. 6 relational operators are:

Assignment operators
Assignment operators are used to assign a value to a variable. = is used as assignment
operator. For example i=10;

Compound Assignment operators


These operators are used to assign a value to variable after getting a desired result.
For example x+=z;That is x=x+z;
Both of the above expressions have same meaning but first expression uses short
handCompound assignment operator and second expression uses simple
assignment operator. The different compound operators are:

Conditional operators
These operators work according to some condition. The syntax is given by
i=expression1? Expression2:expression3
Eg: i=a>b?a:b;
The meaning of above statement is if a>b, then i=a, else i=b

Increment or Decrement operators


The powerful operators in C are increment and decrement operator. ++ is used as
increment operator and used as decrement operator.

12

SWASTIKA RESEARCH & TRAINING INSTITUTE

EMBEDDED C

Eg: i++; meaning

i=i+1;

i; meaning i=i-1;

Bit wise operators


Bitwise operators are used to test the bit or to shift the bits to either left or right.
Operators and its use are given below:

Special operators
Comma operator (,) and Size of operator are the special operators in C.

Comma operator (,)


It is used to connect related expressions.
Eg: Sum= (a=7,b=3,a+b);Here first the compiler assign 5 to a then 7 to b after that it
calculate the result of 7+3 and the result 10 is assigned to the variable Sum.

Size of operator
For calculating the length of a variable we are using size of operator. It will calculate
thenumber of bytes in that variable.
Syntax
i=size of(variable);

13

SWASTIKA RESEARCH & TRAINING INSTITUTE

EMBEDDED C

6. Input and output operators in C


Inbuilt (pre defined) functions are available in C to perform different input
output (I/O) operations. On our 5th day we are discussing about basic input output
functions and branching instructions or control statements in C. Branching
statements are used to change the execution sequence of a running program. if-else,
goto, switch are the important control statements in C language

Scanf()
We can read any value using this function.
Syntax:
scanf(%d,&a);

Meaning:
Here the compiler accept a value (integer type) from the keyboard and it
is saved in theaddress of a. Here %d indicates that the value is integer data type. To
read other data types refer the following:
%d reads Integer data type
%f reads Floating point data type
%c reads Single character
%s reads String value
%o reads Octal integer
%x reads Hexadecimal integer
printf()
Used to display an output data in standard output device.
Syntax:
printf(i-St@r Electronics);
Above statement displays i-St@r Electronics on the monitor
Another syntax:
printf(%d,a); It displays the value of variable a in the monitor.

14

SWASTIKA RESEARCH & TRAINING INSTITUTE

EMBEDDED C

Decision making and branching in C program: if, else, goto, switch statements
We can arrange the execution sequence of a program in different ways using decision
making and branching statements. These instructions are also called as control
statements.

Simple if-else statements


if-else statements are very powerful and effective tool for decision making in C. In this
situation, program codes are divided in to two sections and we are selecting one
part using if statement. else part is optional so we can neglect it if not needed.
Syntax:
1 if(expression)
2 {
3 Statement1;
4 }
5 else
6 {
7 Statement2;
8 }

Here if the expression is true, the statement1 will execute and if it


is false, statement2 will execute.

else-if ladder statements


Simple if-else statements are used to select a part of codes from two sections. But else
if ladder is used to make decisions when there are many conditions.
Example:
1
2
3
4
5
6
7
8

if(expression 1)
{statement 1;}
else if(expression 2)
{statement 2;}
else if(expression 3)
{statement 3;}
else
{statement 4;}

Here the compiler makes decision from 4 conditions.

15

SWASTIKA RESEARCH & TRAINING INSTITUTE

EMBEDDED C

goto statement
It is used in unconditional branching. The syntax of goto statement is given below:
1
2
3
4
5
6
7
8
9

Goto Label;
Statement 1;
Statement 2;
;
;
Statement n;
Label:
Statement x;
Statement y;

Here the Statement 1 to n will not be executed, before the execution,


program sequence branched to Label.

switch statement
This statement is used for multiple branching. Here the branching takes place

according to a valid expression.


Syntax:
1
2
3
4
5
6
7

Switch(expression)
{
Case 1: statement 1; break;
Case 2: statement 2; break;
;
Default: Statement; break;
}

7. Loops in C programming
The statements which appear in the source code only once but execute many
times, such kind of statements are called loops. Repeated executions of certain
statements are popularly known as loops. Almost all the programming languages
support looping instructions. In C program while, do while, for are the looping instructions.

16

SWASTIKA RESEARCH & TRAINING INSTITUTE

EMBEDDED C

For example, consider you want to calculate the sum of 1 to 10 numbers; the program
will be like this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

#include<stdio.h>
#include<conio.h>
main()
{
int n=1,sum=0;
loop:
sum=sum+n;
if(n==10)
{
Goto out:
}
Else
{
N=n+1;
Goto loop;
}
Out:
Printf(\nSum = %d,sum);
}

In the above program the statement sum=sum+n will execute 10 times. A loop will
execute continuously till it satisfy the loop exit condition.
The following processes are included in a loop.
o

Declaration of a counter variable or loop control variable.

Execution of statements inside loop body.

Evaluating the test conditions.

Incrementing or decrementing the counter (loop control) variable.

There are three types of statements available in C language to implement loops.

while loop
It is an entry controlled loop, the loop body will execute till the test condition is false.
Thesyntax of while() loop is given below,
1
2
3
4

17

While(test condition)
{
Body of the loop;
Increment ore decrement;
SWASTIKA RESEARCH & TRAINING INSTITUTE

EMBEDDED C

5 }

Example: sum of 1 to 10 numbers


1
2
3
4
5
6
7
8
9
10
11
12

#include<stdio.h>
#include<conio.h>
Main()
{
Int n=1,sum=0;
While(n<=10)
{
Sum=sum+n;
N++;
}
Printf(\nsum= %d,sum);
}

If the test condition is always true, indefinite loop will arise. That is the body will
execute without break. This method is used in any embedded C
programming. while(1) is commonly used to create indefinite loops. So while(1) is an
essential part of any embedded C programming.

dowhile loop
This is an exit controlled loop, because the loop body will execute at least
once even if the test condition is false.
Syntax:
1
2
3
4
5

Do
{
Body of the loop;
}
While(test condition);

When the program control reaches the do, the body will execute once, it will verify the
test condition only after the first execution of loop body.

for loop
It is somewhat efficient entry controlled loop in C program.
Syntax:

18

SWASTIKA RESEARCH & TRAINING INSTITUTE

EMBEDDED C

1
2
3
4

For(initialization;test condition;increment or decrement)


{
Body of the loop;
}

Execution of for loop:


o

We are initializing a counter variable (loop control variable) i=0 or 1, something like that.

Evaluation of test condition. If the condition is true, to body will execute.

After the execution, the value of loop control variable is either incremented or decremented, again
validates the test condition.

If the condition is true, to body will execute, and this process will repeat.

When the test condition fails, the loop terminates.

Example: Sum of 1 to 10 numbers


1
2
3
4
5
6
7
8

#include<stdio.h>
#include<conio.h>
Main()
{
Int sum=0;
For(n=1;n<=10;n++)
Sum=sum+n;
}

8. Your first C Program


This example program accepts two numbers from the user and calculates its sum. After that it checks whether
the sum is greater than 10 or not. If it is greater than 10, displays Result is greater than 10 otherwise
displays Result is less than 10 on the monitor.
Program codes are given below, it is easy to understand and well commented.
1
2
3
4
5
6
7

#include<stdio.h>
#include<conio.h>
main()
{
float a,b,s; /*Declaring 3 floating point variables*/
clrscr(); /*Clear screen*/
printf("Enter the 1st number= ");

19

SWASTIKA RESEARCH & TRAINING INSTITUTE

EMBEDDED C

8 scanf("%f",&a); /*Read a value from Keyboard and save it in address of a*/


9 printf("\nEnter the 2nd number= ");
10 scanf("%f",&b); /* Read next value from Keyboard and save it in address of b */
11 s=a+b;
12 printf("\nSum= %f",s);/*Display the result*/
13
14 if(s>10)
15
{
16
printf("\nResult is greater than 10");
17
}
18 else
19
{
20
printf("\n\nResult is less than 10");
21
}
22 getch();/*To retain the program on screen*/
23
24 }

How to write program codes in C compiler


Refer the scree shots below.

Step 1: Create a new file

20

SWASTIKA RESEARCH & TRAINING INSTITUTE

EMBEDDED C

Step 2:: Extend the editor window by clicking in the arrow mark shown

How to run a C program?


Step 3:Now write your first C program codes in the editor window, then Run

21

SWASTIKA RESEARCH & TRAINING INSTITUTE

EMBEDDED C

22

SWASTIKA RESEARCH & TRAINING INSTITUTE

EMBEDDED C

How to create Stand alone EXE file?


Open File>Save

Change the NONAME00.CPP in to any other name here we provided istar.cpp

23

SWASTIKA RESEARCH & TRAINING INSTITUTE

EMBEDDED C

Then Run the program again

24

SWASTIKA RESEARCH & TRAINING INSTITUTE

EMBEDDED C

Then Close the window

Now navigate to your installation directory that is C++ Installation> TurboCPP

Now you can see ISTAR.EXE application file. Double click on the file, it is your stand alone EXEfile.

25

SWASTIKA RESEARCH & TRAINING INSTITUTE

EMBEDDED C

9. Simple Program to Blink an LED (using embedded C language)


Before we go in detail of how to blink an LED(light emitting diode) with microcontroller,
let us have a brief introduction on GPIO (general purpose I/O (input / Output)).

GPIO Introduction

The GPIO line of any microcontroller can be used mainly to perform two things

26

SWASTIKA RESEARCH & TRAINING INSTITUTE

EMBEDDED C

1. Generate a digital signal

2. Read a digital signal

The digital signal can be of TTL / CMOS logic depending up on the microcontroller .In
general, the microcontrollers are provided with GPIO lines except for some
microcontrollers which are very application specific and may not have GPIO lines.

The process of controlling GPIO lines for most of the controllers are similar in nature.
There are mainly two configurations for any GPIO

GPIO configured as an input


GPIO configured as an output
The GPIO which is configured as input can read a digital signal from an external device,
the external device can be a battery charge indicator, signal from a sensor or any
device

which you intend to use in performing certain functions. Same way when you

wish to generate a digital signal then the GPIO will be configured as an output and the
GPIO output can generate a digital signal, which can be fed to an external device.

Let us see an example to understand a practical application of a GPIO.

Example: Design an indicator for a battery charger using GPIO

Now let us assume that there is a circuitry which gives a digital signal to microcontroller
when ever the battery is charged. So, microcontroller reads the digital signal from the
battery charger and then generates a digital signal to blink an LED indicator.

Configuring GPIO

The configuration of GPIO for various microcontrollers have almost similar procedure,
but the procedure is not completely same for all microcontrollers. There may be few
more steps to be considered, depending on the microcontroller. In this document the
common configuration procedure is explained.

27

SWASTIKA RESEARCH & TRAINING INSTITUTE

EMBEDDED C

Steps to generate a digital high using GPIO

Step 1: Configure the GPIO bit direction register as output

Step 2: Set the GPIO bit data/port register as high

Steps to read digital signal using GPIO

Step 1: Configure the GPIO bit direction register as input

Step 2: Read the GPIO bit data/port register

Example program to blink an LED(Code implemented with microcontroller


atmega8535)
#include <io.h>
/* This program is compiled using WINAVR platform*/
/* Assumptions
PORT B0 pin of the microcontroller atmega8535 is connected to an LED circuit */
int main()
{
unsigned int i =0;
/* Configure the GPIO B0 bit direction register as output */
DDRB = 0x01;
while(1)
{
for (i=0;i<50000;i++)
{
/* Set the GPIO bit data/port register as low */
PORTB = 0x00;
}

28

SWASTIKA RESEARCH & TRAINING INSTITUTE

EMBEDDED C

for (i=0;i<50000;i++)
{
/* Set the GPIO bit data/port register as HIGH */
PORTB = 0x01;
}
}
return 0;
}
/* End of Program */
Result
LED blinks continuously as long as the microcontroller is powered ON.

29

SWASTIKA RESEARCH & TRAINING INSTITUTE

Das könnte Ihnen auch gefallen