Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 93

C PROGARMMING FOR

MICROCONTROLLER
INTRODUCTION
History of C language
It is a structured, high-level, machine independent
language.

It allows software developers to develop programs


without worrying about the where they will be
implemented.
UNIX is one of the most popular network operating
systems in use today and the heart of the internet data
superhighway.

Today, C is running under a variety of operating system


and hardware platforms.
Cont….
Importance of C
• It is a robust language whose rich set of built-in functions.
• Operators can be used to write any complex program.
• Program written in C are efficient and fast.
• Its variety of data types and powerful operators.
Ex- A program to increment a variable from 0 to 15000
takes about one second in C while it takes more than 50
seconds in an interpreter BASIC.
 C is highly portable.
 C programs written for one computer can be run on
another with little or no modification.
 C language is well suited for structured programming.
Contd…
This modular structure makes program debugging, testing
and maintenance easier.
 Important feature of C is its ability to extend itself.
A C program is basically a collection of functions that are
supported by the C library.
 Continuously add our functions to C library.The
programming task becomes simple.
Assembly Vs. C
Some Sample C Programs and Analyze
PRINTNG A MESSAGE
Main()
{
/*…..printing begins…….*/
printf(“I see, I remember”);
/*…..printing ends…….*/
}
Program is main and the execution begins at this line.
The main() is a special function used by the C system to tell
the computer where the program starts.
BY using more than one function compiler can not understand
which one marks the beginning of the program.
Contd…
The opening brace “{” in second line mark the beginning
of the function main and the closing brace “}” in the last
line indicates the end of the function.
All the statements between these two braces form the
function body.
Function body contains a set of instructions to
perform the given task.
The line beginning with /* and ending with */ are
known as comment lines.
The comment line /* = = = =*/ = = = =*/ = = =*/ is not
valid and therefore results in an error.
Contd…
printf() function only executable statement of the program
printf(“I see, I remember”);
printf() is a predefined standard C function for printing
output.
Predefined means that it is a function that has already
have written and compiled and linked together with our
program at the time of linking.
The printf function causes everything between the starting and
the ending quotation marks to be printed out . In this case , the
output will be :
I see, I remember
Cont…
 Every statement in C should end with a semicolon(;) mark.
 suppose we want to print the above quotation in two lines as

I see,
I remember!
The information contained between the parentheses is called the
argument of the function.
 This argument of the first Printf function is I see, /n’’ and the
second is I remember!”.
 These argument are simply strings of character to be printed out.
 printf contains a combination of two characters \ and n at the end
of the string.
 \n collectively called the newline character and instruct the
computer to go to the next (new) line.
No space is allowed between \ and n.
Contd…
Possible to produce two or more lines of output by one printf
statement with the use of newline character at appropriate
places. e.g. printf(“I see,\n I remember !”);
Will print
I see,
I remember !
while the statement
printf(“I\n.. See, \n… …. ….I\n… … … …
remember !”);
will print
I
.. See,
………I
… … … … remember !
Contd…
Some authors recommend the inclusion of the statement
#include<stdio.h>
At the beginning of all programs that use any input/output
library function
This is not necessary for the function printf and scanf
which have been defined as a part of C language.
• C makes a distinction between uppercase and lowercase
letters.
• printf and PRINTF are not the same.
• In C everything is written in lowercase letter.
• Uppercase letters are used for symbolic names
representing constants.
Contd..
General format of simple program and all C program
need a main function.
The main function()
C permits different forms of main statement.
Following forms are allowed
 main()
 int main()
 void main()
 main(void)
 void main(void)
 int main(void)
 The empty pair of parenthesis indicates that the function has no arguments.
 Keyword void means that the function does not return any information to
the operating system
 int means that the function returns an integer value to the operating system
 When int is specified, the last statement in the program must be “return 0”
C standard library
C program using the if statement
C program using the if statement
C program using loop
C program for implementing conditional loop

Output: Ten times


XYZ
Implementing infinite loop

While(1)
For(;;);

For embedded systems:


Infinite loops are always required for MCU based
applications
C program switch case
ADDING TWO NUMBER
Below C program is for addition of two number and displays result.
/* program addition
Main()
{
int number;
float amount;
number=100;
amount=30.75+75.35;
printf(“%d\n”, number);
printf(“%5.2f”,amount);
}

Output
100
106.10
Contd…
number and amount are variable name and what types
of data they hold.
int number;
float amount;
Tells the compiler that number is an integer(int) and
amount is a floating(float) point number.
The word int and float are called the keywords and
can not used as a variable name.
number=100;
amount=30.75+75.35;
are called the assignment statements and have a
semicolon at the end.
Contd…
Output statement that prints the value of number.
The print statement
printf(“%d\n”,number);
Contains two argument. The first argument “%d” tells
the compiler that the value of second argument
number should be printed as decimal integer.
Printf(“%5.2f”,amount); prints out the value of amount
in floating point format.%5.2f tells the compiler that
the output must be in floating point with five places in
all and two places to the right of the decimal point.
Contd…
A # define instructions defines value to a symbolic constant for use
in the program.
 Whenever a symbolic name is encountered, the compiler
substitutes the value associated with the name automatically.
 To change the value, we have to simply change the definition.
 These values remain constant throughout the execution of the
program.
 A # define lines should not end with a semicolon.
 A # define instructions are usually placed at the beginning before
the main() function.
 The defined constants are not variables.
We may not change their values within the program by using an
assignment statement.
Ex. PRINCIPAL= 10000.00;
Is illegal


Contd…

They can also be declared as


float amount;
float value;
float inrate;
When two or more variables are declared in one
statement, they are separated by a comma.
While is a mechanism for evaluating respectively or a
statement/group of statements.
USE OF SUBROUTINES
Illustrate the use of user-defined function and math function through
sample program
A very simple program that using a user defined function i.e. mul() function.

/*---program using function*/


int mul(int a, int b); /*----declaration ---*/
/*------Main program begins------*/
main()
{
int a, b, c;
a=5;
b=10;
c=mul( a, b);
printf(“multiplication of %d and %d is %d”, a, b,c);
}
/*----Main program ends
Mul() function starts----*/
Contd…
int mul(int x, int y)
{
int p;
p=x*y;
return(p);
}
/* Mul() function ends*/

The mul function multiplies the values of x and y and the result is
returned to the main() function when it is called in the
statement.
c=mul(a, b);
The mul() has two argument x and y that are declared as integer.
The value a and b are passed on to x and y respectively when the
function mul() is called.
The #include Directive
C programs are divided into modules or functions.
some function are written by user and store in the C
library.
Library functions are grouped category wise and stored in
different files known as header files.
To access the functions stored in library, necessary to tell
the compiler about the files to be accessed.
#include<filename>
• file name is the name of library file that contains the
required function definition.
• Preprocessor directives are placed at the beginning of a
program.
BASIC STRUCTURE OF C PROGRAMS
Any C program is consists of 6 main
sections.
C program can be viewed as a group of
building blocks called functions.
A function is a subroutine that may include
one or more statements designed to perform
a specific task.
Contd…
Contd…
Contd…
Various section and Use
Documentation: Consists of comments, some
description of the program, programmer name and
any other useful points that can be referenced later.
Link: Consists of the header files of the functions
that are used in the program. Provides instruction to
the compiler to link function from the library
function.
Definition: Consists of symbolic constants or macros
Global declaration: Can be used anywhere in the
program. Consists of function declaration and global
variables.
Contd…
main( ){ }: Every C program must have a main()
function which is the starting point of the program
execution and contains two parts, declaration and
executable part. The declaration part declares all the
variables that are used in executable part. Must be
written in between the opening and closing braces end
with a semicolon (;). 
variable declaration: In C programming we cannot
create variable anywhere like c++ or java so need to
declare variable before body of program.
Subprograms or function: User defined functions
that are used to perform a specific task. These user
defined functions are called in the main() function.
Contd…
Different sections of the above code
Documentation:/*This section contains a multi line
comment or name of program.  description: program to
call function add(); */ 
In C, we can create single line comment using two forward
slash // and we can create multi line comment using /*
*/. Comments are ignored by the compiler and is used to
write notes and document code.
Link:This section includes header file. 
#include <stdio.h> 
#include<conio.h> 
We are including the stdio.h input/output header file from
the C library.
Contd…
Definition: This section contains constant. 
#define max 10 
In the above code we have created a constant max and
assigned 10 to it. 
The #define is a preprocessor compiler directive which is used
to create constants. We generally use uppercase letters to
create constants. 
The #define is not a statement and must not end with a ;
semicolon.
Global Declaration: This section contains function
declaration. 
void add(); 
int x=10; 
We have declared an add function which print Hello add . 
main( ) function
Contd…
 
This section contains the main() function. 
int main(){ 
int a=10; 
printf("Hello Main"); 
return 0; 

This is the main() function of the code. Inside this function we
have created a integer variable a and assigned 10 to it. 
Then we have called the printf() function to print Hello Main.
Subprograms or Function
This section contains a subprogram or function i.e add( ) or
any no of user defined function . 
void add() { 
void add(){ 
printf(" Hello add ") ; 

Character set of C
Character:-It denotes any alphabet, digit or special symbol
used to represent information.
 
Use:-These characters can be combined to form variables. C
uses constants, variables, operators, keywords and
expressions as building blocks to form a Basic c program
 
Character set:-The character set is the fundamental raw
material of any language and they are used to represent
information.
Contd…
The characters in C are grouped into the
following two categories:
1.      Source character set
                                a.      Alphabets
                                b.      Digits
                                c.      Special Characters
                                d.      White Spaces
2. Execution character set
                                a.     Escape Sequence
Source character set
1. ALPHABETS
            Uppercase letters                 A-Z
            Lowercase letters                 a-z

2. DIGITS                                                  0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Contd…
3.Special Characters
~ tilde
%percent sign
| vertical bar
@ at symbol
+ plus sign
< less than
& ampersand
$ dollar sign
* asterisk \ back slash ,etc.
Contd…
4.White space Characters.
\b blank space
\t horizontal tab
\v vertical tab
\r carriage return
\f form feed
\n new line
\\ Back slash
\’ Single quote
\" Double quote
\? Question mark
\0 Null
\a Alarm (Audible Note)
Contd…
Execution Character Set:
Execution characters set are always represented by a
backslash (\) followed by a character.
They are used in output statements. Escape sequence
usually consists of a backslash and a letter or a
combination of digits. 
Each one of character constants represents one
character, although they consist of two characters.
These characters combinations are called as escape
sequence.
Contd…
Character                      ASCII  value    Escape Sequence             Result

Null                                          000                   \0                                    Null

Alarm (bell)                            007                  \a                                    Beep Sound

Back space                            008                  \b                                   Moves previous position

Horizontal tab                        009                  \t                                    Moves next horizontal tab

New line                                 010                  \n                                   Moves next Line

Vertical tab                             011                  \v                                   Moves next vertical tab

Form feed                              012                  \f                                    Moves initial position of next page

Carriage return                     013                  \r                                    Moves beginning of the line

Double quote                       034                   \"                                    Present Double quotes

Single quote                         039                   \'                                    Present Apostrophe

Question mark                     063                   \?                                  Present Question Mark

Back slash                            092                   \\                                   Present back slash
C program to print all the characters of C character Set
#include<stdio.h>
#include<conio.h>
int main()
{
int i;
clrscr();
printf("ASCII ==> Character\n");
for(i = -128; i <= 127; i++)
printf("%d ==> %c\n", i, i);
getch();
return 0;
}
Tokens in C
In a C program smallest individual units are known as C tokens
A C program consists of various tokens
Token is either a keyword, an identifier, a constant, a string literal, or a
symbol.
For example, the following C statement consists of six type of tokens −
C TOKENS EXAMPLE PROGRAM:
int main()
{
   int x, y, total;
   x = 10, y = 20;
   total = x + y;
   printf ("Total = %d \n", total);
}
where,
main – identifier
{,}, (,) – delimiter
int – keyword
x, y, total – identifier
main, {, }, (, ), int, x, y, total – tokens
Keywords:
Keyword and Every c word is classified as either a keyword or an identifier.
Identifiers
All keywords have fixed meanings and these meaning can not be
changed.
Keywords are predefined, reserved words used in programming that have
special meanings to the compiler.
Keywords serve as basic building block for program statements.
All keywords must be written in lowercase.
Underscore character is also an identifier and used as a link between two
words in long identifiers.

ANSI C Keyword
Contd…
Identifier:
A C identifier is a name used to identify a variable, function,
or any other user-defined item.
An identifier starts with a letter A to Z, a to z, or an
underscore '_' followed by zero or more letters, and digits (0
to 9).
C does not allow punctuation characters such as @, $, and %
within identifiers.
C is a case-sensitive programming language. Thus, Manpower
and manpower are two different identifiers in C.
Here are some examples of acceptable identifiers −
mohd zara abc move_name
myname50 _temp j a23b9
retVal a_123
Constants:
Constant in c refer to fixed values that do not change
during execution of a program.
Constants are like a variable
Value remains the same during the entire execution of
the program.
Constants are also called literals.
Constants can be any of the data types.
It is considered best practice to define constants using
only upper-case names.
Syntax:
const type constant_name;
Basic types of C constant:
Primary Constants
Numeric Constants
 Integer Constants
 Real Constants

Character Constants
 Single Character Constants
 String Constants
 Backslash Character Constants
Contd…
Contd…
Given below is the list of special characters and their
purpose.
By “const”
HOW keyword:INwhen
TO USE CONSTANTS you try to change constant values after defining
A C PROGRAM? in C
program, it will through error.
EXAMPLE PROGRAM USING CONST KEYWORD IN C:
#include<stdio.h>
OUTPUT:
void main() value of height : 100
{ value of number : 3.140000
value of letter : A
const int height = 100; /*int constant*/ value of letter_sequence : ABC
const float number = 3.14; /*Real constant*/ value of backslash_char : ? 
const char letter = 'A'; /*char constant*/
const char letter_sequence[10] = "ABC"; /*string constant*/
const char backslash_char = '\?'; /*special char const*/
printf("value of height :%d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);
printf("value of backslash_char : %c \n", backslash_char);
}
#include <stdio.h>
EXAMPLE PROGRAM USING #DEFINE PREPROCESSOR DIRECTIVE IN C:

#define height 100


Output:
#define number 3.14
value of height : 100
#define letter 'A' value of number : 3.140000
#define letter_sequence "ABC" value of letter : A
value of letter_sequence : ABC
#define backslash_char '\?' value of backslash_char : ?
void main()
{
printf("value of height : %d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n",letter_sequence);
printf("value of backslash_char : %c \n",backslash_char);
}
Variable…contd
Variable name Valid? Remark

First_tag Valid

Char Not valid Char is a keyword

Price$ Not valid Dollar sign is illegal

group one Not valid Blank space is not


permitted
avevge_number Valid First eight characters are
significant

int_type Valid Keyword may be part of


name

Examples of variable names


Data Types
C language is rich in its data types.
ANSCI C supports three classes of data types:
Primary(or fundamental) data types
Derived data types
User-defined data types
All C compilers support five fundamental data types,
namely integer(int),character(char),floating
point(float),double-precision floating point(double) and
void.
• Also extended data types such as long int, long double.
Data Types…contd
Contd…
Contd…
C data types are defined as the data storage format that a
variable can store a data to perform a specific operation.
Data types are used to define a variable before to use in a
program.
Size of variable, constant and array are determined by
data types.
ANSI C provides three types of data types:
Primary(Built-in) Data Types:
void, int, char, double and float.
Derived Data Types:
Array, References, and Pointers.
User Defined Data Types:
Structure, Union, and Enumeration.
Contd…
Primary data types:
Every C compiler supports five primary data types:
Void: As the name suggests, it holds no value and is
generally used for specifying the type of function or what
it returns. If the function has a void type, it means that
the function will not return any value.
Int Used to denote an integer type.
Char Used to denote a character type.
float, double Used to denote a floating point type.
int*,float*,char* Used to denote a pointer type.
Derived data types:
C supports three derived data types:
Contd…
Arrays: Arrays are sequences of data items having
homogeneous values. They have adjacent memory
locations to store values.
References: Function pointers allow referencing
functions with a particular signature.
Pointers: These are powerful C features which are used
to access the memory and deal with their addresses.
User define data types:
C allows the feature called type definition which allows
programmers to define their identifier that would
represent an existing data type. There are three such
types:
Contd…
Structure: It is a package of variables of different
types under a single name. This is done to handle data
efficiently. "struct" keyword is used to define a
structure.
Union: These allow storing various data types in the
same memory location. Programmers can define a
union with different members, but only a single
member can contain a value at a given time.
Enum: Enumeration: is a special data type that
consists of integral constants, and each of them is
assigned with a specific name. "enum" keyword is used
to define the enumerated data type.
Contd…
Operator expression
An operator is a symbol that tells the computer to perform
certain mathematical or logical manipulation.
Operators are used in program to manipulate data and
variables.
Operators, functions, constants and variables are combined
together to form expressions.
Consider the expression A + B * 5. where, +, * are operators, A,
B  are variables, 5 is constant and A + B * 5 is an expression.
Types of c operators:
C language offers many types of operators. They are:
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
Contd…
5. Bit wise operators
6.Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators
Arithmetic operators:
C Arithmetic operators are used to perform mathematical
calculations like addition, subtraction, multiplication,
division and modulus in C programs.
 The following table shows all the relational operators supported by C
Relational Operators
language. Assume variable A holds 10 and variable B holds 20 then:
Logical Operators
Following table shows all the logical operators
supported by C language. Assume variable A holds 1
and variable B holds 0, then:
Increment and decrements operator:
Increment Operators are used to increased the value of the variable
by one and Decrement Operators are used to decrease the value of
the variable by one in C programs.
Syntax
++ // increment operator
 -- // decrement operator
And can not apply on constant
x= 4++;
// gives error, because 4 is constant
Type of Increment Operator
pre-increment
post-increment
pre-increment (++ variable)
In pre-increment first increment the value of variable and then used
inside the expression (initialize into another variable).
Syntax: ++ variable;
Example:
#include<stdio.h>
#include<conio.h>

int main() Output:


{ x: 11
i: 11
int x,i;
i=10;
x=++i;
printf("x: %d\n",x);
printf("i: %d\n",i);
getch();
}

In above program first increase the value of i and then used value of i into
expression.
Contd…post-increment
In post-increment first(variable ++)
value of variable is used in the expression
(initialize into another variable) and then increment the value of
variable.
Syntax: variable ++;
#include<stdio.h>
#include<conio.h> Output:
int main() x: 10
{ i: 11
int x,i;
i=10;
x=i++;
printf("x: %d\n",x);
printf("i: %d\n",i);
getch();
}
In above program first used the value of i into expression then increase value of i
by 1.
Decrement Operator
Type of Decrement Operator
pre-decrement
post-decrement
Pre-decrement (-- variable)
In pre-decrement first decrement the value of variable and then used inside the
expression (initialize into another variable).
Syntax: -- variable;

#include<stdio.h>
#include<conio.h> Output:
int main() x: 9
{ i: 9
int x,i;
i=10;
x=--i;
printf("x: %d\n",x);
printf("i: %d\n",i);
getch();
}

In above program first decrease the value of i and then value of i used in expression.
Contd…post-decrement (variable --)
In Post-decrement first value of variable is used in the expression
(initialize into another variable) and then decrement the value of
variable.
Syntax: variable --;
#include<stdio.h>
Output:
#include<conio.h> x: 10
int main() i: 9
{
int x,i;
i=10;
x=i--;
printf("x: %d\n",x);
printf("i: %d\n",i);
getch();
}

In above program first used the value of x in expression then decrease value of i
by 1.
#include<stdio.h>
Example of increment and decrement operator

#include<conio.h>
int main() Output:
x: 0
{
int x,a,b,c;
a = 2;
b = 4;
c = 5;
x = a-- + b++ - ++c;
printf("x: %d",x);
getch();
}
Programming 8051 microcontroller in C
Programming Languages
C Programming
Data types in C
Software compiler for microcontroller
Use of Keil Microvision
IDE of Keil Microvision
First C Program
Using 8051 I/O ports
Create a project in keil microvision for 8051 microcontroller
Create a project in keil microvision for 8051 microcontroller
First we create a new file:
Create a project in keil microvision for 8051 microcontroller

Write an embedded c code:


Create a project in keil microvision for 8051 microcontroller

And then save it i.e Hello.c


Create a project in keil microvision for 8051 microcontroller

And on add new item


Create a project in keil microvision for 8051 microcontroller

And choose your file i.e Hello.c then close


Create a project in keil microvision for 8051 microcontroller
Now the file Hello.c visible and then build it but it is not
created hex file
Create a project in keil microvision for 8051 microcontroller
Now click on option for target
Create a project in keil microvision for 8051 microcontroller
New windows open like below put the clock frequency like 12
MHz in target section.
Create a project in keil microvision for 8051 microcontroller
In the output tab check on create a hex file and then build it.
After that go your location and check for hex file in object folder
or download the hex file in microcontroller and see the output.
THANK YOU

You might also like