Вы находитесь на странице: 1из 11

Experiment 2

Introduction to C Language Program-


ming
During infancy years of microprocessor based systems, programs were developed using assem-
blers and fused into the EPROMs. There used to be no mechanism to find what the program
was doing. LEDs, switches, etc. were used to check correct execution of the program. Some
very fortunate developers had In-circuit Simulators (ICEs), but they were too costly and were
not quite reliable as well. As time progressed, use of microprocessor-specific assembly-only as
the programming language reduced and embedded systems moved onto C as the embedded pro-
gramming language of choice. C is the most widely used programming language for embedded
processors/controllers. Assembly is also used but mainly to implement those portions of the
code where very high timing accuracy, code size efficiency, etc. are prime requirements.

Embedded System Programming

Embedded programs must work closely with the specialized components and custom circuitry
that makes up the hardware. Unlike programming on top of a full-function operating system,
where the hardware details are removed as much as possible from the programmers notice and
control, most embedded programming acts directly with and on the hardware. This includes
not only the hardware of the CPU, but also the hardware which makes up all the peripherals
(both on-chip and off-chip) of the system. Thus an embedded programmer must have a good
knowledge of hardware, at least as it pertains to writing software that correctly interfaces with
and manipulates that hardware. This knowledge will often extend to specifying key components
of the hardware (microcontroller, memory devices, I/O devices, etc), and in smaller organiza-
tions will often go as far as designing and laying out the hardware as a printed circuit board.
An embedded programmer will also need to have a good understanding of debugging equipment
such as multimeters, oscilloscopes and logic analyzers.

Another difference from more general purpose computers is that most embedded systems are
quite limited as compared to the former. The microcomputers used in embedded systems may
have program memory sizes of a few thousand to a few hundred thousand bytes rather than the
gigabytes in the desktop machine, and will typically have even less data (RAM) memory than
program memory.

14
15

There are many factors to consider when developing a program for embedded systems. Some
of them are:

Efficiency - Programs must be as short as possible and memory must be used efficiently.

Speed - Programs must run as fast as possible.

Ease of implementation.

Maintainability

Readability

Introduction to C Programming Language for Embedded Sys-


tems

Embedded systems are commonly programmed using C, assembly and BASIC. C is a very
flexible and powerful programming language, yet it is small and fairly simple to learn. C gives
embedded programmers an extraordinary degree of direct hardware control without sacrificing
the benefits of high-level languages so its compilers are available for almost every processor in
use today and there is a very large body of experienced C programmers.

C used for embedded systems is slightly different as compared to C used for general purpose
programming (under a PC platform). Programs that are developed for embedded systems are
usually expected to monitor and control external devices and directly manipulate and use the
internal architecture of the processor such as interrupt handling, timers, serial communications
and other available features. C compilers for embedded systems must provide ways to examine
and utilize various features of the microcontrollers internal and external architecture; this
includes interrupt service routines, reading from and writing to internal and external memories,
bit manipulation, implementation of timers/counters and examination of internal registers etc.
Standard C compiler, communicates with the hardware components via the operating system
of the machine but the C compiler for the embedded system must communicate directly with
the processor and its components. For example consider these examples:

p r i n t f ( C Programming f o r Embedded Systems \n ) ;

c = getchar () ;

In standard C running on a PC platform, the printf statement causes the string inside the
quotation to be displayed on the screen. The same statement in an embedded system causes
the string to be transmitted via the serial port pin (i.e., TxD) of the microcontroller provided
the serial port has been initialized and enabled. Similarly, in standard C running on a PC
platform getchar() causes a character to be read from the keyboard on a PC. In an embedded
system the instruction causes a character to be read from the serial pin (i.e., RxD) of the
microcontroller.
16 CHAPTER 2. INTRODUCTION TO C LANGUAGE PROGRAMMING

Template for Embedded C Program

#i n c l u d e l m 4 f 1 2 0 h 5 q r . h

v o i d main ( v o i d )
{
// body o f t h e program g o e s h e r e
}

The first line of the template is the C directive. This tells the compiler that during
compilation, it should look into this file for symbols not defined within the program.

The next line in the template declares the beginning of the body of the main part of the
program. The main part of the program is treated as any other function in C program.
Every C program should have a main function.

Within the curly brackets you write the code for the application you are developing.

Preprocessor Directives

Preprocessor directives are lines included in the code of our programs that are not program
statements but directives for the preprocessor. Preprocessor directives begin with a hash symbol
(#) in the first column. As the name implies, preprocessor commands are processed first.i.e.,
the compiler parses through the program handling the preprocessor directives.

These preprocessor directives extend only across a single line of code. As soon as a newline
character is found, the preprocessor directive is considered to end. No semicolon (;) is expected
at the end of a preprocessor directive. The only way a preprocessor directive can extend through
more than one line is by preceding the newline character at the end of the line by a backslash
(\).

The preprocessor provides the ability for the inclusion of header files, macro expansions, con-
ditional compilation, and line control etc. Here we discuss only two important preprocessor
directives:

Macro Definitions (#define)

To define preprocessor macros we can use #define. Its format is:


#d e f i n e i d e n t i f i e r r e p l a c e m e n t

When the preprocessor encounters this directive, it replaces any occurrence of identifier in the
rest of the code by replacement. This replacement can be an expression, a statement, a block
17

or simply anything. The preprocessor does not understand C, it simply replaces any occurrence
of identifier by replacement. For example:
#d e f i n e DELAY 20000

Wherever, DELAY is found as a token, it is replace with 20000.

Including Files (#include)

It is used to insert the contents of another file into the source code of the current file. There
are two slightly different ways to specify a file to be included:
#i n c l u d e f i l e n a m e

For example:
#i n c l u d e l m 4 f 1 2 0 h 5 q r . h

This include directive will include the file named lm4f120h5qr at this point in the program.
This file will define all the I/O port names for LM4F120 microcontroller.

Bitwise Operations in C

The byte is the lowest level at which we can access data; theres no bit type, and we cant ask
for an individual bit. In fact, we cant even perform operations on a single bit every bitwise
operator will be applied to, at a minimum, an entire byte at a time. This means we will be
considering the whole representation of a number whenever we talk about applying a bitwise
operator. Table 2.1 summarizes the bitwise operators available in C.

Operator Description Example Result


& Bitwise AND 0x88 & 0x0F 0x08
Bitwise XOR 0x0F 0xFF 0xF0
| Bitwise OR 0xCC | 0x0F 0xCF
 Left Shift 0x01  4 0x10
 Right Shift 0x80  6 0x02

Table 2.1: Bitwise Operators in C

Making Decisions

Decision making structures require that the programmer specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if
the condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false. Figure 2.1 is the general from of a typical decision making
structure found in most of the programming languages. C programming language provides
many types of decision making statements. Some of them are briefly described here.
18 CHAPTER 2. INTRODUCTION TO C LANGUAGE PROGRAMMING

start

condition

if condition is true
if condition
is false

conditional
code

end

Figure 2.1: Decision Making Structure

Conditional Statements

Two important conditional statements, if-else and swtich statements, are explained here.

if-else Statements

if-else statement is used, if the programmer wants to execute some code, if the test expression is
true and execute some other code if the test expression is false. Flowchart for if-else statement
is given in Figure 2.2

start

if condition
condition
is false

if condition
is true else code

if code

end

Figure 2.2: if-else Statement


19

Example:
#i n c l u d e <s t d i o . h>

i n t main ( ) {
int a = 100; / l o c a l v a r i a b l e d e f i n i t i o n /

i f ( a < 20 ) / check t h e b o o l e a n c o n d i t i o n /
{
/ i f c o n d i t i o n i s t r u e then p r i n t t h e f o l l o w i n g /
p r i n t f ( a i s l e s s than 20\n ) ;
}
else
{
/ i f c o n d i t i o n i s f a l s e then p r i n t t h e f o l l o w i n g /
p r i n t f ( a i s not l e s s than 20\n ) ;
}
p r i n t f ( v a l u e o f a i s : %d\n , a ) ;
return 0;
}

switch Statements

In switch...case, expression is either an integer or a character. If the value of switch expression


matches any of the constant in case, the relevant codes are executed and control moves out of
the switch...case statement. If the expression doesnt matches any of the constant in case, then
the default statement is executed. Figure 2.3 shows the flowchart for switch statement.

start

expression

case 1
code block 1

case 2
code block 2

case 3
code block 3

default case
code block N

end

Figure 2.3: switch Statement


20 CHAPTER 2. INTRODUCTION TO C LANGUAGE PROGRAMMING

Example:

#i n c l u d e <s t d i o . h>

i n t main ( )
{
/ l o c a l v a r i a b l e d e f i n i t i o n /
c h a r g r a d e = B ;

switch ( grade )
{
c a s e A :
p r i n t f ( E x c e l l e n t ! \ n ) ;
br ea k ;
c a s e B :
c a s e C :
p r i n t f ( Well done \n ) ;
br ea k ;
c a s e D :
p r i n t f ( You p a s s e d \n ) ;
br ea k ;
c a s e F :
p r i n t f ( B e t t e r t r y a g a i n \n ) ;
br ea k ;
default :
p r i n t f ( I n v a l i d g r a d e \n ) ;
}
p r i n t f ( Your g r a d e i s %c \n , g r a d e ) ;

return 0;
}

Loops

Loops causes program to execute the certain block of code repeatedly until some conditions are
satisfied, i.e., loops are used in performing repetitive work in programming. C programming
language provides following types of loop to handle looping requirements.

for Loop

The initial expression is initialized only once at the beginning of the for loop. Then, the test
expression is checked by the program. If the test expression is false, for loop is terminated.
But, if test expression is true then, the codes are executed and increment statement is executed.
Again, the test expression is checked. If it is false, loop is terminated and if it is true, the same
process repeats until test expression is false. Flowchart in Figure 2.4 describes the working of
for loop in C programming.
21

start

for(init; condition; increment)


{
conditional code
} init

if condition
condition
is false

if condition
is true

code block

increment

end

Figure 2.4: for Loop

Example:
#i n c l u d e <s t d i o . h>

i n t main ( )
{
/ f o r l o o p e x e c u t i o n /
for ( int a = 10; a < 20; a = a + 1 )
{
p r i n t f ( v a l u e o f a : %d\n , a ) ;
}

return 0;
}

while Loop

In the beginning of while loop, test expression is checked. If it is true, code inside the body of
while loop is executed and again the test expression is checked and process continues until the
test expression becomes false. Key point of the while loop is that the loop might not ever run.
When the condition is tested and the result is false, the loop body will be skipped and the first
statement after the while loop will be executed. Figure 2.5 represents the flowchart of while
loop.
22 CHAPTER 2. INTRODUCTION TO C LANGUAGE PROGRAMMING

start

while (condition)
{
conditional code
}
if condition
condition
is false

if condition
is true

code block

end

Figure 2.5: while Loop

Example:
#i n c l u d e <s t d i o . h>

i n t main ( )
{
/ l o c a l v a r i a b l e d e f i n i t i o n /
int a = 10;

/ w h i l e l o o p e x e c u t i o n /
w h i l e ( a < 20 )
{
p r i n t f ( v a l u e o f a : %d\n , a ) ;
a++;
}

return 0;
}

Functions

A function is a group of statements that together perform a task. Every C program has at least
one function which is main(), and all the most trivial programs can define additional functions.
You can divide up your code into separate functions. How you divide up your code among
different functions is up to you, but logically the division usually is so each function performs
a specific task. A function declaration tells the compiler about a functions name, return type,
23

and parameters. A function definition provides the actual body of the function. A function is
known with various names like a method or a sub-routine or a procedure etc.

The general form of a function definition in C programming language is as follows:


r e t u r n t y p e f u n c t i o n n a m e ( parameter l i s t )
{
body o f t h e f u n c t i o n
}

Example: Following is the source code for a function called max(). This function takes two
parameters num1 and num2 and returns the maximum between the two:
/ f u n c t i o n r e t u r n i n g t h e max between two numbers /
i n t max( i n t num1 , i n t num2)
{
/ l o c a l v a r i a b l e d e c l a r a t i o n /
int result ;

i f (num1 > num2)


r e s u l t = num1 ;
else
r e s u l t = num2 ;

return r e s u l t ;
}

Lab Exercises

1. Write a function that outputs a right isosceles triangle of height and width n, so n = 6
would look like:

2. Write a function that outputs a right-side-up triangle of height n and width 2n-1; the
output for n = 6 would be:

3. Write a function that computes the factorial of a given number (n) and call this function
in the main program and print the output.
24 CHAPTER 2. INTRODUCTION TO C LANGUAGE PROGRAMMING

4. A palindrome number is a number such that if we reverse it, it will not change. For example
some palindrome numbers examples are 121, 212, 12321. Write a C program that prompts
a user to enter a number and prints a message whether a number is palindrome or not.
(To check whether a number is palindrome or not first we reverse it and then compare the
number obtained with the original, if both are same then number is palindrome otherwise
not.)

Вам также может понравиться