23. DIFFERENCE BETWEEN C AND
EMBEDDED C
Compilers for C (ANSI C) typically generate OS dependant
executables. Embedded C requires compilers to create files to be downloaded
to the microcontrollers/microprocessors where it needs to run. Embedded
compilers give access to all resources which is not provided in compilers for
desktop computer applications.
23
24. DIFFERENCE BETWEEN C AND
EMBEDDED C
C is used for desktop computers, while embedded C is for microcontroller
based applications. Accordingly, C has the luxury to use resources of a desktop
PC like memory, OS, etc. While programming on desktop systems, we need
not bother about memory. However, embedded C has to use with the limited
resources (RAM, ROM, I/Os) on an embedded processor. Thus, program code
must fit into the available program memory. If code exceeds the limit, the
system is likely to crash.
24
25. DIFFERENCE BETWEEN C AND
EMBEDDED C
Embedded systems often have the real-time constraints, which is usually not
there with desktop computer applications.
Embedded systems often do not have a console, which is available in case of
desktop applications.
So, what basically is different while programming with embedded C is the
mindset; for embedded applications, we need to optimally use the resources,
make the program code efficient, and satisfy real time constraints, if any. All
this is done using the basic constructs, syntaxes, and function libraries of ‘C’.
25
30. Why Change to C
C is much more flexible than other high-level programming languages:
• C is a structured language.
• C is a relatively small language.
• C has very loose data typing.
• C easily supports low-level bit-wise data manipulation.
• C is sometimes referred to as a “high-level assembly language”.
► When compared to assembly language programming:
• Code written in C can be more reliable.
• Code written in C can be more scalable.
• Code written in C can be more portable between different platforms.
• Code written in C can be easier to maintain.
• Code written in C can be more productive
30
33. 2.memory-mapped devices
Documenting the source code is helpful not only for your
future reference but for those who come after you. For
instance, if you're working on an embedded system, you
need to have a memory map indicating where all the
memory-mapped devices can be found. Listing 8 shows
an example of a memory map.
33
34. Review: The “super loop” software
architecture
Problem
What is the minimum software environment you need to create an
embedded C program?
Solution
34
35. Review: An introduction to schedulers
Many embedded systems must carry out tasks at particular instants
of time. More specifically, we have two kinds of activity to
perform:
• Periodic tasks, to be performed (say) once every 100 ms,
and - less commonly -
• One-shot tasks, to be performed once after a delay of (say)
50 ms.
35
38. Header File
Each .h file should be “stand alone”
▫ It should declare, #define, and typedef anything needed by prototypes and
include any .h files it needs to avoid compiler errors
In our example prototypes for CircleArea() and Circumference are placed in
circleUtils.h ▫ circleUtils.h included in circleUtils.c ▫ circleUtils.h included in any
other .c file that uses CircleArea()
38
41. Separate Compilation
If code is separated into multiple .c files
▫ Must compile each .c file
▫ Combine resulting .o files to create executable
41
43. Scope/Lifetime
Variable “scope” refers to part of the program
that may access the variable
▫ Local, global, etc…
• Variable “lifetime” refers to time in which a
variable occupies memory
• Both determined by how and where variable is
defined
43
44. Storage classes
In C language, each variable has a storage class which decides scope, visibility
and lifetime of that variable. The following storage classes are most oftenly
used in C programming,
Automatic variables
External variables
Static variables
Register variables
44
45. Automatic variables
A variable declared inside a function without any storage class specification, is by
default an automatic variable. They are created when a function is called and are
destroyed automatically when the function exits. Automatic variables can also be
called local variables because they are local to a function. By default they are
assigned garbage value by the compiler.
45
46. External or Global variable
A variable that is declared outside any function is a Global
variable. Global variables remain available throughout the entire program.
One important thing to remember about global variable is that their values
can be changed by any function in the program.
46
Here the global variable number is available to all three
functions.
47. extern keyword
The extern keyword is used before a variable to inform the compiler that this
variable is declared somewhere else.
The extern declaration does not allocate storage for variables.
47
50. Static variables
A static variable tells the compiler to persist the variable until the end of
program. Instead of creating and destroying a variable every time when it
comes into and goes out of scope, static is initialized only once and remains
into existence till the end of program. A static variable can either be internal or
external depending upon the place of declaraction. Scope of internal
static variable remains inside the function in which it is defined. External
static variables remain restricted to scope of file in each they are declared.
They are assigned 0 (zero) as default value by the compiler.
50
52. Register variable
Register variable inform the compiler to store the variable in register instead
of memory. Register variable has faster access than normal variable.
Frequently used variables are kept in register. Only few variables can be
placed inside register.
NOTE : We can never get the address of such variables.
Syntax :
52
57. #pragma
The #pragma directive gives special instructions to the compiler. The #pragma
directive is especially useful in embedded C programming and can tell the
compiler to allocate a certain variable in RAM or EEPROM. It can also tell the
compiler to insert a snippet of assembly language code.
The GNU GCC compiler, which is a popular compiler for various embedded
architectures such as ARM and AVR, also uses attributes as an alternative
syntax to the #pragma directive.
57
#pragma GCC dependency
allows you to check the relative dates of the current file and another file. If the other file is more recent than the current file, a warning is issued.
This is useful if the current file is derived from the other file,
and should be regenerated. The other file is searched for using the normal include search path.
Optional trailing text can be used to give more information in the warning message.
58. C Startup
It is not possible to directly execute C code, when the processor comes out of
reset. Since, unlike assembly language, C programs need some basic pre-
requisites to be satisfied. This section will describe the pre-requisites and how
to meet the pre-requisites.
We will take the example of C program that calculates the sum of an array as
an example. And by the end of this section, we will be able to perform the
necessary setup, transfer control to the C code and execute it.
58
60. Before transferring control to C code, the
following have to be setup correctly.
Stack
Global variables
Initialized
Uninitialized
Read-only data
60
61. Stack
C uses the stack for storing local (auto)
variables, passing function arguments,
storing return address, etc. So it is
essential that the stack be setup
correctly, before transferring control to
C code.
Stacks are highly flexible in the ARM
architecture, since the implementation
is completely left to the software.
61
62. Stack 62
So all that has to be done in the startup code is to point r13 at the highest RAM
address, so that the stack can grow downwards (towards lower addresses).
For the connex board this can be acheived using the following ARM
instruction.
63. Global Variables
When C code is compiled, the compiler places initialized global variables in the
.data section. So just as with the assembly, the .data has to be copied from
Flash to RAM.
The C language guarantees that all uninitialized global variables will be
initialized to zero. When C programs are compiled, a separate section called
.bss is used for uninitialized variables. Since the value of these variables are all
zeroes to start with, they do not have to be stored in Flash. Before
transferring control to C code, the memory locations corresponding to these
variables have to be initialized to zero.
63
64. Read-only Data
GCC places global variables marked as const in a separate section, called
.rodata. The .rodata is also used for storing string constants.
Since contents of .rodata section will not be modified, they can be placed in
Flash. The linker script has to modified to accomodate this.
64
67. The startup code has the following parts 67
1.exception vectors
2.code to copy the .data from Flash to RAM
3.code to zero out the .bss
4.code to setup the stack pointer
5.branch to main
70. Introduction to Data Structures
Data Structure is a way of collecting and organising data in such a way that we
can perform operations on these data in an effective way
70
71. Basic types of Data Structures
anything that can store data can be called as a data strucure, hence Integer,
Float, Boolean, Char etc, all are data structures. They are known as Primitive
Data Structures.
Then we also have some complex Data Structures, which are used to store
large and connected data. Some example of Abstract Data Structure are :
Linked List
Tree
Graph
Stack, Queue etc.
All these data structures allow us to perform different operations on data. We
select these data structures based on which type of operation is required
71
73. Stacks
Stack is an abstract data type with a bounded(predefined) capacity. It is a
simple data structure that allows adding and removing elements in a particular
order. Every time an element is added, it goes on the top of the stack, the only
element that can be removed is the element that was at the top of the stack,
just like a pile of objects.
73
74. Basic features of Stack
Stack is an ordered list of similar data type.
Stack is a LIFO structure. (Last in First out).
push() function is used to insert new elements into the Stack and pop() is used
to delete an element from the stack. Both insertion and deletion are allowed
at only one end of Stack called Top.
Stack is said to be in Overflow state when it is completely full and is said to be
in Underflow state if it is completely empty.
74
75. Applications of Stack
The simplest application of a stack is to reverse a word. You push a given word
to stack - letter by letter - and then pop letters from the stack.
75
76. Implementation of Stack
Stack can be easily implemented using an Array or a Linked List. Arrays are
quick, but are limited in size and Linked List requires overhead to allocate, link,
unlink, and deallocate, but is not limited in size. Here we will implement Stack
using array.
76
86. Status of Stack
Position of Top Status of Stack
-1 Stack is Empty
0 Only one element in Stack
N-1 Stack is Full
N Overflow state of Stack
86
87. Basic Operations
Stack operations may involve initializing the stack, using it and then de-
initializing it. Apart from these basic stuffs, a stack is used for the following
two primary operations −
push() − pushing (storing) an element on the stack.
pop() − removing (accessing) an element from the stack.
When data is PUSHed onto stack.
To use a stack efficiently we need to check status of stack as well. For the
same purpose, the following functionality is added to stacks −
peek() − get the top data element of the stack, without removing it.
isFull() − check if stack is full.
isEmpty() − check if stack is empty.
87
89. PUSH Operation 89
The process of putting a new data element onto stack is known as PUSHOperation. Push operation involves series of steps −
•Step 1 − Check if stack is full.
•Step 2 − If stack is full, produce error and exit.
•Step 3 − If stack is not full, increment top to point next empty space.
•Step 4 − Add data element to the stack location, where top is pointing.
•Step 5 − return success.
if linked-list is used to implement stack, then in step 3, we need to allocate space dynamically.
90. PUSH Operation 90
void push(int data)
{
if(!isFull())
{ top = top + 1;
stack[top] = data;
}else {
printf("Could not insert data, Stack is full.n");
}
}
91. Pop Operation 91
A POP operation may involve the following steps −
•Step 1 − Check if stack is empty.
•Step 2 − If stack is empty, produce error and exit.
•Step 3 − If stack is not empty, access the data element at which top is pointing.
•Step 4 − Decrease the value of top by 1.
•Step 5 − return success.
94. Queue Data Structures
Queue is also an abstract data type or a linear data structure, in which the first element
is inserted from one end called REAR(also called tail), and the deletion of exisiting
element takes place from the other end called asFRONT(also called head). This makes
queue as FIFO data structure, which means that element inserted first will also be
removed first.
The process to add an element into queue is called Enqueue and the process of
removal of an element from queue is called Dequeue.
94
95. Queue
Queue is an abstract data structure, somewhat similar to Stack. In contrast to
Queue, queue is opened at both end. One end is always used to insert data
(enqueue) and the other is used to remove data (dequeue). Queue follows
First-In-First-Out methodology, i.e., the data item stored first will be accessed
first.
95
96. Queue
Same as Queue, queue can also be implemented using Array,
Linked-list, Pointer and Structures. For the sake of simplicity we
shall implement queue using one-dimensional array.
96
97. Queue Basic Operations
Queue operations may involve initializing or defining the queue, utilizing it and
then completing erasing it from memory. Here we shall try to understand basic
operations associated with queues −
enqueue() − add (store) an item to the queue.
dequeue() − remove (access) an item from the queue.
Few more functions are required to make above mentioned queue operation
efficient. These are −
peek() − get the element at front of the queue without removing it.
isfull() − checks if queue is full.
isempty() − checks if queue is empty.
In queue, we always dequeue (or access) data, pointed by front pointer and while
enqueing (or storing) data in queue we take help of rear pointer.
97
123. Enqueue Operation
Step 1 − Check if queue is full.
Step 2 − If queue is full, produce overflow error and exit.
Step 3 − If queue is not full, increment rear pointer to point next empty space.
Step 4 − Add data element to the queue location, where rear is pointing.
Step 5 − return success.
123
125. Dequeue Operation
Step 1 − Check if queue is empty.
Step 2 − If queue is empty, produce underflow error and exit.
Step 3 − If queue is not empty, access data where frontis pointing.
Step 3 − Increment front pointer to point next available data element.
Step 5 − return success.
125
126. Data Structure - Linked List
A linked-list is a sequence of data structures which are connected together via
links.
Link − Each Link of a linked list can store a data called an element.
Next − Each Link of a linked list contain a link to next link called Next.
LinkedList − A LinkedList contains the connection link to the first Link called
First.
Linked list can be visualized as a chain of nodes, where every node points to
the next node.
126
127. Data Structure - Linked List
As per above shown illustration, following are the important points to be
considered.
LinkedList contains an link element called first.
Each Link carries a data field(s) and a Link Field called next.
Each Link is linked with its next link using its next link.
Last Link carries a Link as null to mark the end of the list
127
128. Types of Linked List
Simple Linked List − Item Navigation is forward only.
Doubly Linked List − Items can be navigated forward and backward way.
Circular Linked List − Last item contains link of the first element as next and
and first element has link to last element as prev.
128
129. Basic Operations
Insertion − add an element at the beginning of the list.
Deletion − delete an element at the beginning of the list.
Display − displaying complete list.
Search − search an element using given key.
Delete − delete an element using given key.
129
133. Data Structure - Doubly Linked List
Doubly Linked List is a variation of Linked list in which navigation is possible in
both ways either forward and backward easily as compared to Single Linked
List
Doubly LinkedList contains an link element called first and last.
Each Link carries a data field(s) and a Link Field called next.
Each Link is linked with its next link using its next link.
Each Link is linked with its previous link using its prev link.
Last Link carries a Link as null to mark the end of the list.
133
134. Singly Linked List as Circular
In singly linked list, the next pointer of the last node points to the first node.
134
135. Doubly Linked List as Circular
n doubly linked list, the next pointer of the last node points to the first node
and the previous pointer of the first node points to the last node making the
circular in both directions.
135
136. Dynamic Linked Lists
Problem Statement
Consider Students Database program, it appears that the program uses (realloc)
when
adding or deleting student member. Using (realloc) may solve the problem,
especially if
the structure size and the number of records are small.
Actually (realloc) function
1. Creates a new buffer with the new size
2. Copies the original contents
3. Deletes the original buffer
4. Returns the address of the new buffer
Consider a complicated SStudent structure containing all student information and
his courses
degrees as shown below:
136
137. Dynamic Linked Lists Contn. 137
Above structure size is 8548 byte, if it is required to build a
program that supports up to
10,000 student. This means adding extra student will cost
transfering following data size
inside the computer:
10000 * 8548 = 85,480,000 Byte
If it is required to transfere 1 byte 1 micosecond the above
addition operation will take 85
second or 1.5 minute. This time is very long.
138. Understanding the Solution
Another techniqe is used, it depends on storing student information in a
separte buffers and
linking between them using a pointers. This techniqe called the Linked List
method.
Assument the new structure SStudent after adding the member (SStudent
*pNextStudent). pNextStudent is a pointer containing the address of the next
member of the list. Last member of the last have equals pNextStudent NULL.
138
140. Write the Program 140
At the beginning of the program only it is required to have one empty pointer,
indicating that
there is no students added.